From 9b4d74f073430dcd6806991de9b5d267bf2cdbde Mon Sep 17 00:00:00 2001 From: kuba Date: Sun, 15 Nov 2026 01:42:42 +0000 Subject: [PATCH 001/178] [Agc] Native stubs for sceAgcDcbDrawIndexIndirect and sceAgcDcbDrawIndirect DrawIndexIndirect writes its five dwords and the cursor in one TryEmitCommandDwords round instead of an allocation plus four writes. The modifier's user-SGPR slot decode moves into AgcExports.IndexIndirectRegisterLocations (shared by DrawIndirect, DrawIndexIndirect and DrawIndexIndirectMulti) and the packet stub encodes the same slots through a new ModifierSgprSlots word kind; DrawInitiator now ORs in its constant. The randomized stub-vs-export test covers both builders with modifiers built to hit stages 3/5 against the others and bits 0, 1, 2, 8 and 32. Co-Authored-By: Claude --- .../Native/DirectExecutionBackend.FastPath.cs | 86 ++++++++++++++++++ .../Agc/AgcExports.DrawPackets.cs | 89 +++++++++---------- .../Agc/AgcExports.PacketStubs.cs | 47 +++++++++- .../Cpu/AgcPacketStubTests.cs | 70 ++++++++++++++- 4 files changed, 242 insertions(+), 50 deletions(-) diff --git a/src/SharpEmu.Core/Cpu/Native/DirectExecutionBackend.FastPath.cs b/src/SharpEmu.Core/Cpu/Native/DirectExecutionBackend.FastPath.cs index d0008b132..06acad057 100644 --- a/src/SharpEmu.Core/Cpu/Native/DirectExecutionBackend.FastPath.cs +++ b/src/SharpEmu.Core/Cpu/Native/DirectExecutionBackend.FastPath.cs @@ -708,6 +708,57 @@ void EmitPart(SharpEmu.Libs.Agc.AgcPacketStubPart part, bool intoR11) } } + // One AgcModifierSgprSlot into r10d, r11d the temporary (AgcExports.IndexIndirectRegisterLocations). + void EmitModifierSlot(SharpEmu.Libs.Agc.AgcModifierSgprSlot slot) + { + if (slot.EnableMask == 0 || slot.FieldShift is < -1 or > 27 || slot.ShiftLeft is < 0 or > 31) + { + throw new ArgumentException("Unsupported modifier slot.", nameof(spec)); + } + + var source = (byte)slot.Register; + var rex = (byte)(0x40 | (source >= 8 ? 0x04 : 0) | 0x01); + // test reg32, mask / jz disabled + if (source >= 8) + { + Emit(0x41); + } + + Emit(0xF7, (byte)(0xC0 | (source & 7))); EmitImm32(slot.EnableMask); + Emit(0x74, 0); + var disabledFixup = code.Count - 1; + if (slot.FieldShift < 0) + { + Emit(0x41, 0xBA); EmitImm32(1); // mov r10d, 1 + } + else + { + Emit(rex, 0x89, (byte)(0xC0 | ((source & 7) << 3) | 3)); // mov r11d, reg32 + Emit(0x41, 0xC1, 0xEB, 29); // shr r11d, 29 the stage + Emit(0x41, 0xBA); EmitImm32(0x28); // mov r10d, 0x28 stages 3 and 5 + Emit(0x45, 0x0F, 0xA3, 0xDA); // bt r10d, r11d + Emit(0x45, 0x19, 0xD2); // sbb r10d, r10d -1 for stages 3 and 5 + Emit(0x41, 0x81, 0xE2); EmitImm32(0x80); // and r10d, 0x80 + Emit(0x41, 0x81, 0xC2); EmitImm32(0x8C); // add r10d, 0x8C the stage's base + Emit(rex, 0x89, (byte)(0xC0 | ((source & 7) << 3) | 3)); // mov r11d, reg32 + if (slot.FieldShift != 0) + { + Emit(0x41, 0xC1, 0xEB, checked((byte)slot.FieldShift)); // shr r11d, n + } + + Emit(0x41, 0x83, 0xE3, 0x1F); // and r11d, 0x1F + Emit(0x45, 0x01, 0xDA); // add r10d, r11d + } + + Emit(0xEB, 0x06); // jmp done + code[disabledFixup] = checked((byte)(code.Count - (disabledFixup + 1))); + Emit(0x41, 0xBA); EmitImm32(slot.Disabled); // disabled: mov r10d, imm32 + if (slot.ShiftLeft != 0) + { + Emit(0x41, 0xC1, 0xE2, checked((byte)slot.ShiftLeft)); // done: shl r10d, n + } + } + for (var index = 0; index < spec.Words.Length; index++) { var word = spec.Words[index]; @@ -755,9 +806,44 @@ void EmitPart(SharpEmu.Libs.Agc.AgcPacketStubPart part, bool intoR11) Emit(0x41, 0xF7, 0xC3); EmitImm32(1); // test r11d, 1 Emit(0x74, 0x03); // jz +3 Emit(0x45, 0x31, 0xD2); // xor r10d, r10d + if (word.Constant != 0) + { + Emit(0x41, 0x81, 0xCA); EmitImm32(word.Constant); // or r10d, imm32 + } + break; } + case SharpEmu.Libs.Agc.AgcPacketStubWordKind.ModifierSgprSlots: + { + // Each slot is computed into r10d (r11d the temporary) and stored, or ORed, into + // the packet dword itself: the stage base needs both scratch registers. + if (word.Slots.Length == 0) + { + throw new ArgumentException("A modifier-slot word needs a slot.", nameof(spec)); + } + + for (var slotIndex = 0; slotIndex < word.Slots.Length; slotIndex++) + { + EmitModifierSlot(word.Slots[slotIndex]); + if (slotIndex == 0) + { + Emit(0x44, 0x89, 0x50, displacement); // mov [rax+disp], r10d + } + else + { + Emit(0x44, 0x09, 0x50, displacement); // or [rax+disp], r10d + } + } + + if (word.Constant != 0) + { + Emit(0x81, 0x48, displacement); EmitImm32(word.Constant); // or dword [rax+disp], imm32 + } + + continue; + } + default: throw new ArgumentOutOfRangeException(nameof(spec), word.Kind, "Unknown packet word kind."); } diff --git a/src/SharpEmu.Libs/Agc/AgcExports.DrawPackets.cs b/src/SharpEmu.Libs/Agc/AgcExports.DrawPackets.cs index 3a1194bab..bef4d6ab4 100644 --- a/src/SharpEmu.Libs/Agc/AgcExports.DrawPackets.cs +++ b/src/SharpEmu.Libs/Agc/AgcExports.DrawPackets.cs @@ -215,20 +215,8 @@ public static int DcbDrawIndirect(CpuContext ctx) return ReturnPointer(ctx, 0); } - var modifierBits = (uint)drawModifier; - var shaderStage = modifierBits >> 29; - var scalarRegisterBase = shaderStage is 3 or 5 ? 0x10Cu : 0x8Cu; - var firstVertexRegister = (modifierBits & 1u) != 0 - ? scalarRegisterBase + ((modifierBits >> 9) & 0x1Fu) - : 0x280u; - var firstInstanceRegister = (modifierBits & 4u) != 0 - ? scalarRegisterBase + ((modifierBits >> 19) & 0x1Fu) - : 0x280u; - var drawInitiator = (drawModifier & (1UL << 32)) != 0 - ? 2u - : ((modifierBits >> 3) & 0x20u) | 2u; - - if (!TryEmitCommandDwords(ctx, commandBufferAddress, out var drawCommand, Pm4(5, ItDrawIndirect, 0), dataOffset, firstVertexRegister, firstInstanceRegister, drawInitiator)) + var registerLocations = DrawIndirectRegisterLocations(drawModifier); + if (!TryEmitCommandDwords(ctx, commandBufferAddress, out var drawCommand, Pm4(5, ItDrawIndirect, 0), dataOffset, (uint)registerLocations, (uint)(registerLocations >> 32), IndirectDrawInitiator(drawModifier))) { var rejects = Interlocked.Increment(ref _indirectDrawEmitRejectCount); if (rejects <= 8 || rejects % 250 == 0) @@ -289,28 +277,12 @@ public static int DcbDrawIndexIndirect(CpuContext ctx) var commandBufferAddress = ctx[CpuRegister.Rdi]; var dataOffset = (uint)ctx[CpuRegister.Rsi]; var modifier = ctx[CpuRegister.Rdx]; - var modifierBits = (uint)modifier; - var shaderStage = modifierBits >> 29; - var scalarRegisterBase = shaderStage 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); - } - - // The API modifier selects register locations; it is not a packet initiator. - var drawInitiator = (modifier & (1UL << 32)) != 0 - ? 2u : ((modifierBits >> 3) & 0x20u) | 2u; + var registerLocations = IndexIndirectRegisterLocations(modifier); + // The API modifier selects register locations; it is not a packet initiator. The packet and + // the cursor are one guest write (AgcPacketStubTests runs the native stub against this). if (commandBufferAddress == 0 || - !TryAllocateCommandDwords(ctx, commandBufferAddress, 5, out var commandAddress) || - !TryWriteUInt32(ctx, commandAddress, Pm4(5, ItDrawIndexIndirect, 0)) || - !TryWriteUInt32(ctx, commandAddress + 4, dataOffset) || - !ctx.TryWriteUInt64(commandAddress + 8, registerLocations) || - !TryWriteUInt32(ctx, commandAddress + 16, drawInitiator)) + !TryEmitCommandDwords(ctx, commandBufferAddress, out var commandAddress, + Pm4(5, ItDrawIndexIndirect, 0), dataOffset, (uint)registerLocations, (uint)(registerLocations >> 32), IndirectDrawInitiator(modifier))) { return ReturnPointer(ctx, 0); } @@ -337,18 +309,8 @@ public static int DcbDrawIndexIndirectMulti(CpuContext ctx) !TryReadUInt64(ctx, ctx[CpuRegister.Rsp] + sizeof(ulong), out var modifier)) return ReturnPointer(ctx, 0); - var modifierBits = (uint)modifier; - var shaderStage = modifierBits >> 29; - var scalarRegisterBase = shaderStage 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); - var drawInitiator = (modifier & (1UL << 32)) != 0 - ? 2u : ((modifierBits >> 3) & 0x20u) | 2u; + var registerLocations = IndexIndirectRegisterLocations(modifier); + var drawInitiator = IndirectDrawInitiator(modifier); if (commandBufferAddress == 0 || !TryAllocateCommandDwords(ctx, commandBufferAddress, 10, out var commandAddress) || @@ -462,5 +424,38 @@ 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). + /// + 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; + } + + /// The first-vertex and first-instance locations of a non-indexed indirect draw (no draw-index slot). + public static ulong DrawIndirectRegisterLocations(ulong modifier) => + IndexIndirectRegisterLocations(modifier & ~2UL); + + /// An indirect draw's initiator: 2, plus bit 5 from modifier bit 8 unless bit 32 is set. + public static uint IndirectDrawInitiator(ulong modifier) => + (modifier & (1UL << 32)) != 0 ? 2u : (((uint)modifier >> 3) & 0x20u) | 2u; + private static long _indirectDrawEmitRejectCount; } diff --git a/src/SharpEmu.Libs/Agc/AgcExports.PacketStubs.cs b/src/SharpEmu.Libs/Agc/AgcExports.PacketStubs.cs index 3c85dec6e..eac1a3618 100644 --- a/src/SharpEmu.Libs/Agc/AgcExports.PacketStubs.cs +++ b/src/SharpEmu.Libs/Agc/AgcExports.PacketStubs.cs @@ -25,12 +25,31 @@ public enum AgcPacketStubWordKind : byte /// /// The draw initiator of a modifier in the first part's register: 0 when bit 32 is set, else - /// ((uint)modifier >> 3) & 0x20. + /// ((uint)modifier >> 3) & 0x20; the constant is ORed in either way. /// DrawInitiator, + + /// + /// The OR of the word's and the constant: the user-SGPR + /// locations an indirect draw's modifier selects (see AgcExports.IndexIndirectRegisterLocations). + /// + ModifierSgprSlots, } -public sealed record AgcPacketStubWord(uint Constant, AgcPacketStubPart[] Parts, AgcPacketStubWordKind Kind = AgcPacketStubWordKind.Parts); +/// +/// 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. +/// +public readonly record struct AgcModifierSgprSlot(AgcStubRegister Register, uint EnableMask, int FieldShift, uint Disabled, int ShiftLeft); + +public sealed record AgcPacketStubWord(uint Constant, AgcPacketStubPart[] Parts, AgcPacketStubWordKind Kind = AgcPacketStubWordKind.Parts) +{ + /// The slots of a word. + public AgcModifierSgprSlot[] Slots { get; init; } = []; +} /// /// A command builder whose whole effect is "append these dwords at the command buffer's cursor and @@ -66,6 +85,20 @@ private static AgcPacketStubWord Arg(AgcStubRegister register, int shiftRight = private static AgcPacketStubWord DrawInitiatorOfRcx() => new(0, [new AgcPacketStubPart(AgcStubRegister.Rcx, 0, 0xFFFF_FFFFu, 0)], AgcPacketStubWordKind.DrawInitiator); + 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); + + // IndirectDrawInitiator of rdx. + private static AgcPacketStubWord IndirectDrawInitiatorOfRdx() => + new(2, [new AgcPacketStubPart(AgcStubRegister.Rdx, 0, 0xFFFF_FFFFu, 0)], AgcPacketStubWordKind.DrawInitiator); + // The leaf builders that append one fixed-shape packet, by NID. Each entry mirrors its export's // TryEmitCommandDwords call word for word (AgcPacketStubTests runs each stub against its export). private static readonly Dictionary PacketStubSpecs = new() @@ -104,6 +137,16 @@ private static AgcPacketStubWord DrawInitiatorOfRcx() => Const(Pm4(6, ItDrawIndex2, 0)), Arg(AgcStubRegister.Rsi), Arg(AgcStubRegister.Rdx), Arg(AgcStubRegister.Rdx, 32), Arg(AgcStubRegister.Rsi), DrawInitiatorOfRcx(), ]), + ["t1vNu082-jM"] = new(5, 0, // sceAgcDcbDrawIndexIndirect + [ + Const(Pm4(5, ItDrawIndexIndirect, 0)), Arg(AgcStubRegister.Rsi), + Slots(BaseVertexSlot, DrawIndexSlot), Slots(FirstInstanceSlot, DrawIndexFlagSlot), IndirectDrawInitiatorOfRdx(), + ]), + ["1q1titRBL6o"] = new(5, 0, // sceAgcDcbDrawIndirect + [ + Const(Pm4(5, ItDrawIndirect, 0)), Arg(AgcStubRegister.Rsi), + Slots(BaseVertexSlot), Slots(FirstInstanceSlot), IndirectDrawInitiatorOfRdx(), + ]), ["k3GhuSNmBLU"] = new(5, 0, // sceAgcCbDispatch [ Const(Pm4(5, ItDispatchDirect, 0)), Arg(AgcStubRegister.Rsi), Arg(AgcStubRegister.Rdx), Arg(AgcStubRegister.Rcx), diff --git a/tests/SharpEmu.Libs.Tests/Cpu/AgcPacketStubTests.cs b/tests/SharpEmu.Libs.Tests/Cpu/AgcPacketStubTests.cs index f60acbe66..3c258b50c 100644 --- a/tests/SharpEmu.Libs.Tests/Cpu/AgcPacketStubTests.cs +++ b/tests/SharpEmu.Libs.Tests/Cpu/AgcPacketStubTests.cs @@ -29,8 +29,31 @@ public static IEnumerable Nids() => { "pFLArOT53+w", "LHFXRrlTPD8", "w4-d0n60hdo", "-HOOCn0JY48", "ZvwO9euwYzc", "hvUfkUIQcOE", "tSBxhAPyytQ", "8N2tmT3jmC8", "GIIW2J37e70", "l4fM9K-Lyks", "Yw0jKSqop+E", "B+aG9DUnTKA", "q88lQ+GP5Yk", "k3GhuSNmBLU", + IndexIndirectNid, DrawIndirectNid, }.Select(nid => new object[] { nid }); + // sceAgcDcbDrawIndexIndirect / sceAgcDcbDrawIndirect: rdx is a draw modifier whose slots the stub decodes. + private const string IndexIndirectNid = "t1vNu082-jM"; + private const string DrawIndirectNid = "1q1titRBL6o"; + + // A draw modifier that covers every branch of the slot decode on purpose: stages 3 and 5 against + // the others, each of bits 0, 1 and 2, bit 8 (the initiator) and bit 32 (which clears it), with + // random fields and high bits. + private static ulong DrawModifier(System.Random random) + { + var low = (uint)random.NextInt64(0, 1L << 32); + var stage = random.Next(4) switch { 0 => 3u, 1 => 5u, _ => (uint)random.Next(8) }; + low = (low & 0x1FFF_FFF8u) | (stage << 29) | (uint)random.Next(8); + var high = random.Next(4) switch + { + 0 => 0u, + 1 => 1u, + 2 => (uint)random.NextInt64(0, 1L << 32) & ~1u, + _ => (uint)random.NextInt64(0, 1L << 32), + }; + return ((ulong)high << 32) | low; + } + [Theory] [MemberData(nameof(Nids))] public void TheStubWritesWhatTheExportWritesAndDeclinesWhereTheExportWouldCallBack(string nid) @@ -68,6 +91,10 @@ public void TheStubWritesWhatTheExportWritesAndDeclinesWhereTheExportWouldCallBa _ => -64, }; var arguments = new[] { Pick(), Pick(), Pick(), Pick() }; + if (nid is IndexIndirectNid or DrawIndirectNid && random.Next(4) != 0) + { + arguments[1] = DrawModifier(random); + } var nullBuffer = random.Next(25) == 0; using var managedBlock = new Block(); @@ -450,13 +477,54 @@ public void APatchStubIsInstalledOnlyWithItsExportAndBothSwitchesOn() Assert.False(DirectExecutionBackend.IsAgcStubAllowed("Ikfdt-rIqCE", packetStubsEnabled: true, patchStubsEnabled: true, all)); } + // The stub's slot decode is AgcExports.IndexIndirectRegisterLocations, which the exports use: + // the packet's two location dwords for every modifier, stage and flag combination. + [Fact] + public void TheIndirectDrawStubsEncodeTheExportsRegisterLocations() + { + if (!OperatingSystem.IsMacOS() || RuntimeInformation.ProcessArchitecture != Architecture.X64) + { + return; + } + + var random = new System.Random(0x1D1C); + foreach (var nid in new[] { IndexIndirectNid, DrawIndirectNid }) + { + Assert.True(AgcExports.TryGetPacketStubSpec(nid, out var spec)); + using var harness = new StubHarness(spec); + using var block = new Block(); + for (var iteration = 0; iteration < 4000; iteration++) + { + var modifier = DrawModifier(random); + block.Reset(0, 0x700, iteration); + block.Rebase(); + var rax = harness.Call((ulong)block.Pointer, 0x40, modifier, 0, 0); + Assert.Equal((ulong)(block.Pointer + PacketOffset), rax); + var packet = (uint*)(block.Pointer + PacketOffset); + var locations = nid == IndexIndirectNid + ? AgcExports.IndexIndirectRegisterLocations(modifier) + : AgcExports.DrawIndirectRegisterLocations(modifier); + Assert.Equal(0x40u, packet[1]); + Assert.Equal(locations, packet[2] | ((ulong)packet[3] << 32)); + Assert.Equal(AgcExports.IndirectDrawInitiator(modifier), packet[4]); + } + } + } + [Fact] public void EveryStubbedBuilderIsAlsoALeafBuilder() { foreach (var nid in Nids().Select(row => (string)row[0])) { - Assert.True(DirectExecutionBackend.IsAgcBuilderLeafImport(nid), nid); Assert.Equal(DirectExecutionBackend.GuestFastPathStub.AgcPacket, DirectExecutionBackend.ClassifyGuestFastPathStub(nid)); + // sceAgcDcbDrawIndirect is stubbed but not a leaf builder: its export logs every refusal, + // a leaf's decline included, so it stays on the full path when the stub declines. + if (nid == DrawIndirectNid) + { + continue; + } + + Assert.True(DirectExecutionBackend.IsAgcBuilderLeafImport(nid), nid); } Assert.True(DirectExecutionBackend.IsAgcBuilderLeafImport("n2fD4A+pb+g")); From 8840cfbb083b6b7441b0f133a6b72de51b82ae47 Mon Sep 17 00:00:00 2001 From: kuba Date: Sun, 15 Nov 2026 01:43:56 +0000 Subject: [PATCH 002/178] [Metal] Test owned pages a line at a time and read the completed serial once per resolution and per re-check On the resolving thread a word in a page that is not clean ran ConcurrentOwner twice, for the page and for the word, each able to take the image-cache lock, send for the completed serial and take the overlay locks; the worker's re-check of a resolution sent for the serial once per answer. Demon's Souls keeps a pending GPU write in its descriptor page, so each of the ~45 words a stage reads paid both tests. - A page found owned is remembered for the rest of the resolution (a ring beside the clean pages), and in it the 256-byte line of a read is tested before the read: a clean line is recorded once, like a clean page, and its words are read from it; only the words of an owned line are tested one by one. Every test is an overlap test, so a clean line is clean for every range inside it, and its answer is checked again at the take like any other. SHARPEMU_CONCURRENT_OWNED_LINES=0 restores the per-word page and word tests. - A resolution and a worker re-check each read the completed serial once, at their first test that needs it, as the worker's scoped serial (4e2e63f64) did for compute materializations. A serial only grows, so an older one reports more writes pending, never fewer: no answer becomes clean that would not be clean with a newer serial. SHARPEMU_CONCURRENT_SCOPED_SERIAL=0 sends at every test again. - The PERF prefetch section gains owner_tests=(page,line,word,recheck,image_locks,serial_reads, overlay_calls), counted per resolution or re-check and added to the host's totals once at its end. Bench (MetalClearFoldingTests.ConcurrentResolveCostOverAnOwnedDescriptorPage, SHARPEMU_BENCH_WORD_READS= 20000; 45 words over 4 lines of a page with one pending write, 250 live records; load 6.0): both off 11.22 us/resolve, 5.52 us/re-check; owned lines only 1.11 / 0.54; scoped serial only 10.97 / 5.07; both on 0.99 / 0.46. Co-Authored-By: Claude --- .../V2/MetalRenderHost.ConcurrentResolve.cs | 337 +++++++++++++++--- ...alClearFoldingTests.CrossDrawCleanPages.cs | 138 +++++++ .../MetalClearFoldingTests.WordReadBench.cs | 104 ++++++ .../Scenes/GpuWordNoWaitSceneTests.cs | 71 ++++ 4 files changed, 610 insertions(+), 40 deletions(-) create mode 100644 tests/SharpEmu.Gpu.Metal.Tests/MetalClearFoldingTests.WordReadBench.cs diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.ConcurrentResolve.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.ConcurrentResolve.cs index 9f67007b0..c7fa777ca 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.ConcurrentResolve.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.ConcurrentResolve.cs @@ -168,7 +168,7 @@ private string FormatPrefetchCounters() $"dispatch_saved_ms={computeSavedMs.ToString("F1", culture)}"; return $"resolved={resolved} abandoned={abandoned} abandoned_by=({TakeAbandonCauses()}) taken={taken} refused={refused} drains={drains} drained={drained} deferred_barriers={deferredBarriers} operand_reads_kept={operandReadsKept} " + $"wait_ms={waitMs.ToString("F1", culture)} resolve_ms={prefetch.TakeResolveMilliseconds().ToString("F1", culture)} " + - $"caller_jobs={callerResolves} caller_ms={callerMs.ToString("F1", culture)} claim_steals={prefetch.TakeClaimSteals()}{dispatches}{FormatPacketCounters()} {own}{TakeDrainCallers()}"; + $"caller_jobs={callerResolves} caller_ms={callerMs.ToString("F1", culture)} claim_steals={prefetch.TakeClaimSteals()}{dispatches}{FormatPacketCounters()} {own} {TakeOwnerTestCounters()}{TakeDrainCallers()}"; } private static string FormatProviderRefusals(long[] refused) => @@ -194,7 +194,115 @@ internal enum ConcurrentQuery : byte private static readonly bool ConcurrentWordLines = Environment.GetEnvironmentVariable("SHARPEMU_CONCURRENT_WORD_LINES") != "0"; - internal sealed class ConcurrentAssumptions((long Overlay, long Labels, ulong GpuWrites, long Images, long GpuModified) versions) + // SHARPEMU_CONCURRENT_OWNED_LINES=0 tests a page found owned again for every word read in it, then the word. + // A page found owned is remembered for the rest of the resolution (a ring beside the clean pages), and in it + // the 256-byte line of a word is tested before the word: a clean line is recorded once and its words are read + // from it, and only the words of an owned line are tested one by one. Demon's Souls keeps a pending GPU write + // in its descriptor page, so each of the ~45 words a stage reads paid a page test and a word test. + private static readonly bool ConcurrentOwnedLinesDefault = + SharpEmu.ShaderCompiler.PerfSwitches.Enabled("SHARPEMU_CONCURRENT_OWNED_LINES"); + + internal bool ConcurrentOwnedLines { get; set; } = ConcurrentOwnedLinesDefault; + + // SHARPEMU_CONCURRENT_SCOPED_SERIAL=0 asks the GPU for the completed serial (a message send) at every + // ownership test of a resolution and of the worker's re-check of one. With it on, a resolution and a re-check + // each read it once, at their first test that needs it. A serial only grows, so an older one reports more + // writes pending, never fewer: an answer it gives is owned where a newer serial may say clean, never the + // other way (the same argument as the worker's scoped serial, SHARPEMU_METAL_V2_SCOPED_SERIAL). + private static readonly bool ConcurrentScopedSerialDefault = + SharpEmu.ShaderCompiler.PerfSwitches.Enabled("SHARPEMU_CONCURRENT_SCOPED_SERIAL"); + + internal bool ConcurrentScopedSerial { get; set; } = ConcurrentScopedSerialDefault; + + // What an ownership test costs, counted where it runs (a resolution, a re-check) and added to the host's + // totals once per resolution or re-check, for the PERF line: owner_tests=(...). + internal enum OwnerTestCounter + { + Page, + Line, + Word, + Recheck, + ImageLock, + SerialRead, + OverlayCall, + } + + private static readonly string[] OwnerTestCounterNames = ["page", "line", "word", "recheck", "image_locks", "serial_reads", "overlay_calls"]; + + private readonly long[] _ownerTests = new long[OwnerTestCounterNames.Length]; + + /// + /// The serial the ownership tests of one resolution or one re-check use, and what they cost. Used by one + /// thread at a time. + /// + internal class ConcurrentOwnerScope + { + private readonly Func _signaled; + private ulong _serial; + private bool _serialKnown; + + public ConcurrentOwnerScope(Func signaled) + { + _signaled = signaled; + Serial = ReadSerial; + } + + // Read once per scope while Scoped is set; every call reads it again otherwise. + public bool Scoped; + + // The completed serial, for IsGpuWritePendingConcurrent and the overlays' Coverage. + public readonly Func Serial; + + public readonly long[] Counters = new long[OwnerTestCounterNames.Length]; + + public void Count(OwnerTestCounter counter) => Counters[(int)counter]++; + + // A new scope: the next test that needs the serial reads it. + public void ForgetSerial() => _serialKnown = false; + + private ulong ReadSerial() + { + if (Scoped && _serialKnown) + { + return _serial; + } + + Counters[(int)OwnerTestCounter.SerialRead]++; + _serial = _signaled(); + _serialKnown = true; + return _serial; + } + } + + // Adds a scope's counters to the host's totals and clears them. + private void FlushOwnerTests(ConcurrentOwnerScope scope) + { + var counters = scope.Counters; + for (var index = 0; index < counters.Length; index++) + { + if (counters[index] != 0) + { + Interlocked.Add(ref _ownerTests[index], counters[index]); + counters[index] = 0; + } + } + } + + internal string TakeOwnerTestCounters() + { + var builder = new System.Text.StringBuilder("owner_tests=("); + for (var index = 0; index < _ownerTests.Length; index++) + { + builder.Append(index == 0 ? string.Empty : ",").Append(OwnerTestCounterNames[index]).Append('=') + .Append(Interlocked.Exchange(ref _ownerTests[index], 0)); + } + + return builder.Append(')').ToString(); + } + + internal sealed class ConcurrentAssumptions( + (long Overlay, long Labels, ulong GpuWrites, long Images, long GpuModified) versions, Func signaled) + : ConcurrentOwnerScope(signaled) { public readonly List<(ConcurrentQuery Query, ulong Address, ulong Size, bool Owned)> Answers = new(); @@ -209,8 +317,19 @@ internal sealed class ConcurrentAssumptions((long Overlay, long Labels, ulong Gp ulong.MaxValue, ulong.MaxValue, ulong.MaxValue, ulong.MaxValue]; private int _nextCleanPage; - // The last line of a clean page read whole for word reads (TryReadGuestWordConcurrent): the words - // after it in the line are answered from it, under the clean-page answer already recorded. + // The last pages found owned (ConcurrentOwnedLines). Not an answer: nothing is recorded for them, and a + // read in one is answered by its line or by itself, as it would be after testing the page again. + private readonly ulong[] _ownedPages = [ulong.MaxValue, ulong.MaxValue, ulong.MaxValue, ulong.MaxValue]; + private int _nextOwnedPage; + + // The last lines of owned pages tested, each with its answer (LineOwnedBit): a clean one was recorded. + private const ulong LineOwnedBit = 2; + private readonly ulong[] _lines = [ulong.MaxValue, ulong.MaxValue, ulong.MaxValue, ulong.MaxValue, + ulong.MaxValue, ulong.MaxValue, ulong.MaxValue, ulong.MaxValue]; + private int _nextLine; + + // The last line of a clean page or a clean line read whole for word reads (TryReadGuestWordConcurrent): + // the words after it in the line are answered from it, under the clean answer already recorded. public ulong WordLine = ulong.MaxValue; public readonly byte[] WordLineBytes = new byte[ConcurrentWordLineBytes]; @@ -221,7 +340,41 @@ public void Reset((long Overlay, long Labels, ulong GpuWrites, long Images, long Versions = versions; Array.Fill(_cleanPages, ulong.MaxValue); _nextCleanPage = 0; + Array.Fill(_ownedPages, ulong.MaxValue); + _nextOwnedPage = 0; + Array.Fill(_lines, ulong.MaxValue); + _nextLine = 0; WordLine = ulong.MaxValue; + ForgetSerial(); + } + + public bool IsOwnedPage(ConcurrentQuery query, ulong page) => Array.IndexOf(_ownedPages, page | (ulong)query) >= 0; + + public void NoteOwnedPage(ConcurrentQuery query, ulong page) + { + _ownedPages[_nextOwnedPage] = page | (ulong)query; + _nextOwnedPage = (_nextOwnedPage + 1) & (_ownedPages.Length - 1); + } + + // Null when the line has not been tested in this resolution (or has left the ring). + public bool? LineOwned(ConcurrentQuery query, ulong line) + { + var key = line | (ulong)query; + foreach (var entry in _lines) + { + if ((entry & ~LineOwnedBit) == key) + { + return (entry & LineOwnedBit) != 0; + } + } + + return null; + } + + public void NoteLine(ConcurrentQuery query, ulong line, bool owned) + { + _lines[_nextLine] = line | (ulong)query | (owned ? LineOwnedBit : 0); + _nextLine = (_nextLine + 1) & (_lines.Length - 1); } public bool IsCleanPage(ConcurrentQuery query, ulong page) @@ -291,12 +444,17 @@ internal void BeginConcurrentResolve() var writeLogVersion = _gpuWrites.WriteLogVersion; if (pooled is null) { - _concurrentAssumptions = new ConcurrentAssumptions(OwnershipVersions()) { WriteLogVersion = writeLogVersion }; + _concurrentAssumptions = new ConcurrentAssumptions(OwnershipVersions(), _signaledSerialReader ??= SignaledSerial) + { + WriteLogVersion = writeLogVersion, + Scoped = ConcurrentScopedSerial, + }; return; } pooled.Reset(OwnershipVersions()); pooled.WriteLogVersion = writeLogVersion; + pooled.Scoped = ConcurrentScopedSerial; _concurrentAssumptions = pooled; } @@ -331,6 +489,7 @@ internal object EndConcurrentResolve() { var assumptions = _concurrentAssumptions ?? throw new InvalidOperationException("No concurrent resolution is open."); _concurrentAssumptions = null; + FlushOwnerTests(assumptions); return assumptions; } @@ -395,17 +554,43 @@ internal bool IsConcurrentResolveStillCurrent(object assumptionsObject) return true; } - foreach (var (query, address, size, owned) in assumptions.Answers) + // One serial for the whole re-check (ConcurrentScopedSerial): an older serial can only turn a clean + // answer owned, so a re-check that passes with it would pass with every newer one. + var scope = t_recheckScope; + if (scope is null || !ReferenceEquals(t_recheckHost, this)) + { + scope = t_recheckScope = new ConcurrentOwnerScope(_signaledSerialReader ??= SignaledSerial); + t_recheckHost = this; + } + + scope.Scoped = ConcurrentScopedSerial; + scope.ForgetSerial(); + try { - if (IsOwnedConcurrent(query, address, size) != owned) + foreach (var (_, address, size, owned) in assumptions.Answers) { - return false; + scope.Count(OwnerTestCounter.Recheck); + if ((ConcurrentOwner(address, size, scope) != AbandonCause.None) != owned) + { + return false; + } } - } - return true; + return true; + } + finally + { + FlushOwnerTests(scope); + } } + // The re-check's scope, per thread that takes resolutions. + [ThreadStatic] + private static ConcurrentOwnerScope? t_recheckScope; + + [ThreadStatic] + private static MetalRenderHost? t_recheckHost; + // On the worker, for a dispatch's resolution that may have read guest memory before the dispatches ahead of it ran: // as IsConcurrentResolveStillCurrent, and no GPU write logged since it began covers a range it read. A write those // dispatches recorded may have landed and retired by now, which the ownership answers alone no longer show. @@ -431,20 +616,53 @@ internal bool IsConcurrentResolveStillCurrentAcrossDispatches(object assumptions // is checked first: the worker records a write's ownership before it lets go of the queued range, // so the range found gone means the ownership below is already there. private bool IsOwnedConcurrent(ConcurrentQuery query, ulong address, ulong size) => - ConcurrentOwner(address, size) != AbandonCause.None; - - // The first owner of the range, in the order the tests above are cheapest to fail. - private AbandonCause ConcurrentOwner(ulong address, ulong size) => - PendingCommandWriteHolds(address, size) ? AbandonCause.Queued - : _imageCache.MayOwn(address, size) && _imageCache.HasGpuModifiedImageBytes(address, size) ? AbandonCause.Image - : IsGpuWritePendingConcurrent(address, size) ? AbandonCause.GpuWrite - : _cpOverlay.Count != 0 && - _cpOverlay.Coverage(address, size, _signaledSerialReader ??= SignaledSerial) != MetalOverlayCoverage.None - ? AbandonCause.CommandProcessor - : _labelOverlay.Count != 0 && - _labelOverlay.Coverage(address, size, _signaledSerialReader ??= SignaledSerial) != MetalOverlayCoverage.None - ? AbandonCause.Label - : AbandonCause.None; + ConcurrentOwner(address, size, scope: null) != AbandonCause.None; + + // The first owner of the range, in the order the tests above are cheapest to fail. A scope gives the + // completed serial (read once while it is scoped) and counts what the tests cost; without one, each test + // that needs the serial asks the GPU for it. + private AbandonCause ConcurrentOwner(ulong address, ulong size, ConcurrentOwnerScope? scope) + { + if (PendingCommandWriteHolds(address, size)) + { + return AbandonCause.Queued; + } + + if (_imageCache.MayOwn(address, size)) + { + scope?.Count(OwnerTestCounter.ImageLock); + if (_imageCache.HasGpuModifiedImageBytes(address, size)) + { + return AbandonCause.Image; + } + } + + var serial = scope?.Serial ?? (_signaledSerialReader ??= SignaledSerial); + if (IsGpuWritePendingConcurrent(address, size, serial)) + { + return AbandonCause.GpuWrite; + } + + if (_cpOverlay.Count != 0) + { + scope?.Count(OwnerTestCounter.OverlayCall); + if (_cpOverlay.Coverage(address, size, serial) != MetalOverlayCoverage.None) + { + return AbandonCause.CommandProcessor; + } + } + + if (_labelOverlay.Count != 0) + { + scope?.Count(OwnerTestCounter.OverlayCall); + if (_labelOverlay.Coverage(address, size, serial) != MetalOverlayCoverage.None) + { + return AbandonCause.Label; + } + } + + return AbandonCause.None; + } private bool PendingCommandWriteHolds(ulong address, ulong size) => _commandThread is { } thread && ParallelProgramPrefetch.ResolvingJob is var job and >= 0 && @@ -469,27 +687,64 @@ private bool IsOwnedRecorded(ConcurrentQuery query, ulong address, ulong size, C return false; } - if (CrossDrawCleanPages && IsCrossDrawClean(query, page, assumptions.Versions)) + var ownedLines = ConcurrentOwnedLines; + if (!ownedLines || !assumptions.IsOwnedPage(query, page)) { - assumptions.Record(query, page, ConcurrentPageBytes, false); - assumptions.NoteCleanPage(query, page); - return false; + if (CrossDrawCleanPages && IsCrossDrawClean(query, page, assumptions.Versions)) + { + assumptions.Record(query, page, ConcurrentPageBytes, false); + assumptions.NoteCleanPage(query, page); + return false; + } + + assumptions.Count(OwnerTestCounter.Page); + if (ConcurrentOwner(page, ConcurrentPageBytes, assumptions) == AbandonCause.None) + { + assumptions.Record(query, page, ConcurrentPageBytes, false); + assumptions.NoteCleanPage(query, page); + if (CrossDrawCleanPages) + { + NoteCrossDrawClean(query, page, assumptions.Versions); + } + + return false; + } + + // Remembered for the rest of the resolution, and not recorded: an owned page answers nothing + // itself. Should it turn clean meanwhile, its reads keep taking the finer tests below, which only + // ever find less clean than the page would. + if (ownedLines) + { + assumptions.NoteOwnedPage(query, page); + } } - if (!IsOwnedConcurrent(query, page, ConcurrentPageBytes)) + // In an owned page, the read's line first. Every test is an overlap test, so a clean line is clean for + // every range inside it; its answer is recorded like a clean page's and checked again at the take. + var line = address & ~((ulong)ConcurrentWordLineBytes - 1); + if (ownedLines && address - line <= ConcurrentWordLineBytes - size) { - assumptions.Record(query, page, ConcurrentPageBytes, false); - assumptions.NoteCleanPage(query, page); - if (CrossDrawCleanPages) + var lineOwned = assumptions.LineOwned(query, line); + if (lineOwned is null) { - NoteCrossDrawClean(query, page, assumptions.Versions); + assumptions.Count(OwnerTestCounter.Line); + lineOwned = ConcurrentOwner(line, ConcurrentWordLineBytes, assumptions) != AbandonCause.None; + assumptions.NoteLine(query, line, lineOwned.Value); + if (!lineOwned.Value) + { + assumptions.Record(query, line, ConcurrentWordLineBytes, false); + } } - return false; + if (!lineOwned.Value) + { + return false; + } } } - _lastConcurrentOwner = ConcurrentOwner(address, size); + assumptions.Count(OwnerTestCounter.Word); + _lastConcurrentOwner = ConcurrentOwner(address, size, assumptions); var owned = _lastConcurrentOwner != AbandonCause.None; assumptions.Record(query, address, size, owned); return owned; @@ -554,14 +809,14 @@ private void NoteCrossDrawClean(ConcurrentQuery query, ulong page, // A recorded GPU write the GPU has not finished covers these bytes. The coarse bounds test first, then // the records themselves, read only while the worker leaves them alone (a few tries, else pending). - private bool IsGpuWritePendingConcurrent(ulong address, ulong size) + private bool IsGpuWritePendingConcurrent(ulong address, ulong size, Func? completedSerial = null) { if (!_gpuWrites.MayCover(address, size)) { return false; } - var completed = SignaledSerial(); + var completed = completedSerial is null ? SignaledSerial() : completedSerial(); for (var attempt = 0; attempt < 4; attempt++) { if (_gpuWrites.TryPendingSerialSnapshot(address, size, completed, out var pending)) @@ -610,11 +865,13 @@ private bool TryReadGuestWordConcurrent(ulong address, out uint word, Concurrent throw new GpuFatal.AbandonedWorkException($"The resolution reads GPU-owned memory: address=0x{address:X16}."); } - // The whole page answered clean: the rest of the line is read with this word. The line lies within the - // page, which an aligned line of a power of two below the page size always does. + // The whole page, or the whole line of an owned page, answered clean: the rest of the line is read with + // this word. The line lies within the page, which an aligned line of a power of two below the page size + // always does. var line = address & ~lineMask; if (ConcurrentWordLines && (address & 3) == 0 && - assumptions.IsCleanPage(ConcurrentQuery.Word, address & ~(ConcurrentPageBytes - 1)) && + (assumptions.IsCleanPage(ConcurrentQuery.Word, address & ~(ConcurrentPageBytes - 1)) || + (ConcurrentOwnedLines && assumptions.LineOwned(ConcurrentQuery.Word, line) == false)) && _backing.TryReadBacking(line, assumptions.WordLineBytes)) { assumptions.WordLine = line; diff --git a/tests/SharpEmu.Gpu.Metal.Tests/MetalClearFoldingTests.CrossDrawCleanPages.cs b/tests/SharpEmu.Gpu.Metal.Tests/MetalClearFoldingTests.CrossDrawCleanPages.cs index 8f197f989..a0a587368 100644 --- a/tests/SharpEmu.Gpu.Metal.Tests/MetalClearFoldingTests.CrossDrawCleanPages.cs +++ b/tests/SharpEmu.Gpu.Metal.Tests/MetalClearFoldingTests.CrossDrawCleanPages.cs @@ -49,4 +49,142 @@ public void APageAResolutionFoundCleanIsOwnedAgainOnceAGpuWriteIsRecordedOnIt() concurrent.ReleaseAssumptions(concurrent.EndConcurrentResolve()); } } + + // A page holding a pending GPU write, as Demon's Souls keeps one in its descriptor page: the 256-byte line + // at 0x800 is owned, every other line of the page is clean. + private const ulong OwnedPage = GuestBase + 0x60000; + private const ulong OwnedPageWrite = OwnedPage + 0x800; + + private static void WriteOwnedPage(Rig rig) + { + for (var word = 0UL; word < ConcurrentPageWords; word++) + { + rig.WriteBacking32(OwnedPage + word * sizeof(uint), 0xD000u + (uint)word); + } + + rig.Host.NoteGuestMemoryWrite(OwnedPageWrite, 16, MetalGpuWriteOrigin.StorageBuffer); + } + + private const ulong ConcurrentPageWords = 4096 / sizeof(uint); + + private static long OwnerTestCount(string counters, string name) + { + var start = counters.IndexOf(name + "=", StringComparison.Ordinal) + name.Length + 1; + var end = start; + while (end < counters.Length && char.IsAsciiDigit(counters[end])) + { + end++; + } + + return long.Parse(counters.AsSpan(start, end - start), System.Globalization.CultureInfo.InvariantCulture); + } + + private static uint OwnedPageWord(ulong address) => 0xD000u + (uint)((address - OwnedPage) / sizeof(uint)); + + // Reads the words in one resolution and returns its assumptions; each word must read as the backing holds it. + private static object ResolveWords(MetalRenderHost host, params ulong[] addresses) + { + var concurrent = (IConcurrentResolveHost)host; + concurrent.BeginConcurrentResolve(); + try + { + foreach (var address in addresses) + { + Assert.True(host.TryReadGuestWord(address, out var word)); + Assert.Equal(OwnedPageWord(address), word); + } + } + catch + { + concurrent.ReleaseAssumptions(concurrent.EndConcurrentResolve()); + throw; + } + + return concurrent.EndConcurrentResolve(); + } + + [Theory] + [InlineData(true)] + [InlineData(false)] + public void TheCleanLinesOfAnOwnedPageAreTestedOnceAndTheirWordsReadFromThem(bool ownedLines) + { + if (!RequireDevice()) return; + using var rig = new Rig(Device.Value); + var host = rig.Host; + host.ConcurrentOwnedLines = ownedLines; + WriteOwnedPage(rig); + _ = host.TakeOwnerTestCounters(); + var concurrent = (IConcurrentResolveHost)host; + + // Two lines: three words in the first, one in the second, and the first again. + var assumptions = ResolveWords(host, OwnedPage + 0x10, OwnedPage + 0x14, OwnedPage + 0x40, OwnedPage + 0x110, OwnedPage + 0x18); + var counters = host.TakeOwnerTestCounters(); + Assert.Contains(ownedLines ? "page=1,line=2,word=0," : "page=5,line=0,word=5,", counters); + Assert.True(concurrent.IsStillCurrent(assumptions)); + + // A write elsewhere moves a version: the worker checks every answer again, with one serial. + host.NoteGuestMemoryWrite(GuestBase + 0x70000, sizeof(uint), MetalGpuWriteOrigin.StorageBuffer); + Assert.True(concurrent.IsStillCurrent(assumptions)); + if (ownedLines) + { + // Two line answers, and the serial asked for once at most for both of them. + var recheck = host.TakeOwnerTestCounters(); + Assert.Contains("recheck=2,", recheck); + Assert.True(OwnerTestCount(recheck, "serial_reads") <= (host.ConcurrentScopedSerial ? 1 : 2), recheck); + } + + concurrent.ReleaseAssumptions(assumptions); + } + + [Fact] + public void TheWordsOfAnOwnedLineAreTestedOneByOneAndAnOwnedWordAbandons() + { + if (!RequireDevice()) return; + using var rig = new Rig(Device.Value); + var host = rig.Host; + host.ConcurrentOwnedLines = true; + WriteOwnedPage(rig); + _ = host.TakeOwnerTestCounters(); + var concurrent = (IConcurrentResolveHost)host; + + concurrent.BeginConcurrentResolve(); + object assumptions; + try + { + // The line the write is in, past the write: read, after its own test. + Assert.True(host.TryReadGuestWord(OwnedPageWrite + 0x20, out var word)); + Assert.Equal(OwnedPageWord(OwnedPageWrite + 0x20), word); + Assert.Throws(() => host.TryReadGuestWord(OwnedPageWrite + 4, out _)); + } + finally + { + assumptions = concurrent.EndConcurrentResolve(); + } + + Assert.Contains("page=1,line=1,word=2,", host.TakeOwnerTestCounters()); + + Assert.Equal("gpu_write=1,copy_dst=0,label=0,cp=0,image=0,code=0,queued=0,other=0", host.TakeAbandonCauses()); + concurrent.ReleaseAssumptions(assumptions); + } + + [Theory] + [InlineData(OwnedPage + 0x14, false)] + [InlineData(OwnedPage + 0x10, false)] + // The same page, another line: the line answer the resolution relied on still holds. + [InlineData(OwnedPage + 0x900, true)] + public void AWriteLandingBetweenTheResolutionAndTheTakeRefusesItWhereItCoversALineItRead(ulong written, bool stands) + { + if (!RequireDevice()) return; + using var rig = new Rig(Device.Value); + var host = rig.Host; + host.ConcurrentOwnedLines = true; + WriteOwnedPage(rig); + var concurrent = (IConcurrentResolveHost)host; + var assumptions = ResolveWords(host, OwnedPage + 0x10, OwnedPage + 0x40); + Assert.True(concurrent.IsStillCurrent(assumptions)); + + host.NoteGuestMemoryWrite(written, sizeof(uint), MetalGpuWriteOrigin.StorageBuffer); + Assert.Equal(stands, concurrent.IsStillCurrent(assumptions)); + concurrent.ReleaseAssumptions(assumptions); + } } diff --git a/tests/SharpEmu.Gpu.Metal.Tests/MetalClearFoldingTests.WordReadBench.cs b/tests/SharpEmu.Gpu.Metal.Tests/MetalClearFoldingTests.WordReadBench.cs new file mode 100644 index 000000000..77e7783fa --- /dev/null +++ b/tests/SharpEmu.Gpu.Metal.Tests/MetalClearFoldingTests.WordReadBench.cs @@ -0,0 +1,104 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using System.Diagnostics; +using SharpEmu.Gpu.Metal.V2; +using SharpEmu.Libs.Gpu.Rendering; +using Xunit; + +namespace SharpEmu.Gpu.Metal.Tests; + +public sealed unsafe partial class MetalClearFoldingTests +{ + /// + /// SHARPEMU_BENCH_WORD_READS=<resolutions> times the guest reads of one stage's resolution on the resolving + /// thread, shaped like Demon's Souls: 45 descriptor words a few words apart in a page that holds one pending GPU + /// write (in a line of its own), over 250 live write records, then the worker's re-check of that resolution + /// after an ownership version moved. Each combination of ConcurrentOwnedLines and ConcurrentScopedSerial is + /// timed on the same host. + /// + [Fact] + public void ConcurrentResolveCostOverAnOwnedDescriptorPage() + { + if (!int.TryParse(Environment.GetEnvironmentVariable("SHARPEMU_BENCH_WORD_READS"), out var resolutions) || resolutions <= 0) + { + return; + } + + if (!RequireDevice()) return; + using var rig = new Rig(Device.Value); + var host = rig.Host; + for (var record = 0UL; record < 250; record++) + { + host.NoteGuestMemoryWrite(GuestBase + 0x40000 + record * 0x100, 0x40, MetalGpuWriteOrigin.StorageBuffer); + } + + WriteOwnedPage(rig); + var words = new ulong[45]; + for (var index = 0; index < words.Length; index++) + { + words[index] = OwnedPage + (ulong)index * 5 * sizeof(uint); + } + + var concurrent = (IConcurrentResolveHost)host; + void Resolve() + { + concurrent.BeginConcurrentResolve(); + try + { + foreach (var address in words) + { + if (!host.TryReadGuestWord(address, out _)) + { + throw new InvalidOperationException($"word 0x{address:X} was not read"); + } + } + } + finally + { + concurrent.ReleaseAssumptions(concurrent.EndConcurrentResolve()); + } + } + + double Time(Action body) + { + for (var warm = 0; warm < 2000; warm++) + { + body(); + } + + var stopwatch = Stopwatch.StartNew(); + for (var index = 0; index < resolutions; index++) + { + body(); + } + + stopwatch.Stop(); + return stopwatch.Elapsed.TotalMilliseconds * 1000 / resolutions; + } + + foreach (var (ownedLines, scopedSerial) in new[] { (false, false), (true, false), (false, true), (true, true) }) + { + host.ConcurrentOwnedLines = ownedLines; + host.ConcurrentScopedSerial = scopedSerial; + _ = host.TakeOwnerTestCounters(); + var resolve = Time(Resolve); + var perResolve = host.TakeOwnerTestCounters(); + + // One resolution's answers, checked again by the worker after a version moved. + concurrent.BeginConcurrentResolve(); + foreach (var address in words) + { + Assert.True(host.TryReadGuestWord(address, out _)); + } + + var assumptions = concurrent.EndConcurrentResolve(); + host.NoteGuestMemoryWrite(GuestBase + 0x80000, sizeof(uint), MetalGpuWriteOrigin.StorageBuffer); + var recheck = Time(() => Assert.True(concurrent.IsStillCurrent(assumptions))); + concurrent.ReleaseAssumptions(assumptions); + output.WriteLine( + $"owned_lines={(ownedLines ? 1 : 0)} scoped_serial={(scopedSerial ? 1 : 0)}: resolve {resolve:F2} us, " + + $"recheck {recheck:F2} us; resolutions {perResolve}"); + } + } +} diff --git a/tests/SharpEmu.Gpu.Metal.Tests/Scenes/GpuWordNoWaitSceneTests.cs b/tests/SharpEmu.Gpu.Metal.Tests/Scenes/GpuWordNoWaitSceneTests.cs index aad2fc97c..4b91782bb 100644 --- a/tests/SharpEmu.Gpu.Metal.Tests/Scenes/GpuWordNoWaitSceneTests.cs +++ b/tests/SharpEmu.Gpu.Metal.Tests/Scenes/GpuWordNoWaitSceneTests.cs @@ -2,6 +2,7 @@ // SPDX-License-Identifier: GPL-2.0-or-later using SharpEmu.Gpu.Metal.V2; +using SharpEmu.Libs.Gpu.Rendering; using SharpEmu.Libs.Gpu.Scheduling; using Xunit; using Xunit.Abstractions; @@ -149,6 +150,76 @@ public void AReadAheadOfTheStreamGivesUpInsteadOfWaitingForTheGpu() Assert.Empty(rig.Fatals); } + // A resolution ahead of the stream reads a page a held dispatch still writes the first line of: the other + // lines of the page are read without waiting (MetalRenderHost.ConcurrentOwnedLines), a word of the written + // line abandons, and a write recorded into a line it read before the take refuses the resolution. + [Fact] + public void AResolutionReadsTheCleanLinesOfAPageTheGpuStillWritesAndAWriteIntoThemRefusesIt() + { + using var rig = CreateRig(); + if (rig is null) return; + var host = rig.Host; + host.ConcurrentOwnedLines = true; + var page = rig.Memory.Allocate(4096, 4096); + var writer = rig.Dispatch(new ScenePm4(), ScenePrograms.StoreGlobalId, Descriptors.Buffer(page, 4, Words, format: 20), 1).ToArray(); + var later = rig.Dispatch(new ScenePm4(), ScenePrograms.StoreGlobalId, Descriptors.Buffer(page + 0x400, 4, Words, format: 20), 1).ToArray(); + rig.Submit(writer); + var planted = new byte[4096]; + for (var index = 0; index < planted.Length / 4; index++) + { + BitConverter.TryWriteBytes(planted.AsSpan(index * 4), 0xC0DE0000u + (uint)index); + } + + rig.Memory.Write(page, planted); + var gate = MetalNative.Send(DeviceOf(host), SelNewSharedEvent); + var released = 0; + using var watchdog = Watchdog(gate, () => Interlocked.Exchange(ref released, 1)); + var concurrent = (IConcurrentResolveHost)host; + try + { + MetalV2Native.SendEventValue(host.CommandBuffer, SelEncodeWaitForEvent, gate, 1); + rig.Enqueue(writer); + rig.RecordPending(); + var waitsBefore = host.HostGpuWaits; + + concurrent.BeginConcurrentResolve(); + object assumptions; + try + { + Assert.True(host.TryReadGuestWord(page + 0x404, out var word)); + Assert.Equal(0xC0DE0000u + 0x404 / 4, word); + Assert.True(host.TryReadGuestWord(page + 0x408, out word)); + Assert.Equal(0xC0DE0000u + 0x408 / 4, word); + Assert.Throws(() => host.TryReadGuestWord(page + 3 * 4, out _)); + } + finally + { + assumptions = concurrent.EndConcurrentResolve(); + } + + Assert.Equal(waitsBefore, host.HostGpuWaits); + Assert.Equal(0, Volatile.Read(ref released)); + Assert.True(concurrent.IsStillCurrent(assumptions)); + + // A store into the clean line the resolution read, recorded before the take. + rig.Enqueue(later); + rig.RecordPending(); + Assert.False(concurrent.IsStillCurrent(assumptions)); + concurrent.ReleaseAssumptions(assumptions); + } + finally + { + MetalNative.SendVoid(gate, SelSetSignaledValue, (nint)1); + } + + rig.Drain(); + AssertStored(rig, page, Words); + AssertStored(rig, page + 0x400, Words); + watchdog.Dispose(); + MetalNative.SendVoid(gate, SelRelease); + Assert.Empty(rig.Fatals); + } + [Theory] [InlineData(false)] [InlineData(true)] From f9baab9e8c7af10bce0e78cec546dbcd3569cdcf Mon Sep 17 00:00:00 2001 From: kuba Date: Sun, 15 Nov 2026 01:46:20 +0000 Subject: [PATCH 003/178] [Agc] Range stub takes a null source; native sceAgcGetDataPacketPayloadAddress sceAgcCbSetShRegisterRangeDirect with a null source reserves the payload for the caller, which then asks sceAgcGetDataPacketPayloadAddress for it and fills it: the pattern Demon's Souls runs ~6,400 times a frame. The range stub now handles a null source as the export does (no overlap check, no copy, any count up to the packet's 0x3FFF limit) instead of declining, and the payload-address query gets its own stub (type 0: header count all ones -> 0, else packet+4; any other type: packet+8). It declines for low/non-user pointers and page-crossing accesses and needs the export behind its trampoline. Tests run both stubs against the exports. Co-Authored-By: Claude --- .../Native/DirectExecutionBackend.FastPath.cs | 142 ++++++++++++- .../Agc/AgcExports.PacketStubs.cs | 17 ++ .../Cpu/AgcPacketStubTests.cs | 190 ++++++++++++++++-- 3 files changed, 330 insertions(+), 19 deletions(-) diff --git a/src/SharpEmu.Core/Cpu/Native/DirectExecutionBackend.FastPath.cs b/src/SharpEmu.Core/Cpu/Native/DirectExecutionBackend.FastPath.cs index 06acad057..23257e6b2 100644 --- a/src/SharpEmu.Core/Cpu/Native/DirectExecutionBackend.FastPath.cs +++ b/src/SharpEmu.Core/Cpu/Native/DirectExecutionBackend.FastPath.cs @@ -241,7 +241,7 @@ private void ConfigureGuestFastPath() _ => IsConstantZeroImport(nid) ? GuestFastPathStub.ConstantZero : SharpEmu.Libs.Agc.AgcExports.TryGetPacketStubSpec(nid, out _) || SharpEmu.Libs.Agc.AgcExports.TryGetVariablePacketStub(nid, out _) || - SharpEmu.Libs.Agc.AgcExports.TryGetRegIndirectPatchStub(nid, out _) + SharpEmu.Libs.Agc.AgcExports.TryGetRegIndirectPatchStub(nid, out _) || SharpEmu.Libs.Agc.AgcExports.TryGetPayloadAddressStub(nid) ? GuestFastPathStub.AgcPacket : GuestFastPathStub.None, }; @@ -266,6 +266,13 @@ internal static bool IsAgcStubAllowed(string nid, bool packetStubsEnabled, bool return patchStubsEnabled && exports.TryGetExport(nid, out _); } + // The payload-address stub writes the answer the export writes on success and declines + // into it for the rest, so it too needs the export behind the trampoline. + if (SharpEmu.Libs.Agc.AgcExports.TryGetPayloadAddressStub(nid)) + { + return exports.TryGetExport(nid, out _); + } + return SharpEmu.Libs.Agc.AgcExports.TryGetPacketStubSpec(nid, out _) || SharpEmu.Libs.Agc.AgcExports.TryGetVariablePacketStub(nid, out _); } @@ -331,7 +338,9 @@ private unsafe bool TryCreateGuestFastPathStub(string nid, nint fallbackTrampoli List code; if (kind == GuestFastPathStub.AgcPacket) { - code = SharpEmu.Libs.Agc.AgcExports.TryGetRegIndirectPatchStub(nid, out var patchSpec) + code = SharpEmu.Libs.Agc.AgcExports.TryGetPayloadAddressStub(nid) + ? EmitGuestAgcPayloadAddressStub(fallbackTrampoline) + : SharpEmu.Libs.Agc.AgcExports.TryGetRegIndirectPatchStub(nid, out var patchSpec) ? EmitGuestAgcRegIndirectPatchStub(patchSpec, fallbackTrampoline) : SharpEmu.Libs.Agc.AgcExports.TryGetVariablePacketStub(nid, out var variableKind) ? EmitGuestAgcVariablePacketStub(variableKind, fallbackTrampoline) @@ -883,7 +892,9 @@ void EmitModifierSlot(SharpEmu.Libs.Agc.AgcModifierSgprSlot slot) /// reserve, and a source that overlaps the packet being written; the export handles the rest. /// /// ShRegisterRange(cb, offset, values, count): offset 1..0x3FF, count 1..64; writes the marker - /// NOP, the SET_SH_REG header, the offset and the values, and returns the SET_SH_REG packet's address. + /// NOP, the SET_SH_REG header, the offset and the values, and returns the SET_SH_REG packet's address. + /// A null source reserves the payload for the caller, as the export does: nothing is copied or + /// checked for overlap, and the count may be anything the export takes (1..0x3FFF). /// ShRegisters(cb, pairs, count): count 1..32 and the pairs' offsets consecutive ascending (the /// export's sort is then a no-op and it emits exactly one packet); verified before anything is /// written, so a decline leaves the buffer untouched. @@ -905,6 +916,15 @@ void EmitBranchToSlowPath(byte shortOpcode) slowPathFixups.Add(code.Count - 4); } + // A forward short jump to a label PatchShortForward places. + int EmitShortForward(byte opcode) + { + Emit(opcode, 0); + return code.Count - 1; + } + + void PatchShortForward(int fixup) => code[fixup] = checked((byte)(code.Count - (fixup + 1))); + // A backwards short jump (opcode jb 0x72) to a code offset. void EmitLoopBack(int target) { @@ -927,10 +947,17 @@ void EmitLoopBack(int target) Emit(0x3D); EmitImm32(0x3FF); // cmp eax, 0x3FF EmitBranchToSlowPath(0x73); // jae slow: offset outside 1..0x3FF Emit(0x8D, 0x41, 0xFF); // lea eax, [rcx-1] - Emit(0x83, 0xF8, (byte)(SharpEmu.Libs.Agc.AgcExports.RangeStubMaxValues - 1)); // cmp eax, max-1 - EmitBranchToSlowPath(0x77); // ja slow: count 0 or too large Emit(0x48, 0x85, 0xD2); // test rdx, rdx - EmitBranchToSlowPath(0x74); // jz slow: a null source reserves the payload for the caller + var nullSourceCount = EmitShortForward(0x74); // jz null-source count + Emit(0x83, 0xF8, (byte)(SharpEmu.Libs.Agc.AgcExports.RangeStubMaxValues - 1)); // cmp eax, max-1 + EmitBranchToSlowPath(0x77); // ja slow: count 0 or too many values to copy + var countChecked = EmitShortForward(0xEB); // jmp count-ok + PatchShortForward(nullSourceCount); + // A null source reserves the payload for the caller (who asks for its address and fills + // it): nothing is copied, so any count the export takes is the stub's too. + Emit(0x3D); EmitImm32(SharpEmu.Libs.Agc.AgcExports.RangeStubMaxReservedValues - 1); // cmp eax, max-1 + EmitBranchToSlowPath(0x77); // ja slow: count 0 or over the packet's limit + PatchShortForward(countChecked); } else { @@ -963,7 +990,14 @@ void EmitLoopBack(int target) Emit(0x4D, 0x39, 0xDA); // cmp r10, r11 EmitBranchToSlowPath(0x72); // jb slow: no room - // The source must not overlap the packet area [rax, rax + r9*4). + // The source must not overlap the packet area [rax, rax + r9*4). A null source has none. + var skipOverlap = -1; + if (range) + { + Emit(0x48, 0x85, 0xD2); // test rdx, rdx + skipOverlap = EmitShortForward(0x74); // jz ok + } + Emit(0x4E, 0x8D, 0x04, 0x88); // lea r8, [rax + r9*4] end of the packet if (range) { @@ -981,6 +1015,11 @@ void EmitLoopBack(int target) Emit(0x49, 0x39, 0xC0); // cmp r8, rax EmitBranchToSlowPath(0x77); // ja slow: the source ends after the packet starts // ok: + if (skipOverlap >= 0) + { + PatchShortForward(skipOverlap); + } + if (!range) { Emit(0x44, 0x8B, 0x06); // mov r8d, [rsi] first offset @@ -1008,6 +1047,8 @@ void EmitLoopBack(int target) Emit(0x41, 0x81, 0xCA); EmitImm32(SharpEmu.Libs.Agc.AgcExports.SetShRegHeaderWithoutCount); // or r10d, header Emit(0x44, 0x89, 0x50, 0x08); // mov [rax+8], r10d Emit(0x89, 0x70, 0x0C); // mov [rax+12], esi the register offset + Emit(0x48, 0x85, 0xD2); // test rdx, rdx + var skipCopy = EmitShortForward(0x74); // jz copied: the payload stays the caller's Emit(0x45, 0x31, 0xC0); // xor r8d, r8d var copy = code.Count; Emit(0x46, 0x8B, 0x14, 0x82); // mov r10d, [rdx + r8*4] @@ -1015,6 +1056,7 @@ void EmitLoopBack(int target) Emit(0x41, 0xFF, 0xC0); // inc r8d Emit(0x41, 0x39, 0xC8); // cmp r8d, ecx EmitLoopBack(copy); // jb copy + PatchShortForward(skipCopy); Emit(0x44, 0x8D, 0x49, 0x04); // lea r9d, [rcx+4] } else @@ -1058,6 +1100,92 @@ void EmitLoopBack(int target) return code; } + /// + /// sceAgcGetDataPacketPayloadAddress(out, packet, type) as guest-side code, on the same terms as + /// : it stores the payload address the export stores at + /// out and returns 0, and declines (jumps to the import's trampoline with every argument + /// register intact, nothing written) for every case in which the export would not just do that: + /// + /// an out or packet pointer below 0x10000 (null included) or at or above 2^47; + /// an 8-byte out that crosses a 4 KiB page, and for type 0 a 4-byte header that + /// does, so the export's partial-write and unreadable-tail answers stay its own. + /// + /// The answer: for type (the low 32 bits of RDX) 0, 0 when the header's count field is all ones, + /// else packet + 4; for any other type, packet + 8. A pointer in range whose page is + /// not mapped faults here where the export would answer MEMORY_FAULT, as the builder and patcher + /// stubs fault on such a pointer. Only RAX and the flags change. + /// + internal static List EmitGuestAgcPayloadAddressStub(nint fallbackTrampoline) + { + var code = new List(128); + var slowPathFixups = new List(); + void Emit(params byte[] bytes) => code.AddRange(bytes); + void EmitImm32(uint value) => code.AddRange(BitConverter.GetBytes(value)); + void EmitBranchToSlowPath(byte shortOpcode) + { + Emit(0x0F, (byte)(shortOpcode + 0x10), 0, 0, 0, 0); + slowPathFixups.Add(code.Count - 4); + } + + int EmitShortForward(byte opcode) + { + Emit(opcode, 0); + return code.Count - 1; + } + + void PatchShortForward(int fixup) => code[fixup] = checked((byte)(code.Count - (fixup + 1))); + + Emit(0x48, 0x81, 0xFF); EmitImm32(0x10000); // cmp rdi, 0x10000 + EmitBranchToSlowPath(0x72); // jb slow: null or a low address + Emit(0x48, 0x89, 0xF8); // mov rax, rdi + Emit(0x48, 0xC1, 0xE8, 0x2F); // shr rax, 47 + EmitBranchToSlowPath(0x75); // jnz slow: not a user address + Emit(0x48, 0x81, 0xFE); EmitImm32(0x10000); // cmp rsi, 0x10000 + EmitBranchToSlowPath(0x72); // jb slow + Emit(0x48, 0x89, 0xF0); // mov rax, rsi + Emit(0x48, 0xC1, 0xE8, 0x2F); // shr rax, 47 + EmitBranchToSlowPath(0x75); // jnz slow + Emit(0x89, 0xF8); // mov eax, edi + Emit(0x25); EmitImm32(0xFFF); // and eax, 0xFFF + Emit(0x3D); EmitImm32(0x1000 - sizeof(ulong)); // cmp eax, 0xFF8 + EmitBranchToSlowPath(0x77); // ja slow: the answer crosses a page + Emit(0x85, 0xD2); // test edx, edx + var otherType = EmitShortForward(0x75); // jnz other + Emit(0x89, 0xF0); // mov eax, esi + Emit(0x25); EmitImm32(0xFFF); // and eax, 0xFFF + Emit(0x3D); EmitImm32(0x1000 - sizeof(uint)); // cmp eax, 0xFFC + EmitBranchToSlowPath(0x77); // ja slow: the header crosses a page + Emit(0x8B, 0x06); // mov eax, [rsi] header + Emit(0x25); EmitImm32(SharpEmu.Libs.Agc.AgcExports.PayloadAddressCountMask); // and eax, count field + Emit(0x3D); EmitImm32(SharpEmu.Libs.Agc.AgcExports.PayloadAddressCountMask); // cmp eax, all ones + var countNotFull = EmitShortForward(0x75); // jne inline + Emit(0x31, 0xC0); // xor eax, eax no payload + var storeAfterNull = EmitShortForward(0xEB); // jmp store + PatchShortForward(countNotFull); + Emit(0x48, 0x8D, 0x46, 0x04); // inline: lea rax, [rsi+4] + var storeAfterInline = EmitShortForward(0xEB); // jmp store + PatchShortForward(otherType); + Emit(0x48, 0x8D, 0x46, 0x08); // other: lea rax, [rsi+8] + PatchShortForward(storeAfterNull); + PatchShortForward(storeAfterInline); + Emit(0x48, 0x89, 0x07); // store: mov [rdi], rax + Emit(0x31, 0xC0); // xor eax, eax + Emit(0xC3); // ret + + foreach (var fixup in slowPathFixups) + { + var delta = BitConverter.GetBytes(code.Count - (fixup + 4)); + for (var i = 0; i < 4; i++) + { + code[fixup + i] = delta[i]; + } + } + + Emit(0xFF, 0x25, 0x00, 0x00, 0x00, 0x00); + code.AddRange(BitConverter.GetBytes((long)fallbackTrampoline)); + return code; + } + /// /// A register-indirect patcher (sceAgcSet{Cx,Sh,Uc}RegIndirectPatch{SetAddress,SetNumRegisters,AddRegisters}) /// as guest-side code, on the same terms as : with the packet in diff --git a/src/SharpEmu.Libs/Agc/AgcExports.PacketStubs.cs b/src/SharpEmu.Libs/Agc/AgcExports.PacketStubs.cs index eac1a3618..08852bd68 100644 --- a/src/SharpEmu.Libs/Agc/AgcExports.PacketStubs.cs +++ b/src/SharpEmu.Libs/Agc/AgcExports.PacketStubs.cs @@ -169,6 +169,12 @@ public static bool TryGetPacketStubSpec(string nid, out AgcPacketStubSpec spec) /// The most values a variable-length packet stub copies; a larger packet is the export's. public const int RangeStubMaxValues = 64; + /// + /// The most values sceAgcCbSetShRegisterRangeDirect reserves for a null source (the packet's + /// count field limit, TryGetCbSetShRegisterRangeDirectLayout); the stub copies nothing then. + /// + public const int RangeStubMaxReservedValues = 0x3FFF; + public const int RegistersStubMaxRegisters = 32; private const string CbSetShRegisterRangeDirectNid = "n2fD4A+pb+g"; @@ -205,6 +211,17 @@ public static bool TryGetPacketStubSpec(string nid, out AgcPacketStubSpec spec) public static bool TryGetRegIndirectPatchStub(string nid, out AgcRegIndirectPatchStubSpec spec) => RegIndirectPatchStubSpecs.TryGetValue(nid, out spec); + private const string GetDataPacketPayloadAddressNid = "V++UgBtQhn0"; + + /// The header bits sceAgcGetDataPacketPayloadAddress tests for a type-0 packet (its count field). + public const uint PayloadAddressCountMask = 0x3FFF_0000u; + + /// + /// Whether is sceAgcGetDataPacketPayloadAddress, whose native stub + /// (EmitGuestAgcPayloadAddressStub) answers the export's success path. + /// + public static bool TryGetPayloadAddressStub(string nid) => nid == GetDataPacketPayloadAddressNid; + /// The variable-length packet stub for a builder import, when it has one. public static bool TryGetVariablePacketStub(string nid, out AgcVariablePacketStub kind) { diff --git a/tests/SharpEmu.Libs.Tests/Cpu/AgcPacketStubTests.cs b/tests/SharpEmu.Libs.Tests/Cpu/AgcPacketStubTests.cs index 3c258b50c..325b4883f 100644 --- a/tests/SharpEmu.Libs.Tests/Cpu/AgcPacketStubTests.cs +++ b/tests/SharpEmu.Libs.Tests/Cpu/AgcPacketStubTests.cs @@ -172,19 +172,34 @@ public void TheVariableLengthStubWritesWhatTheExportWritesAndLeavesTheBufferAlon var random = new System.Random(unchecked(StableSeed(nid) ^ 0x77A1)); var stubRan = 0; var declinedWithRoom = 0; + var nullSourceRan = 0; + var nullSourceDeclines = 0; for (var iteration = 0; iteration < 1500; iteration++) { var reserved = (uint)random.Next(3) * 3; - var count = random.Next(12) switch - { - 0 => 0, - 1 => 1, - 2 => 65, - 3 => 64, - 4 => 33, - 5 => 32, - _ => random.Next(1, 20), - }; + // A null source (the range builder then reserves the payload for the caller) now and + // then, with counts up to the packet's limit and past it: nothing is copied then, so the + // buffer's room may run far past the block. + var valuesNull = random.Next(isRange ? 4 : 40) == 0; + var count = valuesNull && isRange && random.Next(2) == 0 + ? random.Next(6) switch + { + 0 => 0x3FFF, + 1 => 0x4000, + 2 => 0x3FFE, + 3 => 65, + _ => random.Next(1, 0x4001), + } + : random.Next(12) switch + { + 0 => 0, + 1 => 1, + 2 => 65, + 3 => 64, + 4 => 33, + 5 => 32, + _ => random.Next(1, 20), + }; var packetDwords = (isRange ? 4 : 2) + count; var room = random.Next(6) switch { @@ -203,7 +218,6 @@ public void TheVariableLengthStubWritesWhatTheExportWritesAndLeavesTheBufferAlon // The source: the block's tail (clear of the packet area) or, now and then, inside the packet area. var valuesInside = random.Next(8) == 0; - var valuesNull = random.Next(40) == 0; var sourceOffset = valuesInside ? PacketOffset + 4 * random.Next(0, 24) : ValuesOffset; var firstOffset = random.Next(6) switch { @@ -285,17 +299,27 @@ public void TheVariableLengthStubWritesWhatTheExportWritesAndLeavesTheBufferAlon declinedWithRoom++; } + // The range builder with a null source is the stub's for every count the export takes. + Assert.False( + isRange && valuesNull && !nullBuffer && room >= packetDwords * 4 + (int)reserved * 4 && + count is >= 1 and <= AgcExports.RangeStubMaxReservedValues && offsetArgument is >= 1 and <= 0x3FF, + $"{nid}: the stub declined a null-source range of {count} values the export reserves in place"); + nullSourceDeclines += isRange && valuesNull ? 1 : 0; + continue; } stubRan++; + nullSourceRan += valuesNull ? 1 : 0; Assert.False(context.GuestCallbackDeclined, $"{nid}: the stub built a packet where the export had to call back"); Assert.False(nullBuffer, nid + ": the stub accepted a null buffer"); + Assert.False(valuesNull && !isRange, nid + ": the stub accepted null pairs"); Assert.Equal(context[CpuRegister.Rax] - (ulong)managedBlock.Pointer, stubRax - (ulong)stubBlock.Pointer); Assert.Equal(managedBlock.Normalized(), stubBlock.Normalized()); } Assert.True(stubRan > 150, $"{nid}: the stub took the fast path only {stubRan} times"); + Assert.True(!isRange || nullSourceRan > 40, $"{nid}: the stub reserved a null-source payload only {nullSourceRan} times ({nullSourceDeclines} declines)"); Assert.True(declinedWithRoom < 40, $"{nid}: the stub declined {declinedWithRoom} calls the export builds as one in-place packet"); } @@ -432,6 +456,142 @@ public void ThePatchStubPatchesWhatTheExportPatchesAndDeclinesEverythingElse(str } } + private const string PayloadAddressNid = "V++UgBtQhn0"; + + // The stub's null-source count limit is the export's packet limit. + [Fact] + public void TheNullSourceRangeLimitIsTheExportsPacketLimit() + { + var manager = new ModuleManager(); + manager.RegisterExports(SharpEmu.Generated.SysAbiExportRegistry.CreateExports(Generation.Gen5)); + foreach (var (count, valid) in new[] { (AgcExports.RangeStubMaxReservedValues, true), (AgcExports.RangeStubMaxReservedValues + 1, false) }) + { + var context = new CpuContext(new RegionMemory(null, 0), Generation.Gen5); + context[CpuRegister.Rdi] = (ulong)count; + Assert.True(manager.TryDispatch("bxGoVxpdSPQ", context, out _)); // sceAgcCbSetShRegisterRangeDirectGetSize + Assert.Equal(valid, context[CpuRegister.Rax] != 0); + } + } + + [Fact] + public void ThePayloadAddressStubAnswersWhatTheExportAnswersAndDeclinesEverythingElse() + { + if (OperatingSystem.IsWindows() || RuntimeInformation.ProcessArchitecture != Architecture.X64) + { + return; + } + + using var harness = new StubHarness(fallback => DirectExecutionBackend.EmitGuestAgcPayloadAddressStub(fallback), echoArguments: true); + var manager = new ModuleManager(); + manager.RegisterExports(SharpEmu.Generated.SysAbiExportRegistry.CreateExports(Generation.Gen5)); + var random = new System.Random(unchecked(StableSeed(PayloadAddressNid) ^ 0x4A11)); + var managedRegion = (byte*)NativeMemory.AlignedAlloc(PatchRegionBytes, 0x1000); + var stubRegion = (byte*)NativeMemory.AlignedAlloc(PatchRegionBytes, 0x1000); + try + { + var stubRan = 0; + var ranByType = new int[3]; + for (var iteration = 0; iteration < 3000; iteration++) + { + // Where the answer and the packet sit: inside a page, flush against its end, a few + // bytes over it, or a pointer the stub must not touch at all. + int Offset(int size) => random.Next(8) switch + { + 0 => 0x1000 - size, + 1 => 0x1000 - size + random.Next(1, 8), + 2 => 0x2000 - size, + _ => random.Next(0, 0x2000 - size), + }; + + ulong? Special() => random.Next(14) != 0 ? null : random.Next(4) switch + { + 0 => 0UL, + 1 => (ulong)random.Next(1, 0x10000), + 2 => 0x8000_0000_0000UL + (ulong)random.Next(0, 0x1000), + _ => 0xFFFF_8000_0000_0000UL | (ulong)random.NextInt64(0, 0x7FFF_FFFF_FFFF), + }; + + var outOffset = Offset(8); + var packetOffset = Offset(4); + // The answer and the header must not overlap, or the order of the read and the write shows. + if (Math.Abs(outOffset - packetOffset) < 8) + { + continue; + } + + var outSpecial = Special(); + var packetSpecial = Special(); + // Type: 0 (also with high bits that the export's int conversion drops), 1, or anything. + var type = random.Next(6) switch + { + 0 or 1 => 0UL, + 2 => 0x1_0000_0000UL * (ulong)random.Next(1, 1 << 30), + 3 => 1UL, + _ => (ulong)random.NextInt64() | ((ulong)random.Next(2) << 63), + }; + var header = random.Next(4) switch + { + 0 => 0xC000_0000u | AgcExports.PayloadAddressCountMask | (uint)random.Next(0x10000), + 1 => AgcExports.PayloadAddressCountMask, + 2 => 0xC000_0000u | ((uint)random.Next(0x3FFF) << 16) | (uint)random.Next(0x10000), + _ => (uint)random.NextInt64(0, 1L << 32), + }; + + var fill = new System.Random(random.Next()); + for (var index = 0; index < PatchRegionBytes; index++) + { + managedRegion[index] = (byte)fill.Next(256); + } + + *(uint*)(managedRegion + packetOffset) = header; + Buffer.MemoryCopy(managedRegion, stubRegion, PatchRegionBytes, PatchRegionBytes); + var pristine = new ReadOnlySpan(stubRegion, PatchRegionBytes).ToArray(); + + var context = new CpuContext(new RegionMemory(managedRegion, PatchRegionBytes), Generation.Gen5); + context[CpuRegister.Rdi] = outSpecial ?? (ulong)(managedRegion + outOffset); + context[CpuRegister.Rsi] = packetSpecial ?? (ulong)(managedRegion + packetOffset); + context[CpuRegister.Rdx] = type; + Assert.True(manager.TryDispatch(PayloadAddressNid, context, out var managedResult)); + + var stubOut = outSpecial ?? (ulong)(stubRegion + outOffset); + var stubPacket = packetSpecial ?? (ulong)(stubRegion + packetOffset); + var stubRax = harness.Call(stubOut, stubPacket, type, 0, 0); + var fastCase = outSpecial is null && packetSpecial is null && + (outOffset & 0xFFF) <= 0x1000 - 8 && + ((uint)type != 0 || (packetOffset & 0xFFF) <= 0x1000 - 4); + if (stubRax == (Sentinel ^ stubOut ^ stubPacket)) + { + Assert.False(fastCase, $"declined an answer the export gives (out=0x{outOffset:X} packet=0x{packetOffset:X} type=0x{type:X})"); + Assert.Equal(pristine, new ReadOnlySpan(stubRegion, PatchRegionBytes).ToArray()); + continue; + } + + stubRan++; + ranByType[(uint)type != 0 ? 2 : (header & AgcExports.PayloadAddressCountMask) == AgcExports.PayloadAddressCountMask ? 1 : 0]++; + Assert.True(fastCase, $"answered where the export cannot (out=0x{outOffset:X} packet=0x{packetOffset:X} type=0x{type:X} result={managedResult})"); + Assert.Equal(OrbisGen2Result.ORBIS_GEN2_OK, managedResult); + Assert.Equal(context[CpuRegister.Rax], stubRax); + // The answer is an address: compare it relative to its region. + var managedAnswer = *(ulong*)(managedRegion + outOffset); + var stubAnswer = *(ulong*)(stubRegion + outOffset); + Assert.Equal(managedAnswer == 0 ? 0 : managedAnswer - (ulong)managedRegion, stubAnswer == 0 ? 0 : stubAnswer - (ulong)stubRegion); + *(ulong*)(managedRegion + outOffset) = 0; + *(ulong*)(stubRegion + outOffset) = 0; + Assert.Equal( + new ReadOnlySpan(managedRegion, PatchRegionBytes).ToArray(), + new ReadOnlySpan(stubRegion, PatchRegionBytes).ToArray()); + } + + Assert.True(stubRan > 1000, $"the stub answered only {stubRan} times"); + Assert.All(ranByType, ran => Assert.True(ran > 100, $"answers by type (inline, full count, other): {string.Join(",", ranByType)}")); + } + finally + { + NativeMemory.AlignedFree(managedRegion); + NativeMemory.AlignedFree(stubRegion); + } + } + // FNV-1a over the NID: string.GetHashCode is randomized per process, so a failing case would not replay. private static int StableSeed(string nid) { @@ -474,6 +634,12 @@ public void APatchStubIsInstalledOnlyWithItsExportAndBothSwitchesOn() Assert.False(DirectExecutionBackend.IsAgcStubAllowed(nid, packetStubsEnabled: false, patchStubsEnabled: true, all), nid); } + // The payload-address stub needs its export too, and only the packet switch turns it off. + Assert.True(DirectExecutionBackend.IsAgcStubAllowed(PayloadAddressNid, packetStubsEnabled: true, patchStubsEnabled: false, all)); + Assert.False(DirectExecutionBackend.IsAgcStubAllowed(PayloadAddressNid, packetStubsEnabled: false, patchStubsEnabled: true, all)); + Assert.False(DirectExecutionBackend.IsAgcStubAllowed(PayloadAddressNid, packetStubsEnabled: true, patchStubsEnabled: true, none)); + Assert.Equal(DirectExecutionBackend.GuestFastPathStub.AgcPacket, DirectExecutionBackend.ClassifyGuestFastPathStub(PayloadAddressNid)); + Assert.False(DirectExecutionBackend.IsAgcStubAllowed("Ikfdt-rIqCE", packetStubsEnabled: true, patchStubsEnabled: true, all)); } @@ -676,7 +842,7 @@ private StubHarness(AgcPacketStubSpec? spec, AgcVariablePacketStub? kind) { } - private StubHarness(Func> emit, bool echoArguments) + public StubHarness(Func> emit, bool echoArguments) { _page = (byte*)HostMemory.Alloc(null, 4096, HostMemory.MEM_COMMIT | HostMemory.MEM_RESERVE, HostMemory.PAGE_EXECUTE_READWRITE); Assert.True(_page != null); From 69514719056f9ab2fcbfc0b9bdc5c4d7d56b54ff Mon Sep 17 00:00:00 2001 From: kuba Date: Sun, 15 Nov 2026 01:52:18 +0000 Subject: [PATCH 004/178] [Agc] Batched sceAgcCreatePrimState and a trivial-leaf dispatch for it CreatePrimState made about 15 guest reads and 10 writes per call. Its success path now reads each shader header (0x28..0x5A) and specials block (0x00..0x2F) once and writes the cx and uc register blocks with one TryWritePair; anything that path could answer differently (a failing read, a wrong shader type, a null specials pointer, a destination overlapping what is read, a failed write) falls back to the field-by-field code, which keeps every partial write and MEMORY_FAULT/INVALID_ARGUMENT answer. SHARPEMU_AGC_PRIMSTATE_FAST=0 keeps the old path. The export reads registers only and never blocks or calls back, so it joins the trivial leaves. CreateInterpolantMapping reads each shader's two header fields in one read (the separate reads still answer when it fails). PerfAudit 'agc' gains DcbDrawIndexIndirect and CreatePrimState benches; the tool's fakes are brought up to the current IRenderHost/IShaderPipelineProvider so it builds. Co-Authored-By: Claude --- .../Native/DirectExecutionBackend.Imports.cs | 1 + .../Agc/AgcExports.ShaderState.cs | 164 +++++++++++++++++- .../Agc/AgcPrimStateBatchedTests.cs | 115 ++++++++++++ .../Benches.AgcBuilders.cs | 30 ++++ .../PlanningSupport.cs | 22 ++- 5 files changed, 326 insertions(+), 6 deletions(-) create mode 100644 tests/SharpEmu.Libs.Tests/Agc/AgcPrimStateBatchedTests.cs diff --git a/src/SharpEmu.Core/Cpu/Native/DirectExecutionBackend.Imports.cs b/src/SharpEmu.Core/Cpu/Native/DirectExecutionBackend.Imports.cs index 296bb946d..c88573403 100644 --- a/src/SharpEmu.Core/Cpu/Native/DirectExecutionBackend.Imports.cs +++ b/src/SharpEmu.Core/Cpu/Native/DirectExecutionBackend.Imports.cs @@ -2198,6 +2198,7 @@ nid is "ob5xAW4ln-0" or // strchr "9yDWMxEFdJU" or // strrchr "V++UgBtQhn0" or // sceAgcGetDataPacketPayloadAddress + "D9sr1xGUriE" or // sceAgcCreatePrimState: register arguments, guest reads and writes only // Per-frame polls a title runs on every input and playback tick. "h8uongcBNVs" or // sceSystemGestureGetTouchEventsCount "n88vx3C5nW8" or // gettimeofday diff --git a/src/SharpEmu.Libs/Agc/AgcExports.ShaderState.cs b/src/SharpEmu.Libs/Agc/AgcExports.ShaderState.cs index 0f303a0b9..7797838e6 100644 --- a/src/SharpEmu.Libs/Agc/AgcExports.ShaderState.cs +++ b/src/SharpEmu.Libs/Agc/AgcExports.ShaderState.cs @@ -616,7 +616,10 @@ private static bool TryReadFusedResourceEntries( ExportName = "sceAgcCreatePrimState", Target = Generation.Gen5, LibraryName = "libSceAgc")] - public static int CreatePrimState(CpuContext ctx) + public static int CreatePrimState(CpuContext ctx) => CreatePrimStateCore(ctx, PrimStateFastEnabled); + + // batched: try TryCreatePrimStateBatched before the field-by-field path (tests run both). + internal static int CreatePrimStateCore(CpuContext ctx, bool batched) { var cxRegistersAddress = ctx[CpuRegister.Rdi]; var ucRegistersAddress = ctx[CpuRegister.Rsi]; @@ -635,6 +638,15 @@ public static int CreatePrimState(CpuContext ctx) return SetReturn(ctx, OrbisGen2Result.ORBIS_GEN2_ERROR_INVALID_ARGUMENT); } + if (batched && + TryCreatePrimStateBatched(ctx, cxRegistersAddress, ucRegistersAddress, hullShaderAddress, geometryShaderAddress, primitiveType, out var batchedShaderType)) + { + TraceAgc( + $"agc.create_prim_state cx=0x{cxRegistersAddress:X16} uc=0x{ucRegistersAddress:X16} hull=0x{hullShaderAddress:X16} gs=0x{geometryShaderAddress:X16} type={batchedShaderType} prim=0x{primitiveType:X8}"); + ctx[CpuRegister.Rax] = 0; + return (int)OrbisGen2Result.ORBIS_GEN2_OK; + } + if (!TryReadByte(ctx, geometryShaderAddress + ShaderTypeOffset, out var shaderType) || !IsEsGeometryShaderType(shaderType) || !TryReadUInt64(ctx, geometryShaderAddress + ShaderSpecialsOffset, out var specialsAddress) || specialsAddress == 0) @@ -819,6 +831,135 @@ public static int CreateInterpolantMapping2(CpuContext ctx) return (int)OrbisGen2Result.ORBIS_GEN2_OK; } + // SHARPEMU_AGC_PRIMSTATE_FAST=0 keeps sceAgcCreatePrimState on its field-by-field reads and writes. + internal static readonly bool PrimStateFastEnabled = + Environment.GetEnvironmentVariable("SHARPEMU_AGC_PRIMSTATE_FAST") != "0"; + + // The shader header bytes CreatePrimState reads: the specials pointer (0x28) through the type byte (0x5A). + private const int PrimStateHeaderBytes = (int)(ShaderTypeOffset + 1 - ShaderSpecialsOffset); + + // The specials bytes it reads: GE_CNTL (0x00) through GE_USER_VGPR_EN (0x28), as (offset, value) pairs. + private const int PrimStateSpecialsBytes = (int)(ShaderSpecialGeUserVgprEnOffset + 8); + + /// + /// sceAgcCreatePrimState's success path in one read of each shader header and specials block + /// and one guest write of both register blocks. False - with nothing written, or with nothing + /// written that the field-by-field path does not write again in the same order - whenever that + /// path could answer differently: a read it would not make fails, a shader is not the type it + /// takes, a specials pointer is null, a destination overlaps anything read (that path reads + /// some fields after writing others), or the write fails. The field-by-field path then runs + /// and owns every partial write and MEMORY_FAULT/INVALID_ARGUMENT answer. + /// + internal static bool TryCreatePrimStateBatched( + CpuContext ctx, + ulong cxRegistersAddress, + ulong ucRegistersAddress, + ulong hullShaderAddress, + ulong geometryShaderAddress, + uint primitiveType, + out byte shaderType) + { + shaderType = 0; + Span header = stackalloc byte[PrimStateHeaderBytes]; + if (!ctx.Memory.TryRead(geometryShaderAddress + ShaderSpecialsOffset, header)) + { + return false; + } + + shaderType = header[(int)(ShaderTypeOffset - ShaderSpecialsOffset)]; + var specialsAddress = BinaryPrimitives.ReadUInt64LittleEndian(header); + if (!IsEsGeometryShaderType(shaderType) || specialsAddress == 0) + { + return false; + } + + ulong hullSpecialsAddress = 0; + if (hullShaderAddress != 0) + { + if (!ctx.Memory.TryRead(hullShaderAddress + ShaderSpecialsOffset, header) || + header[(int)(ShaderTypeOffset - ShaderSpecialsOffset)] != HsShaderType) + { + return false; + } + + hullSpecialsAddress = BinaryPrimitives.ReadUInt64LittleEndian(header); + if (hullSpecialsAddress == 0) + { + return false; + } + } + + Span specials = stackalloc byte[PrimStateSpecialsBytes]; + Span hullSpecials = stackalloc byte[PrimStateSpecialsBytes]; + if (!ctx.Memory.TryRead(specialsAddress, specials) || + (hullSpecialsAddress != 0 && !ctx.Memory.TryRead(hullSpecialsAddress, hullSpecials))) + { + return false; + } + + // Every range read above, against both destinations. + bool OverlapsRead(ulong address, ulong length) => + !IsSeparate(address, length, geometryShaderAddress + ShaderSpecialsOffset, PrimStateHeaderBytes) || + !IsSeparate(address, length, specialsAddress, PrimStateSpecialsBytes) || + (hullShaderAddress != 0 && + (!IsSeparate(address, length, hullShaderAddress + ShaderSpecialsOffset, PrimStateHeaderBytes) || + !IsSeparate(address, length, hullSpecialsAddress, PrimStateSpecialsBytes))); + const int CxBytes = 16; + const int UcBytes = 24; + if ((cxRegistersAddress != 0 && OverlapsRead(cxRegistersAddress, CxBytes)) || + (ucRegistersAddress != 0 && OverlapsRead(ucRegistersAddress, UcBytes))) + { + return false; + } + + uint Field(ReadOnlySpan block, ulong offset) => BinaryPrimitives.ReadUInt32LittleEndian(block[(int)offset..]); + Span cx = stackalloc uint[CxBytes / sizeof(uint)]; + cx[0] = Field(specials, ShaderSpecialVgtShaderStagesEnOffset); + var stagesValue = Field(specials, ShaderSpecialVgtShaderStagesEnOffset + 4); + if ((stagesValue & VgtShaderStagesGsEnableBit) != 0) + { + cx[2] = Field(specials, ShaderSpecialVgtGsOutPrimTypeOffset); + cx[3] = Field(specials, ShaderSpecialVgtGsOutPrimTypeOffset + 4); + } + else + { + cx[2] = VgtGsOutPrimType; + cx[3] = AgcPrimitiveHelpers.PrimitiveTypeToGsOut(primitiveType); + } + + if (hullSpecialsAddress != 0) + { + stagesValue |= Field(hullSpecials, ShaderSpecialVgtShaderStagesEnOffset + 4); + if ((stagesValue & VgtShaderStagesGsEnableBit) == 0) + { + cx[2] = Field(hullSpecials, ShaderSpecialVgtGsOutPrimTypeOffset); + cx[3] = Field(hullSpecials, ShaderSpecialVgtGsOutPrimTypeOffset + 4); + } + } + + cx[1] = stagesValue; + Span uc = stackalloc uint[UcBytes / sizeof(uint)]; + ReadOnlySpan vgprSource = hullSpecialsAddress != 0 ? hullSpecials : specials; + uc[0] = Field(specials, ShaderSpecialGeCntlOffset); + uc[1] = Field(specials, ShaderSpecialGeCntlOffset + 4); + uc[2] = Field(vgprSource, ShaderSpecialGeUserVgprEnOffset); + uc[3] = Field(vgprSource, ShaderSpecialGeUserVgprEnOffset + 4); + uc[4] = VgtPrimitiveType; + uc[5] = primitiveType; + + var cxBytes = System.Runtime.InteropServices.MemoryMarshal.AsBytes(cx); + var ucBytes = System.Runtime.InteropServices.MemoryMarshal.AsBytes(uc); + // cx before uc, as the field-by-field path writes them. + return cxRegistersAddress == 0 ? ctx.Memory.TryWrite(ucRegistersAddress, ucBytes) + : ucRegistersAddress == 0 ? ctx.Memory.TryWrite(cxRegistersAddress, cxBytes) + : ctx.Memory.TryWritePair(cxRegistersAddress, cxBytes, ucRegistersAddress, ucBytes); + } + + // Whether [a, a + aLength) and [b, b + bLength) are disjoint and neither wraps. + private static bool IsSeparate(ulong a, ulong aLength, ulong b, ulong bLength) => + a <= ulong.MaxValue - aLength && b <= ulong.MaxValue - bLength && + (a + aLength <= b || b + bLength <= a); + private static bool TryCreatePrimCxState( CpuContext ctx, ulong destinationAddress, @@ -988,9 +1129,16 @@ public static int CreateInterpolantMapping(CpuContext ctx) // and pack the hardware CNTL word (location in bits [4:0], Flat at 0x400). uint inputSemanticsCount = 0; ulong inputSemanticsAddress = 0; + // Each shader's two header fields are one read (the separate reads answer when it fails). + Span header = stackalloc byte[(int)(ShaderNumInputSemanticsOffset + sizeof(uint) - ShaderInputSemanticsOffset)]; if (pixelShaderAddress != 0) { - if (!TryReadUInt64(ctx, pixelShaderAddress + ShaderInputSemanticsOffset, out inputSemanticsAddress) || + if (ctx.Memory.TryRead(pixelShaderAddress + ShaderInputSemanticsOffset, header)) + { + inputSemanticsAddress = BinaryPrimitives.ReadUInt64LittleEndian(header); + inputSemanticsCount = BinaryPrimitives.ReadUInt32LittleEndian(header[(int)(ShaderNumInputSemanticsOffset - ShaderInputSemanticsOffset)..]); + } + else if (!TryReadUInt64(ctx, pixelShaderAddress + ShaderInputSemanticsOffset, out inputSemanticsAddress) || !TryReadUInt32(ctx, pixelShaderAddress + ShaderNumInputSemanticsOffset, out inputSemanticsCount)) { return SetReturn(ctx, OrbisGen2Result.ORBIS_GEN2_ERROR_MEMORY_FAULT); @@ -1024,8 +1172,16 @@ public static int CreateInterpolantMapping(CpuContext ctx) } // NumOutputSemantics is a u16 at header +0x56. - if (!TryReadUInt64(ctx, geometryShaderAddress + ShaderOutputSemanticsOffset, out var outputSemanticsAddress) || - !TryReadUInt16(ctx, geometryShaderAddress + ShaderNumOutputSemanticsOffset, out var outputSemanticsCount)) + ulong outputSemanticsAddress; + ushort outputSemanticsCount; + var geometryHeader = header[..(int)(ShaderNumOutputSemanticsOffset + sizeof(ushort) - ShaderOutputSemanticsOffset)]; + if (ctx.Memory.TryRead(geometryShaderAddress + ShaderOutputSemanticsOffset, geometryHeader)) + { + outputSemanticsAddress = BinaryPrimitives.ReadUInt64LittleEndian(geometryHeader); + outputSemanticsCount = BinaryPrimitives.ReadUInt16LittleEndian(geometryHeader[(int)(ShaderNumOutputSemanticsOffset - ShaderOutputSemanticsOffset)..]); + } + else if (!TryReadUInt64(ctx, geometryShaderAddress + ShaderOutputSemanticsOffset, out outputSemanticsAddress) || + !TryReadUInt16(ctx, geometryShaderAddress + ShaderNumOutputSemanticsOffset, out outputSemanticsCount)) { return SetReturn(ctx, OrbisGen2Result.ORBIS_GEN2_ERROR_MEMORY_FAULT); } diff --git a/tests/SharpEmu.Libs.Tests/Agc/AgcPrimStateBatchedTests.cs b/tests/SharpEmu.Libs.Tests/Agc/AgcPrimStateBatchedTests.cs new file mode 100644 index 000000000..9f85b8d19 --- /dev/null +++ b/tests/SharpEmu.Libs.Tests/Agc/AgcPrimStateBatchedTests.cs @@ -0,0 +1,115 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using SharpEmu.HLE; +using SharpEmu.Libs.Agc; +using Xunit; + +namespace SharpEmu.Libs.Tests.Agc; + +/// +/// sceAgcCreatePrimState's batched path (one read per header and specials block, one write of both +/// register blocks) against its field-by-field path, on random shader structures: the same result, +/// the same RAX and the same bytes, including partial writes and faults next to the end of mapped +/// memory, destinations that overlap what is read, and shaders of the wrong type. +/// +public sealed class AgcPrimStateBatchedTests +{ + private const ulong BaseAddress = 0x1_0000_0000; + private const int RegionBytes = 0x2000; + + [Fact] + public void TheBatchedPathAnswersAndWritesWhatTheFieldByFieldPathDoes() + { + var random = new System.Random(0x9817); + var batchedRan = 0; + var outcomes = new Dictionary(); + for (var iteration = 0; iteration < 6000; iteration++) + { + var seed = random.Next(); + var fill = new System.Random(seed); + var bytes = new byte[RegionBytes]; + fill.NextBytes(bytes); + + // An address in the region (anywhere, or flush against its end so only part of a block + // reads), null, or outside it. + ulong Place(int size) => random.Next(10) switch + { + 0 => 0, + 1 => BaseAddress + (ulong)(RegionBytes - random.Next(1, size + 1)), + 2 => BaseAddress + RegionBytes + 0x1000, + _ => BaseAddress + (ulong)(random.Next(0, (RegionBytes - size) / 4) * 4), + }; + + void Put(ulong address, ReadOnlySpan value) + { + var offset = address - BaseAddress; + if (address >= BaseAddress && offset + (ulong)value.Length <= RegionBytes) + { + value.CopyTo(bytes.AsSpan((int)offset)); + } + } + + var geometry = random.Next(12) == 0 ? 0 : Place(0x60); + var hull = random.Next(2) == 0 ? 0 : Place(0x60); + var specials = random.Next(12) == 0 ? 0 : Place(0x30); + var hullSpecials = random.Next(12) == 0 ? 0 : Place(0x30); + var cx = random.Next(5) == 0 ? 0 : Place(16); + var uc = random.Next(5) == 0 ? 0 : Place(24); + // Now and then a destination right on top of something the export reads. + if (random.Next(10) == 0) + { + var targets = new[] { geometry + 0x28, specials, specials + 0x08, hullSpecials + 0x20, hull + 0x50 }; + if (random.Next(2) == 0) cx = targets[random.Next(targets.Length)]; + else uc = targets[random.Next(targets.Length)]; + } + + Put(geometry + 0x28, BitConverter.GetBytes(specials)); + Put(geometry + 0x5A, [random.Next(5) switch { 0 => (byte)6, 1 => (byte)random.Next(256), _ => (byte)2 }]); + Put(hull + 0x28, BitConverter.GetBytes(hullSpecials)); + Put(hull + 0x5A, [random.Next(5) == 0 ? (byte)random.Next(256) : (byte)3]); + // The stages value's GS enable bit (bit 5) both ways in each block. + Put(specials + 0x0C, BitConverter.GetBytes((uint)random.Next() & ~0x20u | (random.Next(2) == 0 ? 0x20u : 0))); + Put(hullSpecials + 0x0C, BitConverter.GetBytes((uint)random.Next() & ~0x20u | (random.Next(3) == 0 ? 0x20u : 0))); + + var primitive = random.Next(4) == 0 ? (uint)random.Next() : (uint)random.Next(0x20); + (int Result, ulong Rax, byte[] Memory) Run(Func body) + { + var memory = new FakeCpuMemory(BaseAddress, RegionBytes); + Assert.True(memory.TryWrite(BaseAddress, bytes)); + var ctx = new CpuContext(memory, Generation.Gen5); + ctx[CpuRegister.Rdi] = cx; + ctx[CpuRegister.Rsi] = uc; + ctx[CpuRegister.Rdx] = hull; + ctx[CpuRegister.Rcx] = geometry; + ctx[CpuRegister.R8] = primitive; + var result = body(ctx); + var after = new byte[RegionBytes]; + Assert.True(memory.TryRead(BaseAddress, after)); + return (result, ctx[CpuRegister.Rax], after); + } + + var legacy = Run(ctx => AgcExports.CreatePrimStateCore(ctx, batched: false)); + var batched = Run(ctx => AgcExports.CreatePrimStateCore(ctx, batched: true)); + var context = $"iteration {iteration}: cx=0x{cx:X} uc=0x{uc:X} hs=0x{hull:X} gs=0x{geometry:X} specials=0x{specials:X} hullSpecials=0x{hullSpecials:X}"; + Assert.True(legacy.Result == batched.Result, context); + Assert.True(legacy.Rax == batched.Rax, context); + Assert.True(legacy.Memory.AsSpan().SequenceEqual(batched.Memory), context); + outcomes[legacy.Result] = outcomes.GetValueOrDefault(legacy.Result) + 1; + + // How often the batched path itself answered (the rest fell back). + if (cx != 0 || uc != 0) + { + var memory = new FakeCpuMemory(BaseAddress, RegionBytes); + memory.TryWrite(BaseAddress, bytes); + if (geometry != 0 && AgcExports.TryCreatePrimStateBatched(new CpuContext(memory, Generation.Gen5), cx, uc, hull, geometry, primitive, out _)) + { + batchedRan++; + } + } + } + + Assert.True(batchedRan > 500, $"the batched path answered only {batchedRan} times"); + Assert.True(outcomes.Count >= 3, "outcomes: " + string.Join(", ", outcomes.Select(pair => $"0x{pair.Key:X}={pair.Value}"))); + } +} diff --git a/tools/SharpEmu.Tools.PerfAudit/Benches.AgcBuilders.cs b/tools/SharpEmu.Tools.PerfAudit/Benches.AgcBuilders.cs index 438e2e163..886fa6713 100644 --- a/tools/SharpEmu.Tools.PerfAudit/Benches.AgcBuilders.cs +++ b/tools/SharpEmu.Tools.PerfAudit/Benches.AgcBuilders.cs @@ -142,6 +142,36 @@ void Bench(string id, string name, Action body, int perReset) c[CpuRegister.Rdi] = cb; c[CpuRegister.Rsi] = 1; AgcExports.DcbSetNumInstances(c); c[CpuRegister.Rdi] = cb; c[CpuRegister.Rsi] = 3; c[CpuRegister.Rdx] = 0x9_0000_0000; c[CpuRegister.Rcx] = 0; AgcExports.DcbDrawIndex(c); }, 400); + // DrawIndexIndirect with every register slot selected (bits 0-2, stage 5) and bit 32 clear. + Bench("c7", "DcbDrawIndexIndirect", c => { c[CpuRegister.Rdi] = cb; c[CpuRegister.Rsi] = 0x40; c[CpuRegister.Rdx] = 0xA008_4A07; AgcExports.DcbDrawIndexIndirect(c); }, 4000); + + // CreatePrimState(cx, uc, hs, gs, prim) over a GS and an HS whose specials select the GS + // output primitive, as a tessellated draw's state does; nothing in the command buffer. + var shaders = address + 0x20_0000; + var gsHeader = shaders; + var hsHeader = shaders + 0x100; + var gsSpecials = shaders + 0x200; + var hsSpecials = shaders + 0x300; + var primCx = shaders + 0x400; + var primUc = shaders + 0x500; + var header = new byte[0x60]; + BitConverter.TryWriteBytes(header.AsSpan(0x28), gsSpecials); + header[0x5A] = 2; + memory.TryWrite(gsHeader, header); + BitConverter.TryWriteBytes(header.AsSpan(0x28), hsSpecials); + header[0x5A] = 3; + memory.TryWrite(hsHeader, header); + var specials = new byte[0x30]; + for (var index = 0; index < specials.Length; index += 4) BitConverter.TryWriteBytes(specials.AsSpan(index), 0x100u + (uint)index); + BitConverter.TryWriteBytes(specials.AsSpan(0x0C), 0x24u); + memory.TryWrite(gsSpecials, specials); + BitConverter.TryWriteBytes(specials.AsSpan(0x0C), 0x08u); + memory.TryWrite(hsSpecials, specials); + Harness.Measure("c8", "CreatePrimState (GS + HS, cx and uc)", 1, 1, i => + { + ctx[CpuRegister.Rdi] = primCx; ctx[CpuRegister.Rsi] = primUc; ctx[CpuRegister.Rdx] = hsHeader; ctx[CpuRegister.Rcx] = gsHeader; ctx[CpuRegister.R8] = 0x11; + AgcExports.CreatePrimState(ctx); + }, unit: "call"); if (sink == long.MinValue) Console.WriteLine(sink); GuestGpuMemoryHook.Attach(null); } diff --git a/tools/SharpEmu.Tools.PerfAudit/PlanningSupport.cs b/tools/SharpEmu.Tools.PerfAudit/PlanningSupport.cs index 3cd8c7a8d..a8e1076d0 100644 --- a/tools/SharpEmu.Tools.PerfAudit/PlanningSupport.cs +++ b/tools/SharpEmu.Tools.PerfAudit/PlanningSupport.cs @@ -244,7 +244,6 @@ public ColorAttachmentAcquisition AcquireColorAttachment(in ColorTargetState tar return new ColorAttachmentAcquisition( target.Image, new GpuImageHandle(0x1000 + target.Image.Index), - ColorLayout, ImageSamples.TryGetValue(address, out var samples) ? samples : target.Resolution.Samples, metadataClear, clearValue); @@ -425,6 +424,11 @@ public void DrawMeshTasks(uint groupCountX, uint groupCountY, uint groupCountZ) public bool TryDispatchIndirect(ulong argumentsAddress) => false; + public bool TryDispatchIndirect(ulong argumentsAddress, ReadOnlySpan physicalAxisOfLogical) => false; + + public void TransitionDepthAttachment(in DepthAttachmentState depth, GpuImageAspect writeAspects) => + Calls.Add($"transition_depth {writeAspects}"); + public void ShaderWriteBarrier(GpuPipelineStage sourceStages) => Calls.Add($"write_barrier {sourceStages}"); public void ShaderWriteHazardBarrier() => Calls.Add("write_hazard_barrier"); @@ -570,6 +574,20 @@ public void RecordUnsupportedGraphics(VertexStageRegisters vertex, ContextRegist public List ExportMappings { get; } = new(); + public GraphicsPrograms GetGraphicsPrograms( + RegisterBanks banks, + ReadOnlySpan targetExportMapping, + bool pixelActive, + bool depthBound, + bool depthAspectBound, + bool stencilAspectBound, + bool triangleList, + int startInstanceUserData) + { + Calls.Add($"get_graphics_programs pixelActive={pixelActive}"); + return Graphics; + } + public GraphicsPrograms GetGraphicsPrograms( VertexStageRegisters vertex, PixelStageRegisters pixel, @@ -711,7 +729,7 @@ public static RegisterBanks Banks(uint primitiveType = PrimitiveTriangleList, bo context.ColorTargets[0] = RegisterWords.Color(ColorBase, 64, 64); context.RenderTargetMask = 0xF; context.ShaderInterface.ColorShaderMask = 0xF; - context.ScreenViewport.Viewports[0] = new ViewportRegisters { XScale = 32, XOffset = 32, YScale = -32, YOffset = 32, ZScale = 0.5f, ZOffset = 0.5f, MaxDepth = 1 }; + context.ScreenViewport.Primary = new ViewportRegisters { XScale = 32, XOffset = 32, YScale = -32, YOffset = 32, ZScale = 0.5f, ZOffset = 0.5f, MaxDepth = 1 }; if (withDepth) { context.DepthTarget = RegisterWords.Depth(DepthBase, 64, 64); From d7e5140bfc492111e53c78b9bd5cd3530ec8fb71 Mon Sep 17 00:00:00 2001 From: kuba Date: Sun, 15 Nov 2026 01:53:07 +0000 Subject: [PATCH 005/178] [Kernel] Native scePthreadGetthreadid answered from the fast-path block The per-host-thread GuestFastPath block gains the bound self handle's unique thread id at offset 24 (free until now). KernelPthreadState.GetCurrentThreadUniqueId publishes it whenever it answers for a bound guest thread, and only into a block whose self handle is that very thread; every path that clears or replaces the self handle (BindGuestThread, PublishHostSelf, Disable, UnbindCurrentThread, ForgetPublishedSelves, ReleaseThread) clears the id first. The stub for scePthreadGetthreadid and pthread_getthreadid_np answers the id and declines with no block, no self handle or no id. SHARPEMU_HLE_FAST_THREADID=0 keeps the export. Co-Authored-By: Claude --- .../Native/DirectExecutionBackend.FastPath.cs | 27 +++++- src/SharpEmu.HLE/GuestFastPath.cs | 34 ++++++- .../Kernel/KernelPthreadState.cs | 14 ++- .../Cpu/GuestFastPathStubTests.cs | 90 +++++++++++++++++++ 4 files changed, 162 insertions(+), 3 deletions(-) diff --git a/src/SharpEmu.Core/Cpu/Native/DirectExecutionBackend.FastPath.cs b/src/SharpEmu.Core/Cpu/Native/DirectExecutionBackend.FastPath.cs index 23257e6b2..fe6fbfd68 100644 --- a/src/SharpEmu.Core/Cpu/Native/DirectExecutionBackend.FastPath.cs +++ b/src/SharpEmu.Core/Cpu/Native/DirectExecutionBackend.FastPath.cs @@ -42,6 +42,12 @@ internal enum GuestFastPathStub /// sceKernelGetProcessTime: microseconds since process start. ProcessTimeMicroseconds, + /// + /// scePthreadGetthreadid / pthread_getthreadid_np: the unique id the managed export published + /// for the self handle bound to this host thread (GuestFastPath.BlockThreadUniqueIdOffset). + /// + PthreadGetthreadid, + /// /// An sceAgc command builder that appends one fixed-shape packet (see ): /// the stub stores the dwords and the cursor itself, as the title's own code does. @@ -78,6 +84,10 @@ internal enum GuestFastPathStub private const string PthreadSelfNid = "aI+OeCz8xrQ"; private const string PosixPthreadSelfNid = "EotR8a3ASf4"; + // scePthreadGetthreadid / pthread_getthreadid_np. + private const string PthreadGetthreadidNid = "EI-5-jlq2dE"; + private const string PosixPthreadGetthreadidNid = "3eqs37G74-s"; + // scePthreadGetspecific / pthread_getspecific. private const string PthreadGetspecificNid = "eoht7mQOCmo"; private const string PosixPthreadGetspecificNid = "0-KXaS70xy4"; @@ -233,6 +243,7 @@ private void ConfigureGuestFastPath() { PthreadSelfNid or PosixPthreadSelfNid => GuestFastPathStub.PthreadSelf, PthreadGetspecificNid or PosixPthreadGetspecificNid => GuestFastPathStub.PthreadGetspecific, + PthreadGetthreadidNid or PosixPthreadGetthreadidNid => GuestFastPathStub.PthreadGetthreadid, MemcpyNid or MemmoveNid => GuestFastPathStub.MemoryCopy, MemsetNid => GuestFastPathStub.MemorySet, ClockGettimeNid or KernelClockGettimeNid => GuestFastPathStub.ClockGettime, @@ -292,7 +303,9 @@ private unsafe bool TryCreateGuestFastPathStub(string nid, nint fallbackTrampoli var kind = ClassifyGuestFastPathStub(nid); if (kind == GuestFastPathStub.None || // The write watch inspects every managed guest write, which a native copy never reaches. - (kind is GuestFastPathStub.MemoryCopy or GuestFastPathStub.MemorySet && (!GuestMemoryCopyStubEnabled || GuestWriteWatch.Armed))) + (kind is GuestFastPathStub.MemoryCopy or GuestFastPathStub.MemorySet && (!GuestMemoryCopyStubEnabled || GuestWriteWatch.Armed)) || + // SHARPEMU_HLE_FAST_THREADID=0 keeps the thread-id query on the managed export. + (kind == GuestFastPathStub.PthreadGetthreadid && !SharpEmu.Libs.Kernel.KernelPthreadState.FastThreadIdEnabled)) { return false; } @@ -459,6 +472,18 @@ void EmitBranchToSlowPath(byte opcode) Emit(0x48, 0x8B, 0x40, checked((byte)GuestFastPath.BlockSelfHandleOffset)); break; + case GuestFastPathStub.PthreadGetthreadid: + // cmp qword [rax + SelfHandleOffset], 0 / je slow: nothing bound here. + Emit(0x48, 0x83, 0x78, checked((byte)GuestFastPath.BlockSelfHandleOffset), 0x00); + EmitJumpToSlowPath(); + // cmp qword [rax + ThreadUniqueIdOffset], 0 / je slow: the export has not + // answered for this handle yet (it publishes the id when it does). + Emit(0x48, 0x83, 0x78, checked((byte)GuestFastPath.BlockThreadUniqueIdOffset), 0x00); + EmitJumpToSlowPath(); + // mov rax, [rax + ThreadUniqueIdOffset] + Emit(0x48, 0x8B, 0x40, checked((byte)GuestFastPath.BlockThreadUniqueIdOffset)); + break; + case GuestFastPathStub.PthreadGetspecific: // cmp qword [rax + TlsValuesOffset], 0 / je slow: this thread // has no value table published. diff --git a/src/SharpEmu.HLE/GuestFastPath.cs b/src/SharpEmu.HLE/GuestFastPath.cs index 2e7e31bc5..1de5b99bb 100644 --- a/src/SharpEmu.HLE/GuestFastPath.cs +++ b/src/SharpEmu.HLE/GuestFastPath.cs @@ -48,6 +48,14 @@ public static unsafe class GuestFastPath /// Byte offset of the pthread_self fast-path hit counter. public const int BlockSelfHitsOffset = 16; + /// + /// Byte offset of the unique thread id scePthreadGetthreadid answers for the self handle at + /// . Zero until the managed export has answered for that + /// handle (), and cleared whenever the self handle is, so + /// the native stub never answers for a handle the id was not published with. + /// + public const int BlockThreadUniqueIdOffset = 24; + /// Byte offset of the pthread_getspecific fast-path hit counter. public const int BlockGetspecificHitsOffset = 32; @@ -115,6 +123,7 @@ public static void Disable() if (block != 0) { *(ulong*)(block + BlockSelfHandleOffset) = 0; + *(ulong*)(block + BlockThreadUniqueIdOffset) = 0; *(nint*)(block + BlockTlsValuesOffset) = 0; } } @@ -139,8 +148,9 @@ public static void BindGuestThread(ulong guestThreadHandle) } // Clear the self handle first so a stub can never answer with a handle - // that no longer owns this host thread. + // that no longer owns this host thread, and its thread id with it. *(ulong*)(block + BlockSelfHandleOffset) = 0; + *(ulong*)(block + BlockThreadUniqueIdOffset) = 0; var tlsHandle = guestThreadHandle != 0 ? guestThreadHandle : _hostThreadHandle; *(nint*)(block + BlockTlsValuesOffset) = tlsHandle == 0 ? 0 : GetOrCreateTable(tlsHandle); *(ulong*)(block + BlockSelfHandleOffset) = guestThreadHandle; @@ -171,9 +181,28 @@ public static void PublishHostSelf(ulong hostThreadHandle) return; } + // An id a racing ForgetPublishedSelves left behind belongs to the handle it cleared. + *(ulong*)(block + BlockThreadUniqueIdOffset) = 0; *(ulong*)(block + BlockSelfHandleOffset) = hostThreadHandle; } + /// + /// Lets the native scePthreadGetthreadid stub answer on the calling + /// host thread while is the self handle its block publishes. + /// The id is a function of the handle (KernelPthreadState never reassigns one), and every + /// path that clears or replaces the self handle clears the id first. + /// + public static void PublishThreadUniqueId(ulong threadHandle, ulong uniqueId) + { + var block = _block; + if (block == 0 || threadHandle == 0 || *(ulong*)(block + BlockSelfHandleOffset) != threadHandle) + { + return; + } + + *(ulong*)(block + BlockThreadUniqueIdOffset) = uniqueId; + } + /// /// Records the calling host thread's own pthread handle - the one /// KernelPthreadState reports when no guest thread is bound - so @@ -209,6 +238,7 @@ public static void UnbindCurrentThread() if (block != 0) { *(ulong*)(block + BlockSelfHandleOffset) = 0; + *(ulong*)(block + BlockThreadUniqueIdOffset) = 0; *(nint*)(block + BlockTlsValuesOffset) = 0; } } @@ -226,6 +256,7 @@ public static void ForgetPublishedSelves() foreach (var block in Blocks) { Volatile.Write(ref *(ulong*)(block + BlockSelfHandleOffset), 0); + Volatile.Write(ref *(ulong*)(block + BlockThreadUniqueIdOffset), 0); } } } @@ -437,6 +468,7 @@ public static void ReleaseThread(ulong threadHandle) if (block != 0 && *(ulong*)(block + BlockSelfHandleOffset) == threadHandle) { *(ulong*)(block + BlockSelfHandleOffset) = 0; + *(ulong*)(block + BlockThreadUniqueIdOffset) = 0; *(nint*)(block + BlockTlsValuesOffset) = 0; } else if (block != 0 && _hostThreadHandle == threadHandle) diff --git a/src/SharpEmu.Libs/Kernel/KernelPthreadState.cs b/src/SharpEmu.Libs/Kernel/KernelPthreadState.cs index 519b486be..24c490b7c 100644 --- a/src/SharpEmu.Libs/Kernel/KernelPthreadState.cs +++ b/src/SharpEmu.Libs/Kernel/KernelPthreadState.cs @@ -50,12 +50,24 @@ internal static ulong GetCurrentThreadHandle() return _currentThreadHandle; } + // SHARPEMU_HLE_FAST_THREADID=0 keeps scePthreadGetthreadid on the managed export. + internal static readonly bool FastThreadIdEnabled = + !string.Equals(Environment.GetEnvironmentVariable("SHARPEMU_HLE_FAST_THREADID"), "0", StringComparison.Ordinal); + internal static ulong GetCurrentThreadUniqueId() { var guestThreadHandle = GuestThreadExecution.CurrentGuestThreadHandle; if (guestThreadHandle != 0) { - return EnsureGuestThreadIdentity(guestThreadHandle).UniqueId; + var uniqueId = EnsureGuestThreadIdentity(guestThreadHandle).UniqueId; + // The native scePthreadGetthreadid stub answers from here on while this handle stays + // bound to the host thread (a no-op unless the block publishes this very handle). + if (FastThreadIdEnabled) + { + GuestFastPath.PublishThreadUniqueId(guestThreadHandle, uniqueId); + } + + return uniqueId; } EnsureCurrentThreadRegistered(); diff --git a/tests/SharpEmu.Libs.Tests/Cpu/GuestFastPathStubTests.cs b/tests/SharpEmu.Libs.Tests/Cpu/GuestFastPathStubTests.cs index 2f92a4bd9..197dfb1c7 100644 --- a/tests/SharpEmu.Libs.Tests/Cpu/GuestFastPathStubTests.cs +++ b/tests/SharpEmu.Libs.Tests/Cpu/GuestFastPathStubTests.cs @@ -221,6 +221,96 @@ public void GetspecificStub_ReadsTheThreadCurrentlyBound() Assert.Equal(0x1111UL, harness.Call(KeyBase + 2)); } + // scePthreadGetthreadid answers the id the managed export published for the self handle bound + // here, and nothing else: every bind, rebind, forget, unbind and release takes it back. + [Fact] + public void ThreadIdStub_AnswersOnlyTheIdPublishedForTheBoundHandle() + { + if (!CanRunStubs()) + { + return; + } + + using var harness = new StubHarness(DirectExecutionBackend.GuestFastPathStub.PthreadGetthreadid); + var first = NewHandle(); + var second = NewHandle(); + + // Nothing bound: the export answers (and publishes nothing for a handle that is not bound). + Assert.Equal(RaxSentinel, harness.Call(0)); + GuestFastPath.PublishThreadUniqueId(first, 41); + Assert.Equal(RaxSentinel, harness.Call(0)); + + // Bound, but the export has not answered yet. + harness.Bind(first); + Assert.Equal(RaxSentinel, harness.Call(0)); + GuestFastPath.PublishThreadUniqueId(first, 41); + Assert.Equal(41UL, harness.Call(0)); + // Another handle's id never lands in this block. + GuestFastPath.PublishThreadUniqueId(second, 42); + Assert.Equal(41UL, harness.Call(0)); + + // Rebinding clears the id until the export answers for the new handle, both ways. + harness.Bind(second); + Assert.Equal(RaxSentinel, harness.Call(0)); + GuestFastPath.PublishThreadUniqueId(second, 42); + Assert.Equal(42UL, harness.Call(0)); + harness.Bind(first); + Assert.Equal(RaxSentinel, harness.Call(0)); + GuestFastPath.PublishThreadUniqueId(first, 41); + Assert.Equal(41UL, harness.Call(0)); + + // A scheduler that forgot its threads, an unbind and a thread exit all take it back. + GuestFastPath.ForgetPublishedSelves(); + Assert.Equal(RaxSentinel, harness.Call(0)); + harness.Bind(first); + GuestFastPath.PublishThreadUniqueId(first, 41); + GuestFastPath.UnbindCurrentThread(); + Assert.Equal(RaxSentinel, harness.Call(0)); + harness.Bind(first); + GuestFastPath.PublishThreadUniqueId(first, 41); + GuestFastPath.ReleaseThread(first); + Assert.Equal(RaxSentinel, harness.Call(0)); + + // A host self published after a forget never inherits a guest thread's id. + harness.Bind(first); + GuestFastPath.PublishThreadUniqueId(first, 41); + harness.Bind(0); + GuestFastPath.PublishHostSelf(second); + Assert.Equal(RaxSentinel, harness.Call(0)); + } + + // The export publishes the id it answers for a bound guest thread, and the stub then answers + // exactly that; leaving the guest thread takes it back. + [Fact] + public void ThreadIdStub_AnswersWhatTheExportAnsweredForTheBoundGuestThread() + { + if (!CanRunStubs()) + { + return; + } + + using var harness = new StubHarness(DirectExecutionBackend.GuestFastPathStub.PthreadGetthreadid); + var handle = NewHandle(); + var previous = GuestThreadExecution.EnterGuestThread(handle); + try + { + Assert.Equal(RaxSentinel, harness.Call(0)); + var ctx = new CpuContext(new FakeCpuMemory(0x1_0000_0000, 0x1000), Generation.Gen5); + Assert.Equal(0, SharpEmu.Libs.Kernel.KernelPthreadCompatExports.PthreadGetthreadid(ctx)); + var id = ctx[CpuRegister.Rax]; + Assert.NotEqual(0UL, id); + Assert.Equal(id, harness.Call(0)); + SharpEmu.Libs.Kernel.KernelPthreadCompatExports.PosixPthreadGetthreadidNp(ctx); + Assert.Equal(id, ctx[CpuRegister.Rax]); + } + finally + { + GuestThreadExecution.RestoreGuestThread(previous); + } + + Assert.Equal(RaxSentinel, harness.Call(0)); + } + /// /// Measures the per-call cost the stubs replace. The managed gateway costs /// ~2.9 us/call as measured in-game with SHARPEMU_PERF_HLE=1; the stub must From 75ce58465c051a1e5eca46a454926ff65a5feefc Mon Sep 17 00:00:00 2001 From: kuba Date: Sun, 15 Nov 2026 01:57:28 +0000 Subject: [PATCH 006/178] [Metal] Answer a read-only guest-range binding from the binding before it while its inputs stand For every read-only storage buffer of every draw, BindResources checked the mapping twice, flushed the images over the range, ordered it after deferred copies and staged stores, looked for a staged copy to share and resolved its window; ObtainBuffer ran the same chain for index and indirect buffers. A worker-owned MetalReadBindingMemo keeps the window range a read-only binding resolved to, keyed by (address, size, compute stage), and answers the next binding of the range while: - the range translates to the same backing alias (read on every hit, so a remap misses; an alias over the whole range is what both mapping checks answered); - the stamp holds: guest-memory submission, window partition and trap versions (holes, stale windows), ImageSetVersion and Epochs.GpuModified, read per lookup and on both sides of the chain an entry is stored from (a miss earlier in a draw can move the cuts); - there is no deferred fill, deferred label copy or staged copy at all (checked live, which leaves the ordering and sharing steps nothing to do), no trap, no released single-copy chunk, and no trace. Only answers from the in-place window path are kept, for ranges mapped whole whose flush found no GPU-modified image (MetalImageCache.FlushGpuWrites now says whether it did). Written bindings always take the full chain. The design's mapping-version stamp (DeviceAddressMappingVersion) is replaced by the alias check: span registrations do not cover every remap of backed memory. SHARPEMU_METAL_V2_READ_BINDING_MEMO=0 takes the full chain for every binding; =verify runs it behind every hit and raises a fatal error on a different range or a found image. The PERF line gains read_binding_memo=(hits,misses,stores,verified) and, for a later stage binding plan, bind_shape=(binds, image_set_moves, binding_epoch_moves, snapshot_repeats per array among the last 8 per stage kind, buffers_read_only, buffers_written, tiny_pass_dummies). DsDrawCostBenchTests (ROUNDS=150, ABAB x3, load 5.1-5.8): draws 3.274-3.350 -> 3.271-3.305 us (within noise), dispatches 4.35-4.41 -> 4.22-4.26 us; checksums A971C9681B3C2325 / 4FAE6605365DFE0E equal with the memo at 0, on and verify; hits 91% of draw lookups, 98% of dispatch lookups. Co-Authored-By: Claude --- .../SharpEmu.Gpu.Metal/V2/MetalGuestMemory.cs | 43 +++- .../SharpEmu.Gpu.Metal/V2/MetalImageCache.cs | 9 +- .../V2/MetalReadBindingMemo.cs | 84 ++++++++ .../V2/MetalRenderHost.Descriptors.cs | 37 +++- .../V2/MetalRenderHost.ReadBindingMemo.cs | 192 ++++++++++++++++++ .../V2/MetalRenderHost.StagedStorage.cs | 11 +- .../SharpEmu.Gpu.Metal/V2/MetalRenderHost.cs | 25 ++- .../MetalClearFoldingTests.ReadBindingMemo.cs | 157 ++++++++++++++ .../MetalClearFoldingTests.cs | 10 + .../Scenes/BindingReuseSceneTests.cs | 81 ++++++++ .../Scenes/DsDrawCostBenchTests.cs | 6 + 11 files changed, 639 insertions(+), 16 deletions(-) create mode 100644 src/graphics/SharpEmu.Gpu.Metal/V2/MetalReadBindingMemo.cs create mode 100644 src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.ReadBindingMemo.cs create mode 100644 tests/SharpEmu.Gpu.Metal.Tests/MetalClearFoldingTests.ReadBindingMemo.cs diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalGuestMemory.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalGuestMemory.cs index afb8fdbbd..d84c614b8 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalGuestMemory.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalGuestMemory.cs @@ -728,10 +728,15 @@ public MetalGuestRange Resolve(ulong gpuVa, ulong size, bool whole = false) /// The window a binding of the range reads and writes in place; false when no one /// window covers it and it has to be staged (). /// - public bool TryResolveInPlace(ulong gpuVa, ulong size, out MetalGuestRange range) + public bool TryResolveInPlace(ulong gpuVa, ulong size, out MetalGuestRange range) => + TryResolveInPlace(gpuVa, size, out range, out _); + + /// , with the backing alias the range was placed by. + public bool TryResolveInPlace(ulong gpuVa, ulong size, out MetalGuestRange range, out ulong alias) { range = default; - if (StageEverything || !TryResolveWindow(gpuVa, size, out range)) + alias = 0; + if (StageEverything || !TryResolveWindow(gpuVa, size, out range, out alias)) { return false; } @@ -740,6 +745,26 @@ public bool TryResolveInPlace(ulong gpuVa, ulong size, out MetalGuestRange range return true; } + /// + /// What an in-place answer depends on besides the range's backing alias (MetalReadBindingMemo): the submission + /// (windows are pinned and touched per command buffer, and a pinned window keeps its cut and its buffer until the + /// next one), the window cuts (a window's buffer is only ever replaced by a cut change, MetalWindowPartition.Replace) + /// and the single-copy holes and stale windows (each change moves the trap version). Read on the worker, as the + /// window memo reads them. + /// + internal (ulong Serial, long Partition, long Trap) InPlaceStamp => + (Volatile.Read(ref _submissionSerial), _partition.Version, Volatile.Read(ref _trapVersion)); + + /// + /// Whether of a range that translates to , resolved in + /// place earlier at the current , would give the same window range now and do nothing + /// else: nothing stages everything, no trap records bindings, and no chunk of the range is released (the window + /// memo's own conditions; with them the full path restores, fills and places nothing). + /// + internal bool InPlaceAnswerStands(ulong alias, ulong size) => + !StageEverything && Trap is null && InAlias(alias, size) && + !(_singleCopy is { } singleCopy && singleCopy.AnyReleased(alias - _aliasBase, size)); + /// True when the range is a window's own bytes - guest memory - rather than a ring copy. public bool IsInPlace(in MetalGuestRange range) { @@ -1146,12 +1171,15 @@ private void PublishWindowMemoLocked(MetalWindowPartition.Window window, ulong o new WindowMemoEntry(window, coverStart, coverEnd, _submissionSerial, version, _trapVersion)); } - private bool TryResolveWindow(ulong gpuVa, ulong size, out MetalGuestRange resolved, bool warn = true) + private bool TryResolveWindow(ulong gpuVa, ulong size, out MetalGuestRange resolved, bool warn = true) => + TryResolveWindow(gpuVa, size, out resolved, out _, warn); + + private bool TryResolveWindow(ulong gpuVa, ulong size, out MetalGuestRange resolved, out ulong alias, bool warn = true) { - var ok = TryResolveWindowCore(gpuVa, size, out resolved, warn, WindowMemoEnabled); + var ok = TryResolveWindowCore(gpuVa, size, out resolved, out alias, warn, WindowMemoEnabled); if (WindowMemoVerify && WindowMemoEnabled) { - var fullOk = TryResolveWindowCore(gpuVa, size, out var full, warn: false, useMemo: false); + var fullOk = TryResolveWindowCore(gpuVa, size, out var full, out _, warn: false, useMemo: false); if (ok != fullOk || (ok && resolved != full)) { throw GpuFatal.Fatal( @@ -1163,10 +1191,11 @@ private bool TryResolveWindow(ulong gpuVa, ulong size, out MetalGuestRange resol return ok; } - private bool TryResolveWindowCore(ulong gpuVa, ulong size, out MetalGuestRange resolved, bool warn, bool useMemo) + private bool TryResolveWindowCore(ulong gpuVa, ulong size, out MetalGuestRange resolved, out ulong alias, bool warn, bool useMemo) { using var phaseScope = SharpEmu.Libs.VideoOut.RenderPhaseProfile.MeasureDetail(SharpEmu.Libs.VideoOut.RenderPhaseProfile.Phase.GuestWindowResolve); resolved = default; + alias = 0; if (size == 0 || gpuVa == 0 || size > ulong.MaxValue - gpuVa) { return false; @@ -1175,7 +1204,7 @@ private bool TryResolveWindowCore(ulong gpuVa, ulong size, out MetalGuestRange r // A range that crosses the edge between two mappings of one allocation is // still contiguous in the backing, so it still has one window address; the // single-mapping test alone sent those to the staging ring. - if (!_backing.TryResolveBackingAliasSpan(gpuVa, size, out var alias) || !InAlias(alias, size)) + if (!_backing.TryResolveBackingAliasSpan(gpuVa, size, out alias) || !InAlias(alias, size)) { if (warn) { diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.cs index 30872b802..ef5c7bf73 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.cs @@ -1912,20 +1912,23 @@ public void RefreshImage(ResourceSlotIdentifier imageIdentifier) /// memory. Called before a buffer binding, an incompatible image request or a /// host read can observe the bytes. says the consumer also /// writes them, and is followed by over the range. + /// True when a GPU-modified image overlapped the range (it was published or written back). /// - public void FlushGpuWrites(ulong address, ulong size, MetalWritebackCause cause, bool written = false) + public bool FlushGpuWrites(ulong address, ulong size, MetalWritebackCause cause, bool written = false) { using var phaseScope = SharpEmu.Libs.VideoOut.RenderPhaseProfile.MeasureDetail(SharpEmu.Libs.VideoOut.RenderPhaseProfile.Phase.GpuWriteFlush); if (!IsValidRange(address, size) || !_pageOwners.MayHaveOwners(address, size)) { - return; + return false; } + var found = false; using var held = _lock.Hold(); foreach (var imageIdentifier in FindImagesInRange(address, size, pageOverlap: false)) { if (_slots.TryGet(imageIdentifier) is { } image && image.GpuOverlaps(address, size)) { + found = true; if (TryPublishConsumerRunLocked(image, address, size, cause, written)) { continue; @@ -1934,6 +1937,8 @@ public void FlushGpuWrites(ulong address, ulong size, MetalWritebackCause cause, WriteBackToGuest(image, cause); } } + + return found; } /// A GPU shader or transfer wrote these guest bytes: the images reload. diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalReadBindingMemo.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalReadBindingMemo.cs new file mode 100644 index 000000000..e9e12d9a8 --- /dev/null +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalReadBindingMemo.cs @@ -0,0 +1,84 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +namespace SharpEmu.Gpu.Metal.V2; + +/// +/// The window range a read-only guest-range binding resolved to (MetalRenderHost.ResolveStorageBuffer through +/// MetalGuestMemory.TryResolveInPlace), kept for the bindings of the same range after it. The worker's alone: no +/// locks. An entry is kept only for a range that was mapped whole, over which the flush found no GPU-modified image, +/// and that resolved in place to a window; it answers while its equals the current one and the +/// range still translates to the same backing alias. What the caller checks live on every hit (no deferred fill or +/// label copy, no staged copy, no trace) is not part of the stamp. +/// +internal sealed class MetalReadBindingMemo +{ + /// + /// What the skipped chain read that can change between two bindings of one range, other than the mapping + /// (checked through the alias) and what the caller checks live. + /// + /// The guest memory's submission: windows are pinned and touched per command buffer. + /// The window cuts; a window's buffer is replaced only with a cut change. + /// Single-copy holes and stale windows (MetalGuestMemory's trap version). + /// Images added or dropped: which images the flush could find over the range. + /// An image going GPU-modified: which of them the flush would write back. + internal readonly record struct Stamp(ulong Serial, long Partition, long Trap, long ImageSet, long GpuModified); + + private struct Entry + { + public ulong Address; + public ulong Size; + public ulong Alias; + public bool Compute; + public bool Valid; + public Stamp Stamp; + public MetalGuestRange Range; + } + + private const int Slots = 1024; + private readonly Entry[] _entries = new Entry[Slots]; + + public long Hits; + public long Misses; + public long Stores; + public long Verified; + + private static int SlotOf(ulong address, ulong size, bool compute) => + (int)((((address >> 4) * 0x9E3779B97F4A7C15UL) ^ (size * 0xC2B2AE3D27D4EB4FUL) ^ (compute ? 1UL : 0UL)) >> 54) & (Slots - 1); + + /// The range kept for this binding at this stamp and alias, if one is. + public bool TryGet(ulong address, ulong size, bool compute, ulong alias, in Stamp stamp, out MetalGuestRange range) + { + ref var entry = ref _entries[SlotOf(address, size, compute)]; + if (entry.Valid && entry.Address == address && entry.Size == size && entry.Compute == compute && + entry.Alias == alias && entry.Stamp == stamp) + { + range = entry.Range; + return true; + } + + range = default; + return false; + } + + public void Store(ulong address, ulong size, bool compute, ulong alias, in Stamp stamp, in MetalGuestRange range) + { + ref var entry = ref _entries[SlotOf(address, size, compute)]; + entry.Address = address; + entry.Size = size; + entry.Alias = alias; + entry.Compute = compute; + entry.Stamp = stamp; + entry.Range = range; + entry.Valid = true; + Stores++; + } + + /// hits, misses, stores and verified hits since the last call; resets them. + public string TakeCounters() + { + var text = $"hits={Hits} misses={Misses} stores={Stores} verified={Verified}"; + Hits = Misses = Stores = Verified = 0; + return text; + } +} diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Descriptors.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Descriptors.cs index b684a7808..04bdee2d1 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Descriptors.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Descriptors.cs @@ -851,6 +851,7 @@ public void BindResources(IPreparedBindings prepared) var stage = (MetalStageBindings)prepared; var info = stage.Program.Resources!.Info; var snapshot = stage.StageResources.Resources; + NoteBindShape(stage, snapshot); for (var index = 0; index < stage.ImageCount; index++) { if (index == stage.MovieLuma || index == stage.MovieChroma) @@ -939,6 +940,30 @@ public void BindResources(IPreparedBindings prepared) continue; } + var written = info.Buffers[index].Written; + var computeStage = stage.Program.Stage == ShaderStageKind.Compute; + if (written) + { + _writtenBufferBinds++; + } + else + { + _readOnlyBufferBinds++; + // A range bound read-only before, whose binding still stands (MetalRenderHost.ReadBindingMemo.cs): + // mapped whole, nothing to flush or order, the same window. + if (TryReadBindingMemo(descriptor.Address, requested, computeStage, out var memo)) + { + if (ReadBindingMemoVerify) + { + VerifyReadBinding(descriptor.Address, requested, computeStage, MetalWritebackCause.StorageDescriptor, memo); + } + + stage.Buffers[index] = memo; + stage.BufferLengths[index] = BoundBufferBytes(requested, memo); + continue; + } + } + // A range mapped whole - nearly every binding - is answered by one query; ClampMappedSize // asks again from its first byte only for a range that runs past its mapping. bool readable; @@ -962,9 +987,14 @@ public void BindResources(IPreparedBindings prepared) } var size = mappedWhole ? requested : ClampMappedSize(descriptor.Address, requested); - var written = info.Buffers[index].Written; - FlushGpuWrites(descriptor.Address, size, MetalWritebackCause.StorageDescriptor, written); - var range = ResolveStorageBuffer(descriptor.Address, size, written, stage.Program.Stage == ShaderStageKind.Compute); + var memoStamp = !written && mappedWhole && ReadBindingMemoEnabled ? ReadBindingStamp() : default; + var flushFoundImage = _imageCache.FlushGpuWrites(descriptor.Address, size, MetalWritebackCause.StorageDescriptor, written); + var range = ResolveStorageBuffer(descriptor.Address, size, written, computeStage, out var inPlaceAlias); + if (!written && mappedWhole && ReadBindingMemoEnabled) + { + StoreReadBinding(descriptor.Address, size, computeStage, memoStamp, flushFoundImage, inPlaceAlias, range); + } + // The text is built only when the trace is on: this runs per storage buffer per draw. if (_traceBufferUserAddress != 0) { @@ -1738,6 +1768,7 @@ private void WriteTextureField( var dummy = TinyPassDummyTexture(texture, resource); if (dummy != 0) { + _tinyPassDummies++; BinaryPrimitives.WriteUInt64LittleEndian( span[(index * sizeof(ulong))..], MetalNative.SendGpuResourceId(dummy, SelGpuResourceId)); NoteUsedResource(dummy, Mtl.ResourceUsageRead); diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.ReadBindingMemo.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.ReadBindingMemo.cs new file mode 100644 index 000000000..6a13f9bb0 --- /dev/null +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.ReadBindingMemo.cs @@ -0,0 +1,192 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using SharpEmu.Libs.Gpu.Rendering; +using SharpEmu.ShaderCompiler.Resources; + +namespace SharpEmu.Gpu.Metal.V2; + +/// +/// Read-only guest-range bindings answered from the binding before them (MetalReadBindingMemo). For every read-only +/// storage buffer of every draw, BindResources asked whether the range was mapped (twice), flushed the images over it, +/// ordered it after deferred copies and staged stores, looked for a staged copy to share, and resolved its window +/// (translation, window memo, census); ObtainBuffer did the same for index and indirect buffers. Their inputs rarely +/// change from one draw to the next. Demon's Souls binds ~7000 draws a frame, most of them the same few vertex and +/// constant buffers. +/// +/// A hit skips that chain, which is sound while each of its steps would do nothing and answer as it did: +/// +/// The mapping checks and the window's translation: the range translates to the backing alias it was placed by +/// (checked on every hit, so a remap misses whatever moved it); a range whose alias spans it is mapped whole, which +/// is what both mapping checks answered. +/// The image flush: an entry is kept only when the flush found no GPU-modified image over the range, and that +/// stays so while no image is added or dropped (ImageSetVersion) and none goes GPU-modified (Epochs.GpuModified); +/// an image's guest range never changes in place. +/// Deferred fills and label copies, staged copies and their recorded stores: checked live, a hit only while +/// there are none at all, which leaves OrderAfterDeferredCopies, TryShare and OrderAfterStagedStores nothing to +/// do. +/// The window: the same command buffer, window cuts and single-copy holes and stale windows +/// (MetalGuestMemory.InPlaceStamp), no trap and no released chunk under the range +/// (MetalGuestMemory.InPlaceAnswerStands). The census mark is made again. +/// No trace or dump that reports bindings is on. +/// +/// The stamp is read for each lookup and on both sides of the chain an entry is stored from (a miss earlier in a +/// draw can move the window cuts). Written bindings always take the full chain: their invalidation and write record +/// must run in order. SHARPEMU_METAL_V2_READ_BINDING_MEMO=0 takes the full chain for every binding; =verify takes it +/// on every hit too and raises a fatal error when the two answers differ. +/// +internal sealed partial class MetalRenderHost +{ + private static readonly string? ReadBindingMemoSetting = + Environment.GetEnvironmentVariable("SHARPEMU_METAL_V2_READ_BINDING_MEMO"); + + internal bool ReadBindingMemoEnabled { get; set; } = ReadBindingMemoSetting != "0"; + + internal bool ReadBindingMemoVerify { get; set; } = + ReadBindingMemoSetting == "verify" || Environment.GetEnvironmentVariable("SHARPEMU_PERF_VERIFY") == "1"; + + private readonly MetalReadBindingMemo _readBindingMemo = new(); + + internal (long Hits, long Misses, long Stores, long Verified) ReadBindingMemoCounts => + (_readBindingMemo.Hits, _readBindingMemo.Misses, _readBindingMemo.Stores, _readBindingMemo.Verified); + + // Nothing that reports bindings is on. + private bool ReadBindingTracesOff => + _traceBufferUserAddress == 0 && _traceRecordChain.Length != 6 && _traceBufferAtCompletion.Length != 4 && + _dumpBufferHashes.Count == 0 && TracedRingRange.High == 0 && _slotTrap is null; + + // What leaves the ordering and sharing steps of the chain nothing to do, whatever the range. + private bool ReadBindingMemoApplies => + ReadBindingMemoEnabled && _deferredFills.Count == 0 && _deferredLabelCopies.Count == 0 && + _stagedStorageCopies is not { Count: > 0 } && ReadBindingTracesOff; + + private MetalReadBindingMemo.Stamp ReadBindingStamp() + { + var (serial, partition, trap) = _guestMemory.InPlaceStamp; + return new MetalReadBindingMemo.Stamp(serial, partition, trap, _imageCache.ImageSetVersion, _imageCache.Epochs.GpuModified); + } + + /// The window range a read-only binding of the range resolved to before, if it still stands. + private bool TryReadBindingMemo(ulong address, ulong size, bool computeStage, out MetalGuestRange range) + { + range = default; + if (!ReadBindingMemoEnabled) + { + return false; + } + + if (!ReadBindingMemoApplies || !_backing.TryResolveBackingAliasSpan(address, size, out var alias) || + !_readBindingMemo.TryGet(address, size, computeStage, alias, ReadBindingStamp(), out range) || + !_guestMemory.InPlaceAnswerStands(alias, size)) + { + _readBindingMemo.Misses++; + range = default; + return false; + } + + _readBindingMemo.Hits++; + MetalGpuReferenceCensus.Mark(address, size); + return true; + } + + // After the full chain of a read-only binding: kept when the flush found no image over the range, the range + // resolved in place, and nothing the stamp holds moved while the chain ran. + private void StoreReadBinding( + ulong address, ulong size, bool computeStage, in MetalReadBindingMemo.Stamp before, bool flushFoundImage, + ulong inPlaceAlias, in MetalGuestRange range) + { + if (flushFoundImage || inPlaceAlias == 0 || !range.IsValid || !ReadBindingMemoEnabled || !ReadBindingTracesOff || + ReadBindingStamp() != before || !_guestMemory.InPlaceAnswerStands(inPlaceAlias, size)) + { + return; + } + + _readBindingMemo.Store(address, size, computeStage, inPlaceAlias, before, range); + } + + // =verify: the full chain behind a hit, which must give the same range and find no image to flush. + private void VerifyReadBinding(ulong address, ulong size, bool computeStage, MetalWritebackCause cause, in MetalGuestRange memo) + { + var flushed = _imageCache.FlushGpuWrites(address, size, cause, written: false); + var full = ResolveStorageBuffer(address, size, written: false, computeStage, out var alias); + if (flushed || alias == 0 || full != memo) + { + throw Fatal( + $"A memoised read-only binding disagrees with the full path: address=0x{address:X16} size=0x{size:X} " + + $"compute={computeStage} memo={memo} full={full} in_place={alias != 0} flushed_image={flushed}."); + } + + _readBindingMemo.Verified++; + } + + // ---- What a later stage binding plan would hit (the PERF line's bind_shape): ---- + + private long _bindCalls; + private long _bindImageSetMoves; + private long _bindBindingEpochMoves; + private long _lastBindImageSet = -1; + private long _lastBindBindingEpoch = -1; + private long _readOnlyBufferBinds; + private long _writtenBufferBinds; + private long _tinyPassDummies; + + // Per stage kind, the last eight Images, Samplers and Buffers arrays a snapshot bound, and how often one repeated. + private const int SnapshotRefSlots = 8; + private readonly object?[] _snapshotRefs = new object?[8 * 3 * SnapshotRefSlots]; + private readonly int[] _snapshotRefNext = new int[8 * 3]; + private readonly long[] _snapshotRefRepeats = new long[3]; + private long _snapshotRefChecks; + + private void NoteBindShape(MetalStageBindings stage, ResourceSnapshot snapshot) + { + _bindCalls++; + var imageSet = _imageCache.ImageSetVersion; + var bindingEpoch = _imageCache.Epochs.Binding; + if (imageSet != _lastBindImageSet) + { + _bindImageSetMoves++; + _lastBindImageSet = imageSet; + } + + if (bindingEpoch != _lastBindBindingEpoch) + { + _bindBindingEpochMoves++; + _lastBindBindingEpoch = bindingEpoch; + } + + var kind = (int)stage.Program.Stage & 7; + _snapshotRefChecks++; + NoteSnapshotRef(kind, 0, snapshot.Images); + NoteSnapshotRef(kind, 1, snapshot.Samplers); + NoteSnapshotRef(kind, 2, snapshot.Buffers); + } + + private void NoteSnapshotRef(int kind, int array, object reference) + { + var ring = (kind * 3) + array; + var refs = _snapshotRefs.AsSpan(ring * SnapshotRefSlots, SnapshotRefSlots); + foreach (var seen in refs) + { + if (ReferenceEquals(seen, reference)) + { + _snapshotRefRepeats[array]++; + return; + } + } + + refs[_snapshotRefNext[ring]] = reference; + _snapshotRefNext[ring] = (_snapshotRefNext[ring] + 1) % SnapshotRefSlots; + } + + private string TakeReadBindingCounters() + { + var text = $"read_binding_memo=({_readBindingMemo.TakeCounters()}) bind_shape=(binds={_bindCalls} " + + $"image_set_moves={_bindImageSetMoves} binding_epoch_moves={_bindBindingEpochMoves} " + + $"snapshot_repeats=[images={_snapshotRefRepeats[0]},samplers={_snapshotRefRepeats[1]},buffers={_snapshotRefRepeats[2]}]/{_snapshotRefChecks} " + + $"buffers_read_only={_readOnlyBufferBinds} buffers_written={_writtenBufferBinds} tiny_pass_dummies={_tinyPassDummies})"; + _bindCalls = _bindImageSetMoves = _bindBindingEpochMoves = _readOnlyBufferBinds = _writtenBufferBinds = 0; + _tinyPassDummies = _snapshotRefChecks = 0; + Array.Clear(_snapshotRefRepeats); + return text; + } +} diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.StagedStorage.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.StagedStorage.cs index 2be3016a1..6856510de 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.StagedStorage.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.StagedStorage.cs @@ -20,8 +20,14 @@ internal sealed partial class MetalRenderHost /// range, otherwise a staged copy that sees the GPU's earlier writes and whose stores /// reach guest memory (). /// - internal MetalGuestRange ResolveStorageBuffer(ulong address, ulong size, bool written, bool computeStage = false) + internal MetalGuestRange ResolveStorageBuffer(ulong address, ulong size, bool written, bool computeStage = false) => + ResolveStorageBuffer(address, size, written, computeStage, out _); + + // inPlaceAlias: the backing alias MetalGuestMemory.TryResolveInPlace placed the range by when the range is its + // window, else 0 (MetalReadBindingMemo). + private MetalGuestRange ResolveStorageBuffer(ulong address, ulong size, bool written, bool computeStage, out ulong inPlaceAlias) { + inPlaceAlias = 0; using var phaseScope = SharpEmu.Libs.VideoOut.RenderPhaseProfile.MeasureDetail(SharpEmu.Libs.VideoOut.RenderPhaseProfile.Phase.StorageDeferredLabels); OrderAfterDeferredCopies(address, size); phaseScope.SwitchPhase(SharpEmu.Libs.VideoOut.RenderPhaseProfile.Phase.StorageSharedLookup); @@ -34,8 +40,9 @@ internal MetalGuestRange ResolveStorageBuffer(ulong address, ulong size, bool wr phaseScope.SwitchPhase(SharpEmu.Libs.VideoOut.RenderPhaseProfile.Phase.StorageStoreOrder); OrderAfterStagedStores(address, size); phaseScope.SwitchPhase(SharpEmu.Libs.VideoOut.RenderPhaseProfile.Phase.StorageBufferResolve); - if (_guestMemory.TryResolveInPlace(address, size, out var window)) + if (_guestMemory.TryResolveInPlace(address, size, out var window, out var alias)) { + inPlaceAlias = alias; return window; } diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.cs index 83c90c8f5..2587aebd1 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.cs @@ -2546,21 +2546,39 @@ private void TraceRingBinding(ulong address, ulong size, bool isWritten, MetalGu public BufferBinding ObtainBuffer(ulong address, ulong size, bool isWritten) { + // A read the binding before it answered, while that answer stands (MetalRenderHost.ReadBindingMemo.cs). + if (!isWritten && TryReadBindingMemo(address, size, computeStage: false, out var memo)) + { + if (ReadBindingMemoVerify) + { + VerifyReadBinding(address, size, computeStage: false, MetalWritebackCause.BufferBinding, memo); + } + + return new BufferBinding((ulong)memo.Buffer, memo.Offset); + } + + var memoStamp = !isWritten && ReadBindingMemoEnabled ? ReadBindingStamp() : default; // A buffer binding sees guest memory, so any image that owns these bytes // publishes them first; a written binding also invalidates those images. - FlushGpuWrites(address, size, MetalWritebackCause.BufferBinding, isWritten); + var flushFoundImage = _imageCache.FlushGpuWrites(address, size, MetalWritebackCause.BufferBinding, isWritten); // A read takes the storage path: its window, a guest view, or a staged copy that // holds the GPU's writes still in flight in this command buffer - whole, however // large, up to the largest window. + var inPlaceAlias = 0UL; var range = isWritten ? _guestMemory.Resolve(address, size, whole: true) - : ResolveStorageBuffer(address, size, written: false); + : ResolveStorageBuffer(address, size, written: false, computeStage: false, out inPlaceAlias); if (!range.IsValid) { return NullBuffer; } + if (!isWritten && ReadBindingMemoEnabled) + { + StoreReadBinding(address, size, computeStage: false, memoStamp, flushFoundImage, inPlaceAlias, range); + } + TraceRingBinding(address, size, isWritten, range); _slotTrap?.NoteBinding( isWritten ? "binding(write)" : "binding(read)", @@ -2736,6 +2754,9 @@ public void ReportCounters() // Sampled bindings the texture memo answered, those whose stamp failed between the preparation // and the bind, lookups made in full, results memoised, and entries held. $"texture_memo=({TakeTextureMemoCounters()}) {FormatGraphicsBindingCounters()} " + + // Read-only bindings answered from the one before (hits), looked up and not (misses), kept, and checked + // against the full path under =verify; then how often a draw's binding inputs repeat (bind_shape). + $"{TakeReadBindingCounters()} " + // Modules and pipeline states resident against made, and what the bound released. $"{DescribeShaderCache()} " + $"images={_imageCache.ImageCount} image_mb={_imageCache.TotalUsedMemory / (1024 * 1024)} " + diff --git a/tests/SharpEmu.Gpu.Metal.Tests/MetalClearFoldingTests.ReadBindingMemo.cs b/tests/SharpEmu.Gpu.Metal.Tests/MetalClearFoldingTests.ReadBindingMemo.cs new file mode 100644 index 000000000..cc67a1bed --- /dev/null +++ b/tests/SharpEmu.Gpu.Metal.Tests/MetalClearFoldingTests.ReadBindingMemo.cs @@ -0,0 +1,157 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using SharpEmu.Gpu.Metal.V2; +using SharpEmu.Libs.Gpu; +using SharpEmu.Libs.Gpu.Images; +using SharpEmu.Libs.Gpu.Rendering; +using Xunit; + +namespace SharpEmu.Gpu.Metal.Tests; + +/// +/// A read-only binding of a range bound before is answered from the earlier binding (MetalReadBindingMemo) while +/// everything the skipped chain read still stands; each change below must send the binding down the full chain +/// again, and the binding it then gets is the full chain's. +/// +public sealed unsafe partial class MetalClearFoldingTests +{ + private const ulong MemoBuffer = GuestBase + 0x100000; + private const ulong MemoBufferBytes = 0x100; + + private static BufferBinding BindRead(MetalRenderHost host, ulong address = MemoBuffer, ulong size = MemoBufferBytes) => + host.ObtainBuffer(address, size, isWritten: false); + + // Binds the range twice: the first binding is kept, the second is answered from it. + private static BufferBinding BindTwiceAndHit(MetalRenderHost host, ulong address = MemoBuffer, ulong size = MemoBufferBytes) + { + var first = BindRead(host, address, size); + var hits = host.ReadBindingMemoCounts.Hits; + var second = BindRead(host, address, size); + Assert.Equal(hits + 1, host.ReadBindingMemoCounts.Hits); + Assert.Equal(first, second); + return second; + } + + private static void AssertMisses(MetalRenderHost host, Func bind, BufferBinding expected) + { + var (hits, misses, _, _) = host.ReadBindingMemoCounts; + var binding = bind(); + Assert.Equal(hits, host.ReadBindingMemoCounts.Hits); + Assert.Equal(misses + 1, host.ReadBindingMemoCounts.Misses); + Assert.Equal(expected, binding); + } + + private static Rig MemoRig() + { + var rig = new Rig(Device.Value); + rig.Host.ReadBindingMemoEnabled = true; + rig.Host.ReadBindingMemoVerify = true; + return rig; + } + + [Fact] + public void ARepeatedReadOnlyBindingIsAnsweredFromTheOneBeforeAndAWrittenOneIsNot() + { + if (!RequireDevice()) return; + using var rig = MemoRig(); + var host = rig.Host; + var read = BindTwiceAndHit(host); + Assert.Equal(1L, host.ReadBindingMemoCounts.Verified); + + var hits = host.ReadBindingMemoCounts.Hits; + var written = host.ObtainBuffer(MemoBuffer, MemoBufferBytes, isWritten: true); + Assert.Equal(read, written); + Assert.Equal(hits, host.ReadBindingMemoCounts.Hits); + + host.ReadBindingMemoEnabled = false; + Assert.Equal(read, BindRead(host)); + Assert.Equal(hits, host.ReadBindingMemoCounts.Hits); + } + + [Fact] + public void AReadOnlyBindingMissesOnceItsRangeIsRemapped() + { + if (!RequireDevice()) return; + using var rig = MemoRig(); + var host = rig.Host; + var before = BindTwiceAndHit(host); + + rig.Remap = (MemoBuffer, MemoBuffer + 0x1000, 0x1000); + AssertMisses(host, () => BindRead(host), before with { Offset = before.Offset + 0x1000 }); + } + + [Fact] + public void AReadOnlyBindingMissesWhileAStagedCopyIsBound() + { + if (!RequireDevice()) return; + using var rig = MemoRig(); + var host = rig.Host; + var before = BindTwiceAndHit(host); + + // A written range across a view edge has no window: it is staged, and the copy is listed. + const ulong edge = GuestBase + 0x200000; + rig.ViewBoundary = edge; + Assert.True(host.ResolveStorageBuffer(edge - 0x80, 0x100, written: true).IsValid); + AssertMisses(host, () => BindRead(host), before); + } + + [Fact] + public void AReadOnlyBindingMissesOnceAnImageOverItGoesGpuModified() + { + if (!RequireDevice()) return; + using var rig = MemoRig(); + var host = rig.Host; + var request = Rig.Request(TargetAddress, ImageRole.Texture); + var image = host.ImageCache.FindImage(ref request); + var before = BindTwiceAndHit(host, TargetAddress + 0x40, 0x40); + + host.ImageCache.MarkGpuWritten(image); + Assert.True(host.ImageCache.HasGpuModifiedImageBytes(TargetAddress + 0x40, 0x40)); + AssertMisses(host, () => BindRead(host, TargetAddress + 0x40, 0x40), before); + // While the image owns the bytes, the flush finds it each time: nothing is kept for the range. + if (host.ImageCache.HasGpuModifiedImageBytes(TargetAddress + 0x40, 0x40)) + { + AssertMisses(host, () => BindRead(host, TargetAddress + 0x40, 0x40), before); + } + } + + [Fact] + public void AReadOnlyBindingMissesWhileADeferredLabelCopyIsHeld() + { + if (!RequireDevice()) return; + using var rig = MemoRig(); + var host = rig.Host; + using (host.BeginPreparation()) + { + var target = rig.Target(TargetAddress); + var attachment = ((IRenderHost)host).AcquireColorAttachment(in target); + host.BeginRendering(Rig.PassOver(attachment.View)); + var before = BindTwiceAndHit(host); + + host.RecordCommandProcessorWrite(MemoBuffer + 0x10, BitConverter.GetBytes(0xC0FFEE11u), "WRITE_DATA"); + Assert.True(host.DeferredLabelCopyCount > 0, "the write was not held as a label copy"); + AssertMisses(host, () => BindRead(host), before); + host.EndRendering(); + } + + host.FlushAndWaitForGpu(); + } + + [Fact] + public void AReadOnlyBindingMissesInANewCommandBuffer() + { + if (!RequireDevice()) return; + using var rig = MemoRig(); + var host = rig.Host; + Assert.NotEqual(0, host.EnsureComputeEncoder()); + var before = BindTwiceAndHit(host); + var serial = host.SubmissionSerial; + + host.FlushAndWaitForGpu(); + Assert.NotEqual(0, host.EnsureComputeEncoder()); + Assert.NotEqual(serial, host.SubmissionSerial); + AssertMisses(host, () => BindRead(host), before); + host.FlushAndWaitForGpu(); + } +} diff --git a/tests/SharpEmu.Gpu.Metal.Tests/MetalClearFoldingTests.cs b/tests/SharpEmu.Gpu.Metal.Tests/MetalClearFoldingTests.cs index 690716178..a34209566 100644 --- a/tests/SharpEmu.Gpu.Metal.Tests/MetalClearFoldingTests.cs +++ b/tests/SharpEmu.Gpu.Metal.Tests/MetalClearFoldingTests.cs @@ -198,10 +198,18 @@ private sealed class Backing : IGuestBackedSpace, ICpuMemory, IDisposable public bool TryEnterBackingAliasAccess() => AliasAccess; + // Off unless a test sets it: guest [Start, End) moved to backing bytes Delta further on, as a remap would. + public (ulong Start, ulong End, ulong Delta) Remap { get; set; } + public bool TryResolveBackingAlias(ulong address, ulong size, out ulong alias) { var crossesView = ViewBoundary != 0 && address < ViewBoundary && address + size > ViewBoundary; alias = Contains(address, size) && !crossesView ? (ulong)_block + (address - GuestBase) : 0; + if (alias != 0 && address >= Remap.Start && address + size <= Remap.End) + { + alias += Remap.Delta; + } + return alias != 0; } @@ -246,6 +254,8 @@ public Rig(nint device) public ulong ViewBoundary { set => _backing.ViewBoundary = value; } + public (ulong Start, ulong End, ulong Delta) Remap { set => _backing.Remap = value; } + public static ImageRequest Request(ulong address, ImageRole role) { var description = ImageDescription.Create(); diff --git a/tests/SharpEmu.Gpu.Metal.Tests/Scenes/BindingReuseSceneTests.cs b/tests/SharpEmu.Gpu.Metal.Tests/Scenes/BindingReuseSceneTests.cs index ee187fcea..04dfb325c 100644 --- a/tests/SharpEmu.Gpu.Metal.Tests/Scenes/BindingReuseSceneTests.cs +++ b/tests/SharpEmu.Gpu.Metal.Tests/Scenes/BindingReuseSceneTests.cs @@ -169,4 +169,85 @@ float[] Pixel(int x) output.WriteLine($"graphics binding reuse={reuse} attempted={rig.Host.GraphicsBindingAttempts} skipped={rig.Host.GraphicsBindingSkipped}"); } + // Draws of one mesh read its vertex buffer through the same read-only storage binding: within a command buffer + // the binding after the first is answered from it (MetalReadBindingMemo), a new command buffer looks it up in + // full first, and every draw renders the texture it binds either way. + [Theory] + [InlineData(true)] + [InlineData(false)] + public void DrawsOfOneMeshReuseTheirReadOnlyVertexBindingAndRenderAsWithout(bool memo) + { + using var rig = CreateRig(); + if (rig is null) return; + var host = rig.Host; + host.ReadBindingMemoEnabled = memo; + host.ReadBindingMemoVerify = memo; + const uint red = 0xFF0000FF; + const uint green = 0xFF00FF00; + const uint width = 16; + var textures = new Dictionary { [red] = SolidTexture(rig, red), [green] = SolidTexture(rig, green) }; + SceneVertex[] quad = + [ + SceneVertex.At(-1, -1, 0.5f, 0, 1, 0, 1), SceneVertex.At(1, -1, 0.5f, 1, 1, 0, 1), + SceneVertex.At(-1, 1, 0.5f, 0, 0, 0, 1), SceneVertex.At(-1, 1, 0.5f, 0, 0, 0, 1), + SceneVertex.At(1, -1, 0.5f, 1, 1, 0, 1), SceneVertex.At(1, 1, 0.5f, 1, 0, 0, 1), + ]; + var mesh = rig.UploadMesh(quad); + var vertex = rig.Program(ScenePrograms.FetchVertex); + var pixel = rig.Program(Sample); + // One target, a stripe per draw: the same images every draw, so only the vertex binding's lookup varies. + var target = rig.ColorTarget(width, width, 16, 0xFF); + var state = new SceneState(width, width).ColorTarget(0, target, width, width, format: 14, numberType: 7); + void Stripe(ScenePm4 pm4, int stripe, uint colour) + { + state.ScreenScissor(stripe * 4, 0, stripe * 4 + 4, (int)width); + uint[] userData = [.. Descriptors.Texture(textures[colour], Rgba8, Size, Size), .. Descriptors.Sampler(), 0, 0, 0, 0]; + state.VertexShader(vertex, mesh); + state.PixelShader(pixel, userData); + state.Emit(pm4); + pm4.NumInstances(1); + pm4.DrawAuto((uint)quad.Length); + } + + float[] Pixel(int x) + { + var pixels = MemoryMarshal.Cast(rig.ReadImage(target, width, width, 16)); + return pixels.Slice((int)((8 * width + (uint)x) * 4), 4).ToArray(); + } + + uint[] first = [red, green, red, red]; + var stream = new ScenePm4(); + for (var stripe = 0; stripe < first.Length; stripe++) + { + Stripe(stream, stripe, first[stripe]); + } + + var (hits, _, _, _) = host.ReadBindingMemoCounts; + rig.Submit(stream); + var afterFirst = host.ReadBindingMemoCounts; + for (var stripe = 0; stripe < first.Length; stripe++) + { + AssertColour($"stripe {stripe}", Pixel(stripe * 4 + 2), first[stripe]); + } + + var again = new ScenePm4(); + Stripe(again, 1, red); + rig.Submit(again); + AssertColour("next command buffer", Pixel(6), red); + var afterSecond = host.ReadBindingMemoCounts; + output.WriteLine($"memo={memo}: first {afterFirst}, second {afterSecond}"); + if (memo) + { + Assert.True(afterFirst.Hits > hits, "no draw's vertex binding was answered from the one before"); + Assert.Equal(afterFirst.Hits - hits, afterFirst.Verified); + Assert.True(afterSecond.Misses > afterFirst.Misses, "the new command buffer's first binding did not miss"); + } + else + { + Assert.Equal(hits, afterSecond.Hits); + } + + Assert.Empty(rig.Fatals); + } + } diff --git a/tests/SharpEmu.Gpu.Metal.Tests/Scenes/DsDrawCostBenchTests.cs b/tests/SharpEmu.Gpu.Metal.Tests/Scenes/DsDrawCostBenchTests.cs index 227840778..9b982f7b3 100644 --- a/tests/SharpEmu.Gpu.Metal.Tests/Scenes/DsDrawCostBenchTests.cs +++ b/tests/SharpEmu.Gpu.Metal.Tests/Scenes/DsDrawCostBenchTests.cs @@ -205,6 +205,9 @@ private static uint[] TablePixel(int targets) private static readonly MethodInfo PrefetchCounters = typeof(MetalRenderHost).GetMethod("FormatPrefetchCounters", BindingFlags.Instance | BindingFlags.NonPublic)!; + private static readonly MethodInfo ReadBindingCounters = + typeof(MetalRenderHost).GetMethod("TakeReadBindingCounters", BindingFlags.Instance | BindingFlags.NonPublic)!; + [DllImport("libSystem.dylib")] private static extern ulong clock_gettime_nsec_np(int clockId); @@ -455,6 +458,8 @@ uint[] DispatchStream() } var prefetch = (string)PrefetchCounters.Invoke(rig.Host, null)!; + // Read-only bindings answered from the one before (MetalReadBindingMemo) over every round, warm-up included. + var bindings = (string)ReadBindingCounters.Invoke(rig.Host, null)!; var checksum = 0xCBF29CE484222325UL; void Fold(ulong address, int count) { @@ -495,6 +500,7 @@ void Fold(ulong address, int count) gen0CollectionsPerThousandItems = collections * 1000.0 / (rounds * items), checksum = $"{checksum:X16}", counters = prefetch, + bindings, phaseMicroseconds = phaseTotals.Where(pair => pair.Value / rounds >= 0.005) .OrderByDescending(pair => pair.Value).ToDictionary(pair => pair.Key, pair => Math.Round(pair.Value / rounds, 3)), }); From d2c7e4c34e8de4ad6ac7ae209b7d78b53a001c6d Mon Sep 17 00:00:00 2001 From: kuba Date: Sun, 15 Nov 2026 01:59:59 +0000 Subject: [PATCH 007/178] [Core] Decide the leaf path's per-call diagnostics once per session DispatchImportCore tested the address probe, the register-packet profile, SHARPEMU_PERF_HLE, the guest-RIP sampler, the all-imports warning and the import filter on every call. They are fixed when the session is configured, so one precomputed _leafDiagnosticsOff skips them together. NoteHleEntry, the session counters and the shutdown safe point still run on every call. Co-Authored-By: Claude --- .../Native/DirectExecutionBackend.Imports.cs | 38 ++++++++++++------- .../Cpu/Native/DirectExecutionBackend.cs | 14 +++++++ 2 files changed, 38 insertions(+), 14 deletions(-) diff --git a/src/SharpEmu.Core/Cpu/Native/DirectExecutionBackend.Imports.cs b/src/SharpEmu.Core/Cpu/Native/DirectExecutionBackend.Imports.cs index c88573403..e1230e880 100644 --- a/src/SharpEmu.Core/Cpu/Native/DirectExecutionBackend.Imports.cs +++ b/src/SharpEmu.Core/Cpu/Native/DirectExecutionBackend.Imports.cs @@ -534,10 +534,26 @@ private unsafe ulong DispatchImportCore(int importIndex, nint argPackPtr) // By reference: the entry is 48 bytes of per-import classification that // nothing here mutates, and copying it was pure cost on every guest call. ref readonly ImportStubEntry importStubEntry = ref _importEntries[importIndex]; - TraceImportAddressProbe(cpuContext, in importStubEntry, argPackPtr); - using var registerPacketImport = SharpEmu.Libs.Diagnostics.AgcRegisterPacketProfile.MeasureImport(importStubEntry.Nid); + // The session counters can be armed while the guest runs, so they are read on every call. Volatile.Read(ref _activeImportSessionCounters)?.Record(importIndex, importStubEntry.Nid); - if (_perfHleHistogram) + int num2 = Volatile.Read(in _rawSentinelRecoveries); + if (num2 != _lastReportedRawSentinelRecoveries) + { + Console.Error.WriteLine($"[LOADER][TRACE] Raw sentinel recoveries: {num2} (last import index={importIndex})"); + _lastReportedRawSentinelRecoveries = num2; + } + + // With no per-call diagnostic on for the session (decided once, at configuration), one test + // skips all of them and the call goes straight to the leaf dispatches below. + var diagnostics = !_leafDiagnosticsOff; + if (diagnostics) + { + TraceImportAddressProbe(cpuContext, in importStubEntry, argPackPtr); + } + using var registerPacketImport = diagnostics + ? SharpEmu.Libs.Diagnostics.AgcRegisterPacketProfile.MeasureImport(importStubEntry.Nid) + : default; + if (diagnostics && _perfHleHistogram) { try { RecordPerfHleCall(importStubEntry.Export?.Name ?? importStubEntry.Nid); } catch (Exception diagnosticFailure) when (diagnosticFailure is System.IO.IOException or ObjectDisposedException) @@ -545,16 +561,10 @@ private unsafe ulong DispatchImportCore(int importIndex, nint argPackPtr) // Profiling output is optional; a closed sink must not skip the export. } } - if (_profileGuestRip) + if (diagnostics && _profileGuestRip) { EnsureGuestRipSampler(); } - int num2 = Volatile.Read(in _rawSentinelRecoveries); - if (num2 != _lastReportedRawSentinelRecoveries) - { - Console.Error.WriteLine($"[LOADER][TRACE] Raw sentinel recoveries: {num2} (last import index={importIndex})"); - _lastReportedRawSentinelRecoveries = num2; - } // The leaf paths answer the guest and return from this gateway before the // [LOADER][TRACE] Import# block further down, so SHARPEMU_LOG_ALL_IMPORTS // shows nothing at all for an import dispatched as a leaf. Reading that @@ -562,7 +572,7 @@ private unsafe ulong DispatchImportCore(int importIndex, nint argPackPtr) // to make: Quake reads scePadReadState roughly two hundred thousand times a // second and an all-imports log of a Quake run contains not one line of it. // Say so once, and name the counter that does see them. - if (_logAllImports && + if (diagnostics && _logAllImports && (importStubEntry.IsLeaf || importStubEntry.IsTrivialLeaf) && Interlocked.Exchange(ref _leafTraceGapAnnounced, 1) == 0) { @@ -577,8 +587,8 @@ private unsafe ulong DispatchImportCore(int importIndex, nint argPackPtr) // that need it - is this status import ever called, and what does it answer - // are about imports the all-imports log cannot see. The arguments are read // before the dispatch: the leaf paths write results through the same pack. - var traceLeaf = (importStubEntry.IsLeaf || importStubEntry.IsTrivialLeaf) && - !string.IsNullOrWhiteSpace(_importFilter) && + var traceLeaf = diagnostics && _importFilterSet && + (importStubEntry.IsLeaf || importStubEntry.IsTrivialLeaf) && MatchesImportFilter(in importStubEntry); ulong leafArg0 = 0, leafArg1 = 0, leafArg2 = 0, leafArg3 = 0, leafReturnRip = 0; if (traceLeaf) @@ -2102,7 +2112,7 @@ private unsafe bool TryDispatchBuilderLeaf( if (!_builderLeafEnabled || _logAllImports || _profileGuestRip || - !string.IsNullOrWhiteSpace(_importFilter) || + _importFilterSet || Volatile.Read(ref _pendingGuestExceptionCount) != 0 || Volatile.Read(ref _forcedGuestExit) || importStubEntry.Export is not { } export || diff --git a/src/SharpEmu.Core/Cpu/Native/DirectExecutionBackend.cs b/src/SharpEmu.Core/Cpu/Native/DirectExecutionBackend.cs index cc6474b14..55051cdfe 100644 --- a/src/SharpEmu.Core/Cpu/Native/DirectExecutionBackend.cs +++ b/src/SharpEmu.Core/Cpu/Native/DirectExecutionBackend.cs @@ -556,6 +556,15 @@ private static bool TryTakeReusableNestedCallbackStack(IVirtualMemory memory, ou private string? _importFilter; + // !string.IsNullOrWhiteSpace(_importFilter), set with it. + private bool _importFilterSet; + + // No per-call import diagnostic is on (all-imports and filtered traces, SHARPEMU_PERF_HLE, the + // guest RIP sampler, the return-address probe, the register-packet profile): DispatchImportCore + // skips straight to the leaf dispatch. False until the session configures it, which keeps + // every diagnostic on the path. + private bool _leafDiagnosticsOff; + private bool _disableImportLoopGuard; private int _importLoopGuardSeconds; @@ -1540,6 +1549,11 @@ private bool TryExecuteCore(CpuContext context, ulong entryPoint, Generation gen _probeImportRootAddress = ParseOptionalHexAddress( Environment.GetEnvironmentVariable("SHARPEMU_PROBE_IMPORT_ROOT_ADDRESS")); _importFilter = Environment.GetEnvironmentVariable("SHARPEMU_LOG_IMPORT_FILTER"); + _importFilterSet = !string.IsNullOrWhiteSpace(_importFilter); + // Every per-call diagnostic DispatchImportCore runs before a leaf dispatch, decided once: + // all of them are fixed for the session from here on. + _leafDiagnosticsOff = !_logAllImports && !_importFilterSet && !_perfHleHistogram && !_profileGuestRip && + _probeImportReturnAddress == 0 && !SharpEmu.Libs.Diagnostics.AgcRegisterPacketProfile.Enabled; _disableImportLoopGuard = !string.Equals( Environment.GetEnvironmentVariable("SHARPEMU_DISABLE_IMPORT_LOOP_GUARD"), "0", From 6f59784e7e714cdfc481f56d167e72fc78ed1849 Mon Sep 17 00:00:00 2001 From: kuba Date: Sun, 15 Nov 2026 02:03:36 +0000 Subject: [PATCH 008/178] [Metal] Test a range longer than a line as itself in an owned page A range of more than 256 bytes passed the line guard by unsigned wrap-around, so only the line it starts in was tested and a pending write further on in the range was missed. --- .../V2/MetalRenderHost.ConcurrentResolve.cs | 3 +- ...alClearFoldingTests.CrossDrawCleanPages.cs | 35 +++++++++++++++++++ 2 files changed, 37 insertions(+), 1 deletion(-) diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.ConcurrentResolve.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.ConcurrentResolve.cs index c7fa777ca..727653fcc 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.ConcurrentResolve.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.ConcurrentResolve.cs @@ -721,8 +721,9 @@ private bool IsOwnedRecorded(ConcurrentQuery query, ulong address, ulong size, C // In an owned page, the read's line first. Every test is an overlap test, so a clean line is clean for // every range inside it; its answer is recorded like a clean page's and checked again at the take. + // A range longer than a line, or one that leaves its line, is in no single line: tested as itself. var line = address & ~((ulong)ConcurrentWordLineBytes - 1); - if (ownedLines && address - line <= ConcurrentWordLineBytes - size) + if (ownedLines && size <= ConcurrentWordLineBytes && address - line <= ConcurrentWordLineBytes - size) { var lineOwned = assumptions.LineOwned(query, line); if (lineOwned is null) diff --git a/tests/SharpEmu.Gpu.Metal.Tests/MetalClearFoldingTests.CrossDrawCleanPages.cs b/tests/SharpEmu.Gpu.Metal.Tests/MetalClearFoldingTests.CrossDrawCleanPages.cs index a0a587368..e01eb08f2 100644 --- a/tests/SharpEmu.Gpu.Metal.Tests/MetalClearFoldingTests.CrossDrawCleanPages.cs +++ b/tests/SharpEmu.Gpu.Metal.Tests/MetalClearFoldingTests.CrossDrawCleanPages.cs @@ -136,6 +136,41 @@ public void TheCleanLinesOfAnOwnedPageAreTestedOnceAndTheirWordsReadFromThem(boo concurrent.ReleaseAssumptions(assumptions); } + // A range that starts in a clean line and runs on into the written one is in no single line: the clean + // line it starts in says nothing for it. + [Theory] + [InlineData(0x300, true)] + [InlineData(0x300, false)] + [InlineData(0x108, true)] + [InlineData(0x108, false)] + public void ARangeLeavingItsCleanLineForAWrittenOneIsRefused(int length, bool ownedLines) + { + if (!RequireDevice()) return; + using var rig = new Rig(Device.Value); + var host = rig.Host; + host.ConcurrentOwnedLines = ownedLines; + WriteOwnedPage(rig); + var concurrent = (IConcurrentResolveHost)host; + + concurrent.BeginConcurrentResolve(); + object assumptions; + try + { + // The page is found owned and the line before the write clean, first. + Assert.True(host.TryReadGuestWord(OwnedPageWrite - 0x100, out var word)); + Assert.Equal(OwnedPageWord(OwnedPageWrite - 0x100), word); + Assert.False(host.TryReadResidentGuestBytes(OwnedPageWrite - 0x100, new byte[length], clean: false)); + // Inside the clean line the same reader answers. + Assert.True(host.TryReadResidentGuestBytes(OwnedPageWrite - 0x100, new byte[0x100], clean: false)); + } + finally + { + assumptions = concurrent.EndConcurrentResolve(); + } + + concurrent.ReleaseAssumptions(assumptions); + } + [Fact] public void TheWordsOfAnOwnedLineAreTestedOneByOneAndAnOwnedWordAbandons() { From b664dd3b9377c65a97d030d5a4e34029cd66801b Mon Sep 17 00:00:00 2001 From: kuba Date: Sun, 15 Nov 2026 02:05:23 +0000 Subject: [PATCH 009/178] [Core] Measure the import gateway crossing; PERF_HLE mutex and SetShRegistersDirect shapes GatewayCrossingMeasurementTests (opt-in, SHARPEMU_GATEWAY_BENCH_OUTPUT names the report) calls the real import trampoline from native code for a trivial-leaf and a full-path import, against a native stub and DispatchImportCore alone. SHARPEMU_PERF_HLE=1 adds two [PERF][HLE] lines: how mutex lock, trylock and unlock arguments resolve (explicit slot, implicit slot, aliased, created from the static initialiser or a zero slot, missing) and how many were uncontended; and the shape of sceAgcCbSetShRegistersDirect calls that reach the export (over the stub's 32 registers, unsorted, duplicates, runs, source overlap, no room, failures). Co-Authored-By: Claude --- .../DirectExecutionBackend.Diagnostics.cs | 5 + .../Agc/AgcExports.RegisterPackets.cs | 40 ++++ .../Diagnostics/HleCallShapeProfile.cs | 105 ++++++++++ .../Kernel/KernelPthreadCompatExports.cs | 38 +++- .../Cpu/GatewayCrossingMeasurementTests.cs | 185 ++++++++++++++++++ 5 files changed, 370 insertions(+), 3 deletions(-) create mode 100644 src/SharpEmu.Libs/Diagnostics/HleCallShapeProfile.cs create mode 100644 tests/SharpEmu.Libs.Tests/Cpu/GatewayCrossingMeasurementTests.cs diff --git a/src/SharpEmu.Core/Cpu/Native/DirectExecutionBackend.Diagnostics.cs b/src/SharpEmu.Core/Cpu/Native/DirectExecutionBackend.Diagnostics.cs index ba0238461..c8a73ac34 100644 --- a/src/SharpEmu.Core/Cpu/Native/DirectExecutionBackend.Diagnostics.cs +++ b/src/SharpEmu.Core/Cpu/Native/DirectExecutionBackend.Diagnostics.cs @@ -112,6 +112,11 @@ private static void RecordPerfHleDispatchTime(HleDispatchTiming.Elapsed elapsed) $"[PERF][HLE] fast_path: self_hits={fastPath.SelfHits} " + $"getspecific_hits={fastPath.GetspecificHits} blocks={fastPath.Blocks}"); } + + foreach (var line in SharpEmu.Libs.Diagnostics.HleCallShapeProfile.FormatLines()) + { + System.Console.Error.WriteLine(line); + } } } diff --git a/src/SharpEmu.Libs/Agc/AgcExports.RegisterPackets.cs b/src/SharpEmu.Libs/Agc/AgcExports.RegisterPackets.cs index 0959b146a..8dda38746 100644 --- a/src/SharpEmu.Libs/Agc/AgcExports.RegisterPackets.cs +++ b/src/SharpEmu.Libs/Agc/AgcExports.RegisterPackets.cs @@ -25,11 +25,13 @@ public static int CbSetShRegistersDirect(CpuContext ctx) var registerCount = (uint)ctx[CpuRegister.Rdx]; if (registerCount == 0) { + if (Diagnostics.HleCallShapeProfile.Enabled) Diagnostics.HleCallShapeProfile.RecordShRegisters(0, false, false, 0, false, Diagnostics.HleCallShapeProfile.ShRegistersOutcome.Invalid); return ReturnPointer(ctx, 0); } if (commandBufferAddress == 0 || registersAddress == 0 || registerCount > 4096) { + if (Diagnostics.HleCallShapeProfile.Enabled) Diagnostics.HleCallShapeProfile.RecordShRegisters(registerCount, false, false, 0, false, Diagnostics.HleCallShapeProfile.ShRegistersOutcome.Invalid); return ReturnPointer(ctx, 0); } @@ -40,6 +42,13 @@ public static int CbSetShRegistersDirect(CpuContext ctx) var registerPool = System.Buffers.ArrayPool.Shared; var registers = registerPool.Rent((int)registerCount); uint[]? packet = null; + // SHARPEMU_PERF_HLE only: the call's shape, recorded once on the way out. + var profile = Diagnostics.HleCallShapeProfile.Enabled; + var unsorted = false; + var duplicates = false; + var sourceOverlap = false; + var runs = 0; + var outcome = Diagnostics.HleCallShapeProfile.ShRegistersOutcome.ReadFailed; try { if (!ctx.Memory.TryRead( @@ -49,7 +58,23 @@ public static int CbSetShRegistersDirect(CpuContext ctx) return ReturnPointer(ctx, 0); } + if (profile) + { + for (var index = 1; index < (int)registerCount; index++) + { + unsorted |= registers[index].Offset < registers[index - 1].Offset; + } + } + registers.AsSpan(0, (int)registerCount).Sort(static (left, right) => left.Offset.CompareTo(right.Offset)); + if (profile) + { + for (var index = 1; index < (int)registerCount; index++) + { + duplicates |= registers[index].Offset == registers[index - 1].Offset; + } + } + ulong firstCommandAddress = 0; var startIndex = 0; var count = (int)registerCount; @@ -64,11 +89,19 @@ public static int CbSetShRegistersDirect(CpuContext ctx) var valueCount = (uint)(endIndex - startIndex); var packetDwords = valueCount + 2; + runs++; if (!TryAllocateCommandDwords(ctx, commandBufferAddress, packetDwords, out var commandAddress)) { + outcome = Diagnostics.HleCallShapeProfile.ShRegistersOutcome.NoRoom; return ReturnPointer(ctx, 0); } + if (profile) + { + sourceOverlap |= commandAddress < registersAddress + registerCount * 8UL && + registersAddress < commandAddress + packetDwords * 4UL; + } + packet ??= System.Buffers.ArrayPool.Shared.Rent(count + 2); packet[0] = Pm4(packetDwords, ItSetShReg, 0); packet[1] = registers[startIndex].Offset & 0xFFFFu; @@ -79,6 +112,7 @@ public static int CbSetShRegistersDirect(CpuContext ctx) if (!TryWriteCommandDwords(ctx, commandAddress, packet.AsSpan(0, (int)packetDwords))) { + outcome = Diagnostics.HleCallShapeProfile.ShRegistersOutcome.WriteFailed; return ReturnPointer(ctx, 0); } @@ -86,10 +120,16 @@ public static int CbSetShRegistersDirect(CpuContext ctx) startIndex = endIndex; } + outcome = Diagnostics.HleCallShapeProfile.ShRegistersOutcome.Written; return ReturnPointer(ctx, firstCommandAddress); } finally { + if (profile) + { + Diagnostics.HleCallShapeProfile.RecordShRegisters(registerCount, unsorted, duplicates, runs, sourceOverlap, outcome); + } + registerPool.Return(registers); if (packet is not null) { diff --git a/src/SharpEmu.Libs/Diagnostics/HleCallShapeProfile.cs b/src/SharpEmu.Libs/Diagnostics/HleCallShapeProfile.cs new file mode 100644 index 000000000..351e212c2 --- /dev/null +++ b/src/SharpEmu.Libs/Diagnostics/HleCallShapeProfile.cs @@ -0,0 +1,105 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +namespace SharpEmu.Libs.Diagnostics; + +/// +/// SHARPEMU_PERF_HLE=1 only: what the calls that reach two hot managed exports look like, to size +/// the native stubs that could answer them. The guest mutex lock, trylock and unlock: how the +/// mutex argument resolved (the slot of a mutex scePthreadMutexInit made, the slot of one made +/// implicitly, an alias of another slot or handle, created on this call from the static +/// initialiser or a zero slot, or not resolved) and how many took the uncontended path. +/// sceAgcCbSetShRegistersDirect: everything its native stub declines (more registers than the +/// stub takes, unsorted, duplicate offsets, more than one run, a destination overlapping the +/// source, no room in the buffer). Printed with the [PERF][HLE] lines. +/// +internal static class HleCallShapeProfile +{ + internal static readonly bool Enabled = + string.Equals(Environment.GetEnvironmentVariable("SHARPEMU_PERF_HLE"), "1", StringComparison.Ordinal); + + internal enum MutexOp { Lock, Trylock, Unlock, Count } + + internal enum MutexResolve { ExplicitSlot, ImplicitSlot, Aliased, CreatedStatic, CreatedZero, Missing, Count } + + internal enum ShRegistersOutcome { Written, Invalid, ReadFailed, NoRoom, WriteFailed, Count } + + private static readonly long[] _mutexResolves = new long[(int)MutexOp.Count * (int)MutexResolve.Count]; + private static readonly long[] _mutexUncontended = new long[(int)MutexOp.Count]; + + private static readonly long[] _shOutcomes = new long[(int)ShRegistersOutcome.Count]; + private static long _shCalls; + private static long _shOverStubLimit; + private static long _shUnsorted; + private static long _shDuplicates; + private static long _shSourceOverlap; + private static long _shStubShaped; + // Runs per call: 1, 2, 3-4, 5-8, more. + private static readonly long[] _shRuns = new long[5]; + + internal static void RecordMutexResolve(MutexOp op, MutexResolve resolve) => + Interlocked.Increment(ref _mutexResolves[(int)op * (int)MutexResolve.Count + (int)resolve]); + + internal static void RecordMutexUncontended(MutexOp op) => Interlocked.Increment(ref _mutexUncontended[(int)op]); + + internal static void RecordShRegisters( + uint count, bool unsorted, bool duplicates, int runs, bool sourceOverlap, ShRegistersOutcome outcome) + { + Interlocked.Increment(ref _shCalls); + Interlocked.Increment(ref _shOutcomes[(int)outcome]); + if (outcome is ShRegistersOutcome.Invalid or ShRegistersOutcome.ReadFailed) return; + if (count > Agc.AgcExports.RegistersStubMaxRegisters) Interlocked.Increment(ref _shOverStubLimit); + if (unsorted) Interlocked.Increment(ref _shUnsorted); + if (duplicates) Interlocked.Increment(ref _shDuplicates); + if (sourceOverlap) Interlocked.Increment(ref _shSourceOverlap); + if (runs > 0) Interlocked.Increment(ref _shRuns[runs switch { 1 => 0, 2 => 1, <= 4 => 2, <= 8 => 3, _ => 4 }]); + // The shape the stub answers; such a call reaching the export was declined for something else. + if (count <= Agc.AgcExports.RegistersStubMaxRegisters && !unsorted && !duplicates && runs == 1 && !sourceOverlap) + Interlocked.Increment(ref _shStubShaped); + } + + internal static IEnumerable FormatLines() + { + var mutex = new System.Text.StringBuilder("[PERF][HLE] mutex:"); + for (var op = 0; op < (int)MutexOp.Count; op++) + { + long total = 0; + var parts = new System.Text.StringBuilder(); + for (var resolve = 0; resolve < (int)MutexResolve.Count; resolve++) + { + var value = Interlocked.Read(ref _mutexResolves[op * (int)MutexResolve.Count + resolve]); + total += value; + parts.Append(' ').Append(ToSnake((MutexResolve)resolve)).Append('=').Append(value); + } + + mutex.Append(' ').Append(((MutexOp)op).ToString().ToLowerInvariant()) + .Append("{total=").Append(total) + .Append(" uncontended=").Append(Interlocked.Read(ref _mutexUncontended[op])) + .Append(parts).Append('}'); + } + + yield return mutex.ToString(); + yield return + $"[PERF][HLE] sh_registers_direct (calls reaching the export): calls={Interlocked.Read(ref _shCalls)} " + + $"written={Interlocked.Read(ref _shOutcomes[(int)ShRegistersOutcome.Written])} " + + $"invalid={Interlocked.Read(ref _shOutcomes[(int)ShRegistersOutcome.Invalid])} " + + $"read_failed={Interlocked.Read(ref _shOutcomes[(int)ShRegistersOutcome.ReadFailed])} " + + $"no_room={Interlocked.Read(ref _shOutcomes[(int)ShRegistersOutcome.NoRoom])} " + + $"write_failed={Interlocked.Read(ref _shOutcomes[(int)ShRegistersOutcome.WriteFailed])} " + + $"over_{Agc.AgcExports.RegistersStubMaxRegisters}={Interlocked.Read(ref _shOverStubLimit)} " + + $"unsorted={Interlocked.Read(ref _shUnsorted)} duplicates={Interlocked.Read(ref _shDuplicates)} " + + $"source_overlap={Interlocked.Read(ref _shSourceOverlap)} stub_shaped={Interlocked.Read(ref _shStubShaped)} " + + $"runs{{1={Interlocked.Read(ref _shRuns[0])} 2={Interlocked.Read(ref _shRuns[1])} 3-4={Interlocked.Read(ref _shRuns[2])} " + + $"5-8={Interlocked.Read(ref _shRuns[3])} 9+={Interlocked.Read(ref _shRuns[4])}}}"; + } + + private static string ToSnake(MutexResolve resolve) => resolve switch + { + MutexResolve.ExplicitSlot => "explicit", + MutexResolve.ImplicitSlot => "implicit", + MutexResolve.Aliased => "aliased", + MutexResolve.CreatedStatic => "created_static", + MutexResolve.CreatedZero => "created_zero", + _ => "missing", + }; +} diff --git a/src/SharpEmu.Libs/Kernel/KernelPthreadCompatExports.cs b/src/SharpEmu.Libs/Kernel/KernelPthreadCompatExports.cs index 6d0cb1801..04a1e3924 100644 --- a/src/SharpEmu.Libs/Kernel/KernelPthreadCompatExports.cs +++ b/src/SharpEmu.Libs/Kernel/KernelPthreadCompatExports.cs @@ -91,6 +91,8 @@ public int RecursionCount public int QueuedWaiterCount => Volatile.Read(ref _queuedWaiterCount); public int Type { get; set; } = MutexTypeErrorCheck; public int Protocol { get; set; } + // Made by the first lock or unlock of a zero or statically initialised slot, not by an init call. + public bool Implicit { get; init; } public LinkedList Waiters { get; } = new(); // SHARPEMU_PERF_MUTEX only: the thread that last took the mutex. public string? ProfileOwner; @@ -1133,7 +1135,14 @@ private static int PthreadMutexLockSce(CpuContext ctx, ulong mutexAddress, bool return (int)OrbisGen2Result.ORBIS_GEN2_ERROR_INVALID_ARGUMENT; } - if (!TryResolveMutexState(ctx, mutexAddress, createIfZero: true, out var resolvedAddress, out var state)) + var resolved = TryResolveMutexState(ctx, mutexAddress, createIfZero: true, out var resolvedAddress, out var state, out var resolve); + var profileOp = tryOnly ? SharpEmu.Libs.Diagnostics.HleCallShapeProfile.MutexOp.Trylock : SharpEmu.Libs.Diagnostics.HleCallShapeProfile.MutexOp.Lock; + if (SharpEmu.Libs.Diagnostics.HleCallShapeProfile.Enabled) + { + SharpEmu.Libs.Diagnostics.HleCallShapeProfile.RecordMutexResolve(profileOp, resolved ? resolve : SharpEmu.Libs.Diagnostics.HleCallShapeProfile.MutexResolve.Missing); + } + + if (!resolved) { TracePthreadFastPathBusy(tryOnly ? "trylock_missing" : "lock_missing", mutexAddress, resolvedAddress, null, KernelPthreadState.GetCurrentThreadHandle(), (int)OrbisGen2Result.ORBIS_GEN2_ERROR_NOT_FOUND); TracePthreadMutex(ctx, tryOnly ? "trylock" : "lock", mutexAddress, resolvedAddress, null, KernelPthreadState.GetCurrentThreadHandle(), (int)OrbisGen2Result.ORBIS_GEN2_ERROR_NOT_FOUND); @@ -1143,6 +1152,7 @@ private static int PthreadMutexLockSce(CpuContext ctx, ulong mutexAddress, bool var currentThreadId = KernelPthreadState.GetCurrentThreadHandle(); if (state.TryAcquireUncontended(currentThreadId, allowWaiterBarge: tryOnly || !state.FifoHandoff)) { + if (SharpEmu.Libs.Diagnostics.HleCallShapeProfile.Enabled) SharpEmu.Libs.Diagnostics.HleCallShapeProfile.RecordMutexUncontended(profileOp); if (MutexContentionProfile.Enabled) state.ProfileOwner = MutexContentionProfile.CurrentThreadName(); TracePthreadMutex(ctx, tryOnly ? "trylock" : "lock", mutexAddress, resolvedAddress, state, currentThreadId, (int)OrbisGen2Result.ORBIS_GEN2_OK); return (int)OrbisGen2Result.ORBIS_GEN2_OK; @@ -1287,7 +1297,13 @@ private static int PthreadMutexUnlockSce(CpuContext ctx, ulong mutexAddress, boo return (int)OrbisGen2Result.ORBIS_GEN2_ERROR_INVALID_ARGUMENT; } - if (!TryResolveMutexState(ctx, mutexAddress, createIfZero: true, out var resolvedAddress, out var state)) + var resolved = TryResolveMutexState(ctx, mutexAddress, createIfZero: true, out var resolvedAddress, out var state, out var resolve); + if (SharpEmu.Libs.Diagnostics.HleCallShapeProfile.Enabled) + { + SharpEmu.Libs.Diagnostics.HleCallShapeProfile.RecordMutexResolve(SharpEmu.Libs.Diagnostics.HleCallShapeProfile.MutexOp.Unlock, resolved ? resolve : SharpEmu.Libs.Diagnostics.HleCallShapeProfile.MutexResolve.Missing); + } + + if (!resolved) { TracePthreadMutex(ctx, "unlock", mutexAddress, resolvedAddress, null, KernelPthreadState.GetCurrentThreadHandle(), (int)OrbisGen2Result.ORBIS_GEN2_ERROR_NOT_FOUND); return (int)OrbisGen2Result.ORBIS_GEN2_ERROR_NOT_FOUND; @@ -1310,6 +1326,10 @@ private static int PthreadMutexUnlockSce(CpuContext ctx, ulong mutexAddress, boo { WakeFirstMutexWaiter(state, mutexAddress, currentThreadId); } + else if (SharpEmu.Libs.Diagnostics.HleCallShapeProfile.Enabled) + { + SharpEmu.Libs.Diagnostics.HleCallShapeProfile.RecordMutexUncontended(SharpEmu.Libs.Diagnostics.HleCallShapeProfile.MutexOp.Unlock); + } TracePthreadMutex(ctx, "unlock", mutexAddress, resolvedAddress, state, currentThreadId, (int)OrbisGen2Result.ORBIS_GEN2_OK); return (int)OrbisGen2Result.ORBIS_GEN2_OK; @@ -1742,8 +1762,13 @@ private static ulong ResolveMutexAllocationAddress( return resolvedAddress; } - private static bool TryResolveMutexState(CpuContext ctx, ulong mutexAddress, bool createIfZero, out ulong resolvedAddress, [NotNullWhen(true)] out PthreadMutexState? state) + private static bool TryResolveMutexState(CpuContext ctx, ulong mutexAddress, bool createIfZero, out ulong resolvedAddress, [NotNullWhen(true)] out PthreadMutexState? state) => + TryResolveMutexState(ctx, mutexAddress, createIfZero, out resolvedAddress, out state, out _); + + // `resolve` says which path answered, for the SHARPEMU_PERF_HLE mutex counters. + private static bool TryResolveMutexState(CpuContext ctx, ulong mutexAddress, bool createIfZero, out ulong resolvedAddress, [NotNullWhen(true)] out PthreadMutexState? state, out SharpEmu.Libs.Diagnostics.HleCallShapeProfile.MutexResolve resolve) { + resolve = SharpEmu.Libs.Diagnostics.HleCallShapeProfile.MutexResolve.Missing; resolvedAddress = 0; state = null; if (mutexAddress == 0) @@ -1773,6 +1798,7 @@ private static bool TryResolveMutexState(CpuContext ctx, ulong mutexAddress, boo _mutexStates[mutexAddress] = pointedState; resolvedAddress = pointedHandle; state = pointedState; + resolve = SharpEmu.Libs.Diagnostics.HleCallShapeProfile.MutexResolve.Aliased; return true; } @@ -1793,12 +1819,14 @@ private static bool TryResolveMutexState(CpuContext ctx, ulong mutexAddress, boo goto retry; case StaleAliasCheck.Kept: resolvedAddress = mutexAddress; + resolve = state.Implicit ? SharpEmu.Libs.Diagnostics.HleCallShapeProfile.MutexResolve.ImplicitSlot : SharpEmu.Libs.Diagnostics.HleCallShapeProfile.MutexResolve.ExplicitSlot; return true; } } else { resolvedAddress = mutexAddress; + resolve = state.Implicit ? SharpEmu.Libs.Diagnostics.HleCallShapeProfile.MutexResolve.ImplicitSlot : SharpEmu.Libs.Diagnostics.HleCallShapeProfile.MutexResolve.ExplicitSlot; return true; } @@ -1813,6 +1841,7 @@ private static bool TryResolveMutexState(CpuContext ctx, ulong mutexAddress, boo if (pointedHandle == StaticAdaptiveMutexInitializer) { + resolve = SharpEmu.Libs.Diagnostics.HleCallShapeProfile.MutexResolve.CreatedStatic; return CreateImplicitMutexState(ctx, mutexAddress, MutexTypeAdaptiveNp, out resolvedAddress, out state); } @@ -1820,6 +1849,7 @@ private static bool TryResolveMutexState(CpuContext ctx, ulong mutexAddress, boo { _mutexStates[mutexAddress] = state; resolvedAddress = pointedHandle; + resolve = SharpEmu.Libs.Diagnostics.HleCallShapeProfile.MutexResolve.Aliased; return true; } @@ -1835,6 +1865,7 @@ private static bool TryResolveMutexState(CpuContext ctx, ulong mutexAddress, boo return false; } + resolve = SharpEmu.Libs.Diagnostics.HleCallShapeProfile.MutexResolve.CreatedZero; return CreateImplicitMutexState(ctx, mutexAddress, MutexTypeErrorCheck, out resolvedAddress, out state); } @@ -3288,6 +3319,7 @@ private static bool CreateImplicitMutexState(CpuContext ctx, ulong mutexAddress, PthreadMutexState? createdState = new PthreadMutexState { Type = type, + Implicit = true, }; if (!TryAllocateOpaqueObject(ctx, MutexObjectSize, out var handle)) diff --git a/tests/SharpEmu.Libs.Tests/Cpu/GatewayCrossingMeasurementTests.cs b/tests/SharpEmu.Libs.Tests/Cpu/GatewayCrossingMeasurementTests.cs new file mode 100644 index 000000000..a9dd5819e --- /dev/null +++ b/tests/SharpEmu.Libs.Tests/Cpu/GatewayCrossingMeasurementTests.cs @@ -0,0 +1,185 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using System.Diagnostics; +using System.Reflection; +using System.Runtime.InteropServices; +using SharpEmu.Core.Cpu.Native; +using SharpEmu.Core.Cpu.Native.Platform; +using SharpEmu.HLE; +using Xunit; + +namespace SharpEmu.Libs.Tests.Cpu; + +/// +/// What a guest import costs to cross into managed code, measured through the real import trampoline: +/// native code calls the trampoline the backend emits for an import, which switches to the host +/// stack and enters the managed gateway (the reverse P/Invoke under Rosetta), and the gateway +/// dispatches a managed export that only sets RAX. Opt-in (SHARPEMU_GATEWAY_BENCH_OUTPUT names the +/// report file): ordinary runs do not collect timing data. +/// +public sealed unsafe class GatewayCrossingMeasurementTests +{ + private const BindingFlags Instance = BindingFlags.Instance | BindingFlags.NonPublic; + + [NativeX64Fact] + public void GatewayCrossingMeasurement() + { + var outputPath = Environment.GetEnvironmentVariable("SHARPEMU_GATEWAY_BENCH_OUTPUT"); + if (string.IsNullOrEmpty(outputPath)) + { + return; + } + + var lines = new List(); + Exception? failure = null; + // The gateway runs 64 KiB below the caller on the same thread stack, as it runs below the + // frame that entered guest code in a game: give the thread room. + var thread = new Thread(() => + { + try + { + Measure(lines); + } + catch (Exception exception) + { + failure = exception; + } + }, 16 << 20); + thread.Start(); + thread.Join(); + File.WriteAllLines(outputPath, lines); + Assert.Null(failure); + } + + private static void Measure(List lines) + { + Thread.CurrentThread.CurrentCulture = System.Globalization.CultureInfo.InvariantCulture; + var modules = new ModuleManager(); + modules.Freeze(); + using var backend = new DirectExecutionBackend(modules); + var type = typeof(DirectExecutionBackend); + type.GetField("_cpuContext", Instance)!.SetValue(backend, new CpuContext(new FakeCpuMemory(0x1_0000_0000, 0x1000), Generation.Gen5)); + // Entry 0 is classified a trivial leaf by its NID; entry 1 takes the full import path. + var entryType = type.GetNestedType("ImportStubEntry", BindingFlags.NonPublic)!; + var entries = Array.CreateInstance(entryType, 2); + var nids = new[] { "V++UgBtQhn0", "gateway-bench-full-path" }; + for (var index = 0; index < nids.Length; index++) + { + var export = new ExportedFunction("bench", nids[index], "gateway bench", Generation.Gen5, c => + { + c[CpuRegister.Rax] = 0; + return 0; + }); + entries.SetValue(Activator.CreateInstance(entryType, [0x200000UL, nids[index], export, false, false, false, false, 0UL]), index); + } + + type.GetField("_importEntries", Instance)!.SetValue(backend, entries); + Assert.True(DirectExecutionBackend.IsTrivialLeafImport(nids[0])); + var createTrampoline = type.GetMethod("CreateImportHandlerTrampoline", Instance)!; + var trivialTrampoline = (nint)createTrampoline.Invoke(backend, [0])!; + var fullTrampoline = (nint)createTrampoline.Invoke(backend, [1])!; + Assert.NotEqual(0, trivialTrampoline); + Assert.NotEqual(0, fullTrampoline); + + var hostRspSlot = (ulong*)NativeMemory.AllocZeroed(sizeof(ulong)); + var hostRspTlsIndex = (uint)type.GetField("_hostRspSlotTlsIndex", Instance)!.GetValue(backend)!; + Assert.True(DirectExecutionPlatform.Current.SetTlsValue(hostRspTlsIndex, (nint)hostRspSlot)); + + // A native stub with no managed crossing at all, for the floor of the same loop. + var nativeOnly = (byte*)HostMemory.Alloc(null, 4096, HostMemory.MEM_COMMIT | HostMemory.MEM_RESERVE, HostMemory.PAGE_EXECUTE_READWRITE); + nativeOnly[0] = 0x31; nativeOnly[1] = 0xC0; nativeOnly[2] = 0xC3; // xor eax, eax / ret + + // The caller: rdi = count, rsi = target, rdx = host RSP slot. It points the slot 64 KiB + // below its own frame and calls the target count times, as guest code calls an import. + var loop = (byte*)HostMemory.Alloc(null, 4096, HostMemory.MEM_COMMIT | HostMemory.MEM_RESERVE, HostMemory.PAGE_EXECUTE_READWRITE); + byte[] code = + [ + 0x53, 0x41, 0x54, 0x41, 0x55, 0x41, 0x56, 0x41, 0x57, 0x55, // push rbx, r12-r15, rbp + 0x48, 0x83, 0xEC, 0x08, // sub rsp, 8 (16-align the calls) + 0x48, 0x89, 0xFB, // mov rbx, rdi + 0x49, 0x89, 0xF4, // mov r12, rsi + 0x48, 0x8D, 0x84, 0x24, 0x00, 0x00, 0xFF, 0xFF, // lea rax, [rsp - 0x10000] + 0x48, 0x83, 0xE0, 0xF0, // and rax, -16 + 0x48, 0x89, 0x02, // mov [rdx], rax + // loop: + 0x31, 0xFF, // xor edi, edi + 0x31, 0xF6, // xor esi, esi + 0x41, 0xFF, 0xD4, // call r12 + 0x48, 0xFF, 0xCB, // dec rbx + 0x75, 0xF4, // jnz loop + 0x48, 0x83, 0xC4, 0x08, // add rsp, 8 + 0x5D, 0x41, 0x5F, 0x41, 0x5E, 0x41, 0x5D, 0x41, 0x5C, 0x5B, // pop rbp, r15-r12, rbx + 0xC3, + ]; + code.CopyTo(new Span(loop, code.Length)); + Assert.True(HostMemory.Protect(loop, 4096, HostMemory.PAGE_EXECUTE_READ, out _)); + Assert.True(HostMemory.Protect(nativeOnly, 4096, HostMemory.PAGE_EXECUTE_READ, out _)); + HostMemory.FlushInstructionCache(loop, 4096); + HostMemory.FlushInstructionCache(nativeOnly, 4096); + var run = (delegate* unmanaged)loop; + + double NanosPerCall(nint target, ulong count) + { + var start = Stopwatch.GetTimestamp(); + run(count, target, hostRspSlot); + return Stopwatch.GetElapsedTime(start).TotalNanoseconds / count; + } + + // The managed half on its own: DispatchImportCore as the gateway calls it, with the per-call + // diagnostics block on (a backend no session configured) and off (_leafDiagnosticsOff). + var dispatch = type.GetMethod("DispatchImportCore", Instance)!.CreateDelegate>(backend); + var pack = Marshal.AllocHGlobal(512); + new Span((void*)pack, 512).Clear(); + *(ulong*)(pack + 192 + 96) = 0x800010000UL; + var diagnosticsOff = type.GetField("_leafDiagnosticsOff", Instance)!; + double ManagedNanosPerCall(int index, int count) + { + var start = Stopwatch.GetTimestamp(); + for (var i = 0; i < count; i++) + { + dispatch(index, pack + 192); + } + + return Stopwatch.GetElapsedTime(start).TotalNanoseconds / count; + } + + try + { + // Warm up every path until tiered compilation has settled. + for (var warm = 0; warm < 5; warm++) + { + NanosPerCall((nint)nativeOnly, 200_000); + NanosPerCall(trivialTrampoline, 400_000); + NanosPerCall(fullTrampoline, 400_000); + ManagedNanosPerCall(0, 400_000); + ManagedNanosPerCall(1, 400_000); + } + + const ulong Calls = 400_000; + foreach (var round in Enumerable.Range(0, 6)) + { + lines.Add( + $"round {round}: native_stub_ns={NanosPerCall((nint)nativeOnly, Calls):F1} " + + $"trampoline_trivial_leaf_ns={NanosPerCall(trivialTrampoline, Calls):F1} " + + $"trampoline_full_path_ns={NanosPerCall(fullTrampoline, Calls):F1}"); + } + + foreach (var off in new[] { false, true, false, true }) + { + diagnosticsOff.SetValue(backend, off); + lines.Add( + $"managed DispatchImportCore leaf_diagnostics_off={off}: trivial_leaf_ns={ManagedNanosPerCall(0, 400_000):F1} " + + $"full_path_ns={ManagedNanosPerCall(1, 400_000):F1}"); + } + } + finally + { + Marshal.FreeHGlobal(pack); + HostMemory.Free(loop, 0, HostMemory.MEM_RELEASE); + HostMemory.Free(nativeOnly, 0, HostMemory.MEM_RELEASE); + DirectExecutionPlatform.Current.SetTlsValue(hostRspTlsIndex, 0); + NativeMemory.Free(hostRspSlot); + } + } +} From 557073a1492f7041fae4419c8ea62b97ae61c542 Mon Sep 17 00:00:00 2001 From: kuba Date: Sun, 15 Nov 2026 02:32:53 +0000 Subject: [PATCH 010/178] [Metal] Answer a stage's texture memo entries and samplers from the last preparation of the same snapshot arrays The materializer hands draws whose descriptors evaluate the same way the same Images and Samplers arrays (Demon's Souls: nine in ten stage bindings), and PrepareBindings looked every T# up in the texture memo and every S# up in the sampler cache again. The stage binding plan keeps, per stage, program and pair of arrays (two-way, 1024 sets), the memo entry each T# key maps to and the sampler for each S# and integer-view class. Each entry's stamp is still checked per use, a stale one is resolved and memoised as on a lookup miss; a cleared memo or sampler cache retires every plan (generations); a host movie stage takes the full path; the sampler class is resolved again per draw. Buffers are not planned. SHARPEMU_METAL_V2_STAGE_PLAN=0 looks everything up; =verify checks every planned answer against a fresh lookup and raises a fatal error on a difference. stage_plan=(...) on the PERF line counts hits and misses by cause. The bind_shape ring scans now run only under SHARPEMU_METAL_V2_BIND_SHAPE=1 or the trace switch. DsDrawCostBench (6 runs per arm, ABBA): draws 3.297 -> 3.254 us, dispatches 4.11 -> 3.97 us, plan hit rate 97.5% / 97.4%, checksums unchanged. Co-Authored-By: Claude --- .../V2/MetalRenderHost.Descriptors.cs | 100 +++++++- .../V2/MetalRenderHost.Pipelines.cs | 1 + .../V2/MetalRenderHost.ReadBindingMemo.cs | 14 +- .../V2/MetalRenderHost.StagePlan.cs | 242 ++++++++++++++++++ .../Scenes/StagePlanSceneTests.cs | 174 +++++++++++++ 5 files changed, 521 insertions(+), 10 deletions(-) create mode 100644 src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.StagePlan.cs create mode 100644 tests/SharpEmu.Gpu.Metal.Tests/Scenes/StagePlanSceneTests.cs diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Descriptors.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Descriptors.cs index 04bdee2d1..184e95af0 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Descriptors.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Descriptors.cs @@ -366,11 +366,14 @@ internal string TakeTextureMemoCounters() // A sampled binding found in the memo with a stamp that still holds; otherwise notes the key for // the full resolution, which reads the owner-list counts over the request before its lookup. - private bool TryTextureMemo(MetalStageBindings prepared, ImageResource image, uint[] words, int index, MetalBindingPacket? packet = null) + // `found` is the entry the key maps to, whether or not its stamp holds (the stage plan keeps it). + private bool TryTextureMemo(MetalStageBindings prepared, ImageResource image, uint[] words, int index, MetalBindingPacket? packet, + out TextureMemoEntry? found) { prepared.MemoHits[index] = null; prepared.MemoWanted[index] = false; - if (!TextureMemoEnabled || image.ResourceClass == MslImageResourceClass.Storage || words.Length < 8) + found = null; + if (!TextureMemoApplies(image, words)) { return false; } @@ -378,7 +381,17 @@ private bool TryTextureMemo(MetalStageBindings prepared, ImageResource image, ui var key = packet is not null && packet.HasMemoKey(index) ? packet.MemoKeys![index] : new TextureMemoKey(words[0], words[1], words[2], words[3], words[4], words[5], words[6], words[7], ShapeOf(image)); - if (_textureMemo.TryGetValue(key, out var entry) && _imageCache.TextureStampMayHold(in entry.Stamp)) + found = _textureMemo.TryGetValue(key, out var entry) ? entry : null; + return TextureMemoAnswer(prepared, found, in key, index); + } + + private static bool TextureMemoApplies(ImageResource image, uint[] words) => + TextureMemoEnabled && image.ResourceClass != MslImageResourceClass.Storage && words.Length >= 8; + + // A hit when the key's entry is there and its stamp may hold; otherwise notes the key for the full resolution. + private bool TextureMemoAnswer(MetalStageBindings prepared, TextureMemoEntry? entry, in TextureMemoKey key, int index) + { + if (entry is not null && _imageCache.TextureStampMayHold(in entry.Stamp)) { // The request stays the entry's (MetalStageBindings.RequestAt): a copy is a quarter-kilobyte of // reference-holding struct per sampled binding per draw. @@ -395,6 +408,13 @@ private bool TryTextureMemo(MetalStageBindings prepared, ImageResource image, ui return false; } + // Drops every entry; the stage plans made before it keep none of theirs (_textureMemoGeneration). + internal void ClearTextureMemo() + { + _textureMemo.Clear(); + _textureMemoGeneration++; + } + private void RememberTexture(MetalStageBindings stage, int index, ResourceSlotIdentifier identifier, in ImageRequest request, in MetalImageCache.TextureMemoStamp stamp) { @@ -403,7 +423,7 @@ private void RememberTexture(MetalStageBindings stage, int index, ResourceSlotId { if (_textureMemo.Count >= TextureMemoLimit) { - _textureMemo.Clear(); + ClearTextureMemo(); } entry = new TextureMemoEntry { Key = key }; @@ -448,6 +468,13 @@ public IPreparedBindings PrepareBindings(ShaderStageResources stage) var movie = FindHostMovieBindings(info, snapshot); prepared.MovieLuma = movie.Luma; prepared.MovieChroma = movie.Chroma; + // The stage binding plan for these arrays (MetalRenderHost.StagePlan.cs), or whether to keep this one's answers. + var plan = FindStagePlan(stageIndex, program, info, snapshot, movie, out var storePlan); + if (storePlan && _stagePlanEntries.Length < info.Images.Count) + { + _stagePlanEntries = new TextureMemoEntry?[info.Images.Count]; + } + for (var index = 0; index < info.Images.Count; index++) { if (index == movie.Luma || index == movie.Chroma) @@ -457,9 +484,40 @@ public IPreparedBindings PrepareBindings(ShaderStageResources stage) continue; } - if (TryTextureMemo(prepared, info.Images[index], snapshot.Images[index], index, packet)) + if (plan?.Entries[index] is { } planned) { - continue; + if (StagePlanVerify) + { + VerifyPlannedImage(prepared, info.Images[index], snapshot.Images[index], index, planned); + } + + prepared.MemoHits[index] = null; + prepared.MemoWanted[index] = false; + if (TextureMemoAnswer(prepared, planned, in planned.Key, index)) + { + continue; + } + + _stagePlanStaleImages++; + } + else + { + var hit = TryTextureMemo(prepared, info.Images[index], snapshot.Images[index], index, packet, out var found); + if (storePlan) + { + _stagePlanEntries[index] = found; + } + else if (plan is not null && TextureMemoApplies(info.Images[index], snapshot.Images[index])) + { + // A memoisable key that had no entry when the plan was made: the plan takes the one found now. + _stagePlanImageLookups++; + plan.Entries[index] = found; + } + + if (hit) + { + continue; + } } ResolveImageBinding(prepared, info.Images[index], snapshot.Images[index], index, packet); @@ -471,9 +529,35 @@ public IPreparedBindings PrepareBindings(ShaderStageResources stage) prepared.SamplerViewClasses.AsSpan(0, info.Samplers.Count)); for (var index = 0; index < info.Samplers.Count; index++) { + var integer = prepared.SamplerViewClasses[index] == MetalSamplerViewClasses.AllInteger; + if (plan is not null && plan.SamplerInteger[index] == integer) + { + if (StagePlanVerify) + { + VerifyPlannedSampler(prepared, info.Samplers[index], snapshot.Samplers[index], index, integer, + plan.SamplerHandles[index], plan.SamplerIds[index]); + } + + prepared.Samplers[index] = plan.SamplerHandles[index]; + prepared.SamplerIds[index] = plan.SamplerIds[index]; + continue; + } + prepared.Samplers[index] = ResolveSampler( - prepared, info.Samplers[index], snapshot.Samplers[index], index, - prepared.SamplerViewClasses[index] == MetalSamplerViewClasses.AllInteger, out prepared.SamplerIds[index], packet); + prepared, info.Samplers[index], snapshot.Samplers[index], index, integer, out prepared.SamplerIds[index], packet); + if (plan is not null) + { + // The class moved with this draw's image requests: the plan takes the sampler for the new one. + _stagePlanSamplerClass++; + plan.SamplerInteger[index] = integer; + plan.SamplerHandles[index] = prepared.Samplers[index]; + plan.SamplerIds[index] = prepared.SamplerIds[index]; + } + } + + if (storePlan) + { + StoreStagePlan(stageIndex, program, info, snapshot, prepared); } var shaderData = prepared.ShaderData; diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Pipelines.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Pipelines.cs index 635361315..8a4e03801 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Pipelines.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Pipelines.cs @@ -2198,5 +2198,6 @@ private void DisposePipelines() } _samplers.Clear(); + _samplerGeneration++; } } diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.ReadBindingMemo.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.ReadBindingMemo.cs index 6a13f9bb0..47a6acce8 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.ReadBindingMemo.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.ReadBindingMemo.cs @@ -119,7 +119,12 @@ private void VerifyReadBinding(ulong address, ulong size, bool computeStage, Met _readBindingMemo.Verified++; } - // ---- What a later stage binding plan would hit (the PERF line's bind_shape): ---- + // ---- The shape of the stage bindings (the PERF line's bind_shape): ---- + + // SHARPEMU_METAL_V2_BIND_SHAPE=1 (or SHARPEMU_METAL_V2_TRACE=1): the epoch moves and snapshot-array repeats too, + // three ring scans per binding; otherwise only the counts. + private static readonly bool BindShapeDiagnostics = + MetalV2Diagnostics.Verbose || Environment.GetEnvironmentVariable("SHARPEMU_METAL_V2_BIND_SHAPE") == "1"; private long _bindCalls; private long _bindImageSetMoves; @@ -140,6 +145,11 @@ private void VerifyReadBinding(ulong address, ulong size, bool computeStage, Met private void NoteBindShape(MetalStageBindings stage, ResourceSnapshot snapshot) { _bindCalls++; + if (!BindShapeDiagnostics) + { + return; + } + var imageSet = _imageCache.ImageSetVersion; var bindingEpoch = _imageCache.Epochs.Binding; if (imageSet != _lastBindImageSet) @@ -183,7 +193,7 @@ private string TakeReadBindingCounters() var text = $"read_binding_memo=({_readBindingMemo.TakeCounters()}) bind_shape=(binds={_bindCalls} " + $"image_set_moves={_bindImageSetMoves} binding_epoch_moves={_bindBindingEpochMoves} " + $"snapshot_repeats=[images={_snapshotRefRepeats[0]},samplers={_snapshotRefRepeats[1]},buffers={_snapshotRefRepeats[2]}]/{_snapshotRefChecks} " + - $"buffers_read_only={_readOnlyBufferBinds} buffers_written={_writtenBufferBinds} tiny_pass_dummies={_tinyPassDummies})"; + $"buffers_read_only={_readOnlyBufferBinds} buffers_written={_writtenBufferBinds} tiny_pass_dummies={_tinyPassDummies}) {TakeStagePlanCounters()}"; _bindCalls = _bindImageSetMoves = _bindBindingEpochMoves = _readOnlyBufferBinds = _writtenBufferBinds = 0; _tinyPassDummies = _snapshotRefChecks = 0; Array.Clear(_snapshotRefRepeats); diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.StagePlan.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.StagePlan.cs new file mode 100644 index 000000000..97e2ee072 --- /dev/null +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.StagePlan.cs @@ -0,0 +1,242 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using System.Runtime.CompilerServices; +using SharpEmu.Libs.Gpu.Rendering; +using SharpEmu.ShaderCompiler; +using SharpEmu.ShaderCompiler.Resources; + +namespace SharpEmu.Gpu.Metal.V2; + +/// +/// A stage's image and sampler lookups answered from the last preparation of the same snapshot arrays (the stage +/// binding plan). The resource materializer hands every draw whose descriptors evaluate the same way the same +/// Images and Samplers arrays (Demon's Souls: nine in ten stage bindings), and PrepareBindings looked each of their +/// T#s up in the texture memo (a hash and a whole-key compare per sampled image) and each S# up in the sampler +/// cache again. The plan keeps what those lookups returned: per image the texture memo entry the T#'s key maps to, +/// per sampler the handle for its words and integer-view class. +/// +/// What a plan's answers depend on, and how each is checked: +/// +/// The stage, the program (its image shapes, sampler resources and sampled pairs) and the T# and S# words: +/// a plan answers only for the same stage, the same and the same Images and Samplers +/// arrays by reference. A published snapshot's arrays are never written (the materializer builds new ones per +/// evaluation and shares them whole); =verify recomputes every key from the words to catch one that was. +/// Which memo entry a key maps to: an entry changes in place only for its own key (RememberTexture), so +/// the entry stays the one a lookup returns until the memo is cleared (its generation, checked per plan). +/// Whether the entry's stamp holds: checked for every use exactly as on a lookup hit, and a binding whose stamp +/// fails is resolved and memoised as on a lookup miss. A memoisable image whose key had no entry when the plan was +/// made is looked up each time, and the plan takes the entry once a lookup finds one. +/// A host movie plane: a stage with one takes the full path (FindHostMovieBindings runs for every preparation). +/// The sampler handles: the sampler cache is only ever cleared whole (its generation, checked per plan). +/// A sampler's integer-view class: resolved again for every preparation from this draw's image requests; a +/// planned handle answers only for the class it was made for, and the plan takes the other one when it moves. +/// +/// Buffers are not planned: what a buffer binding answers depends on live state (mapping, staged copies, GPU-modified +/// images, the window), which MetalReadBindingMemo already stamps per range. SHARPEMU_METAL_V2_STAGE_PLAN=0 looks +/// everything up; =verify also checks every planned answer against a fresh lookup and raises a fatal error when one +/// differs. +/// +internal sealed partial class MetalRenderHost +{ + private static readonly string? StagePlanSetting = Environment.GetEnvironmentVariable("SHARPEMU_METAL_V2_STAGE_PLAN"); + + internal bool StagePlanEnabled { get; set; } = StagePlanSetting != "0"; + + internal bool StagePlanVerify { get; set; } = + StagePlanSetting == "verify" || Environment.GetEnvironmentVariable("SHARPEMU_PERF_VERIFY") == "1"; + + private sealed class StagePlan + { + public int Stage; + public ShaderProgramInfo? Program; + public uint[][]? Images; + public uint[][]? Samplers; + public long MemoGeneration; + public long SamplerGeneration; + // Per image the memo entry its key maps to; null for a binding the memo does not take, or a key that had none. + public TextureMemoEntry?[] Entries = []; + public bool[] SamplerInteger = []; + public nint[] SamplerHandles = []; + public ulong[] SamplerIds = []; + } + + // Two ways per set, the more recently used first. + private const int StagePlanSets = 1024; + private readonly StagePlan?[] _stagePlans = new StagePlan?[StagePlanSets * 2]; + private TextureMemoEntry?[] _stagePlanEntries = []; + private long _textureMemoGeneration; + private long _samplerGeneration; + + private long _stagePlanHits, _stagePlanAbsent, _stagePlanMemoCleared, _stagePlanSamplersCleared, _stagePlanMovie; + private long _stagePlanStores, _stagePlanEvictions, _stagePlanStaleImages, _stagePlanImageLookups; + private long _stagePlanSamplerClass, _stagePlanVerified; + + internal (long Hits, long Absent, long MemoCleared, long Stores, long StaleImages, long ImageLookups, long Verified) StagePlanCounts => + (_stagePlanHits, _stagePlanAbsent, _stagePlanMemoCleared, _stagePlanStores, _stagePlanStaleImages, _stagePlanImageLookups, + _stagePlanVerified); + + private static int StagePlanSet(int stage, uint[][] images, uint[][] samplers) => + (int)((((uint)RuntimeHelpers.GetHashCode(images) * 0x9E3779B1u) ^ ((uint)RuntimeHelpers.GetHashCode(samplers) * 0x85EBCA77u) ^ + ((uint)stage * 0xC2B2AE3Du)) >> 22) & (StagePlanSets - 1); + + private static bool PlanFor([System.Diagnostics.CodeAnalysis.NotNullWhen(true)] StagePlan? plan, int stage, ShaderProgramInfo program, + ResourceSnapshot snapshot) => + plan is not null && plan.Stage == stage && ReferenceEquals(plan.Program, program) && + ReferenceEquals(plan.Images, snapshot.Images) && ReferenceEquals(plan.Samplers, snapshot.Samplers); + + /// + /// The plan for this stage's arrays when one stands; otherwise null, with set when the + /// full path's answers should be kept as the plan. + /// + private StagePlan? FindStagePlan(int stage, ShaderProgramInfo program, ShaderResourceInfo info, ResourceSnapshot snapshot, + MetalHostMovieSelector.Bindings movie, out bool store) + { + store = false; + if (!StagePlanEnabled || info.Images.Count + info.Samplers.Count == 0) + { + return null; + } + + if (movie != MetalHostMovieSelector.Bindings.None) + { + _stagePlanMovie++; + return null; + } + + store = true; + var way = StagePlanSet(stage, snapshot.Images, snapshot.Samplers) * 2; + var plan = _stagePlans[way]; + if (!PlanFor(plan, stage, program, snapshot)) + { + plan = _stagePlans[way + 1]; + if (!PlanFor(plan, stage, program, snapshot)) + { + _stagePlanAbsent++; + return null; + } + + (_stagePlans[way], _stagePlans[way + 1]) = (plan, _stagePlans[way]); + } + + if (plan.MemoGeneration != _textureMemoGeneration) + { + _stagePlanMemoCleared++; + return null; + } + + if (plan.SamplerGeneration != _samplerGeneration) + { + _stagePlanSamplersCleared++; + return null; + } + + store = false; + _stagePlanHits++; + return plan; + } + + // The full path's answers for this stage's arrays, from the memo entries its lookups found (_stagePlanEntries) + // and the samplers it resolved. Reuses the evicted plan's object: a stage whose arrays never repeat allocates nothing. + private void StoreStagePlan(int stage, ShaderProgramInfo program, ShaderResourceInfo info, ResourceSnapshot snapshot, + MetalStageBindings prepared) + { + var way = StagePlanSet(stage, snapshot.Images, snapshot.Samplers) * 2; + StagePlan plan; + if (PlanFor(_stagePlans[way], stage, program, snapshot)) + { + plan = _stagePlans[way]!; + } + else if (PlanFor(_stagePlans[way + 1], stage, program, snapshot)) + { + plan = _stagePlans[way + 1]!; + (_stagePlans[way], _stagePlans[way + 1]) = (plan, _stagePlans[way]); + } + else + { + // The less recently used way's object takes the new plan, in front. + plan = _stagePlans[way + 1] ?? new StagePlan(); + if (plan.Images is not null) + { + _stagePlanEvictions++; + } + + _stagePlans[way + 1] = _stagePlans[way]; + _stagePlans[way] = plan; + } + + var images = info.Images.Count; + var samplers = info.Samplers.Count; + if (plan.Entries.Length < images) + { + plan.Entries = new TextureMemoEntry?[images]; + } + + if (plan.SamplerHandles.Length < samplers) + { + plan.SamplerInteger = new bool[samplers]; + plan.SamplerHandles = new nint[samplers]; + plan.SamplerIds = new ulong[samplers]; + } + + Array.Copy(_stagePlanEntries, plan.Entries, images); + for (var index = 0; index < samplers; index++) + { + plan.SamplerInteger[index] = prepared.SamplerViewClasses[index] == MetalSamplerViewClasses.AllInteger; + plan.SamplerHandles[index] = prepared.Samplers[index]; + plan.SamplerIds[index] = prepared.SamplerIds[index]; + } + + plan.Stage = stage; + plan.Program = program; + plan.Images = snapshot.Images; + plan.Samplers = snapshot.Samplers; + plan.MemoGeneration = _textureMemoGeneration; + plan.SamplerGeneration = _samplerGeneration; + _stagePlanStores++; + } + + // =verify: the entry a fresh lookup of the image's key returns is the planned one. + private void VerifyPlannedImage(MetalStageBindings prepared, ImageResource image, uint[] words, int index, TextureMemoEntry planned) + { + TextureMemoEntry? found = null; + if (!TextureMemoApplies(image, words) || + !_textureMemo.TryGetValue(new TextureMemoKey(words[0], words[1], words[2], words[3], words[4], words[5], words[6], words[7], + ShapeOf(image)), out found) || !ReferenceEquals(found, planned)) + { + throw Fatal( + $"The stage plan's texture memo entry differs from a lookup: hash=0x{prepared.Program.Hash:X16} image={index} " + + $"planned=0x{planned.Key.W0:X8}/{planned.Image} found={(found is null ? "none" : $"0x{found.Key.W0:X8}/{found.Image}")}."); + } + + _stagePlanVerified++; + } + + // =verify: the sampler a fresh lookup of the S# and class returns is the planned one. + private void VerifyPlannedSampler(MetalStageBindings prepared, SamplerResource sampler, uint[] words, int index, bool integer, + nint planned, ulong plannedId) + { + var descriptor = NativeSamplerWords(sampler, words); + var found = GetSampler(in descriptor, integer, out var foundId); + if (found != planned || foundId != plannedId) + { + throw Fatal( + $"The stage plan's sampler differs from a lookup: hash=0x{prepared.Program.Hash:X16} sampler={index} " + + $"integer={integer} planned=0x{planned:X}/{plannedId} found=0x{found:X}/{foundId}."); + } + + _stagePlanVerified++; + } + + private string TakeStagePlanCounters() + { + var text = $"stage_plan=(hits={_stagePlanHits} absent={_stagePlanAbsent} memo_cleared={_stagePlanMemoCleared} " + + $"samplers_cleared={_stagePlanSamplersCleared} movie={_stagePlanMovie} stores={_stagePlanStores} " + + $"evictions={_stagePlanEvictions} stale_images={_stagePlanStaleImages} image_lookups={_stagePlanImageLookups} " + + $"sampler_class={_stagePlanSamplerClass} verified={_stagePlanVerified})"; + _stagePlanHits = _stagePlanAbsent = _stagePlanMemoCleared = _stagePlanSamplersCleared = _stagePlanMovie = 0; + _stagePlanStores = _stagePlanEvictions = _stagePlanStaleImages = _stagePlanImageLookups = 0; + _stagePlanSamplerClass = _stagePlanVerified = 0; + return text; + } +} diff --git a/tests/SharpEmu.Gpu.Metal.Tests/Scenes/StagePlanSceneTests.cs b/tests/SharpEmu.Gpu.Metal.Tests/Scenes/StagePlanSceneTests.cs new file mode 100644 index 000000000..9cae240cb --- /dev/null +++ b/tests/SharpEmu.Gpu.Metal.Tests/Scenes/StagePlanSceneTests.cs @@ -0,0 +1,174 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using System.Runtime.InteropServices; +using SharpEmu.Gpu.Metal.V2; +using Xunit; +using Xunit.Abstractions; + +namespace SharpEmu.Gpu.Metal.Tests.Scenes; + +/// +/// A stage whose snapshot arrays were prepared before takes its texture memo entries and samplers from that +/// preparation (the stage binding plan, MetalRenderHost.StagePlan.cs). Every draw renders a stripe of one target with +/// the texture it binds, under =verify (each planned answer checked against a fresh lookup), and each case that +/// retires a plan or one of its answers must render what the full path renders. +/// +public sealed class StagePlanSceneTests(ITestOutputHelper output) : SceneTestBase(output) +{ + private const uint Rgba8 = 56; + private const uint Size = 8; + private const uint Width = 16; + private const uint Red = 0xFF0000FF; + private const uint Green = 0xFF00FF00; + + private sealed class Scene + { + private readonly SceneRig _rig; + private readonly ulong _target; + private readonly SceneState _state; + private readonly SceneVertex[] _quad = + [ + SceneVertex.At(-1, -1, 0.5f, 0, 1, 0, 1), SceneVertex.At(1, -1, 0.5f, 1, 1, 0, 1), + SceneVertex.At(-1, 1, 0.5f, 0, 0, 0, 1), SceneVertex.At(-1, 1, 0.5f, 0, 0, 0, 1), + SceneVertex.At(1, -1, 0.5f, 1, 1, 0, 1), SceneVertex.At(1, 1, 0.5f, 1, 0, 0, 1), + ]; + + public Scene(SceneRig rig, bool plan) + { + _rig = rig; + rig.Host.StagePlanEnabled = plan; + rig.Host.StagePlanVerify = plan; + _target = rig.ColorTarget(Width, Width, 16, 0xFF); + _state = new SceneState(Width, Width).ColorTarget(0, _target, Width, Width, format: 14, numberType: 7); + } + + public ulong Solid(uint abgr) + { + var texels = new uint[Size * 64]; + Array.Fill(texels, abgr); + var address = _rig.Memory.Allocate(Size * 64 * 4, 0x10000); + _rig.Memory.Write(address, MemoryMarshal.AsBytes(texels.AsSpan())); + return address; + } + + // One draw over columns [left, right) sampling the texture through a T# of the given extent. + public void Stripe(ScenePm4 pm4, int left, int right, ulong texture, uint extent = Size) + { + _state.ScreenScissor(left, 0, right, (int)Width); + uint[] data = [.. Descriptors.Texture(texture, Rgba8, extent, extent), .. Descriptors.Sampler()]; + _rig.DrawMesh(pm4, _state, _quad, ScenePrograms.SampledTexture, data); + } + + public void Submit(params Action[] stripes) + { + var pm4 = new ScenePm4(); + foreach (var stripe in stripes) stripe(pm4); + _rig.Submit(pm4); + } + + public void AssertColour(int x, uint abgr) + { + var pixels = MemoryMarshal.Cast(_rig.ReadImage(_target, Width, Width, 16)); + var actual = pixels.Slice((int)((8 * Width + (uint)x) * 4), 4).ToArray(); + float[] expected = + [(abgr & 0xFF) / 255f, ((abgr >> 8) & 0xFF) / 255f, ((abgr >> 16) & 0xFF) / 255f, ((abgr >> 24) & 0xFF) / 255f]; + for (var channel = 0; channel < 4; channel++) + { + Assert.True(MathF.Abs(actual[channel] - expected[channel]) <= 0.01f, + $"column {x}: channel {channel} is {actual[channel]}, expected {expected[channel]}"); + } + } + } + + // A material bound again takes the plan: its first draw stores it, the next finds its texture's memo entry + // (made by the first draw's binding), and the ones after take the entry from the plan. + [Theory] + [InlineData(true)] + [InlineData(false)] + public void RepeatedMaterialsAreAnsweredFromTheirPlanAndRenderAsWithout(bool plan) + { + using var rig = CreateRig(); + if (rig is null) return; + var scene = new Scene(rig, plan); + var red = scene.Solid(Red); + var green = scene.Solid(Green); + scene.Submit( + pm4 => scene.Stripe(pm4, 0, 3, red), + pm4 => scene.Stripe(pm4, 3, 6, red), + pm4 => scene.Stripe(pm4, 6, 9, green), + pm4 => scene.Stripe(pm4, 9, 12, red), + pm4 => scene.Stripe(pm4, 12, 16, green)); + scene.AssertColour(1, Red); + scene.AssertColour(4, Red); + scene.AssertColour(7, Green); + scene.AssertColour(10, Red); + scene.AssertColour(14, Green); + var counts = rig.Host.StagePlanCounts; + output.WriteLine($"plan={plan} {counts}"); + if (plan) + { + Assert.True(counts.Hits >= 3, $"the repeated materials took {counts.Hits} plans"); + Assert.True(counts.ImageLookups >= 1, "no plan took the memo entry its first binding made"); + Assert.True(counts.Verified > 0, "no planned answer was verified"); + } + else + { + Assert.Equal(0L, counts.Hits); + Assert.Equal(0L, counts.Stores); + } + + Assert.Empty(rig.Fatals); + } + + // Another image over a planned texture's bytes (the same address through a T# of another extent) moves the owner + // versions its memo stamp holds: the planned binding is resolved again and memoised as on a lookup miss. + [Fact] + public void AnImageAddedOverAPlannedTextureSendsItsBindingDownTheFullPath() + { + using var rig = CreateRig(); + if (rig is null) return; + var scene = new Scene(rig, plan: true); + var red = scene.Solid(Red); + scene.Submit( + pm4 => scene.Stripe(pm4, 0, 4, red), + pm4 => scene.Stripe(pm4, 4, 8, red), + pm4 => scene.Stripe(pm4, 8, 12, red)); + var before = rig.Host.StagePlanCounts; + Assert.Equal(0L, before.StaleImages); + + scene.Submit( + pm4 => scene.Stripe(pm4, 0, 8, red, extent: Size / 2), + pm4 => scene.Stripe(pm4, 8, 16, red)); + var after = rig.Host.StagePlanCounts; + output.WriteLine($"{before} -> {after}"); + Assert.True(after.Hits > before.Hits, "the original material took no plan after the other image came"); + Assert.True(after.StaleImages > before.StaleImages, "the planned binding's stamp held over a new image"); + scene.AssertColour(12, Red); + Assert.Empty(rig.Fatals); + } + + // Clearing the texture memo retires every plan made before it: the next binding looks its texture up again. + [Fact] + public void AClearedTextureMemoRetiresThePlansMadeBeforeIt() + { + using var rig = CreateRig(); + if (rig is null) return; + var scene = new Scene(rig, plan: true); + var red = scene.Solid(Red); + var green = scene.Solid(Green); + scene.Submit(pm4 => scene.Stripe(pm4, 0, 8, red), pm4 => scene.Stripe(pm4, 8, 16, red)); + var before = rig.Host.StagePlanCounts; + Assert.True(before.Hits >= 1); + + rig.Host.ClearTextureMemo(); + scene.Submit(pm4 => scene.Stripe(pm4, 0, 8, red), pm4 => scene.Stripe(pm4, 8, 16, green)); + var after = rig.Host.StagePlanCounts; + output.WriteLine($"{before} -> {after}"); + Assert.Equal(before.MemoCleared + 1, after.MemoCleared); + Assert.Equal(before.Hits, after.Hits); + scene.AssertColour(4, Red); + scene.AssertColour(12, Green); + Assert.Empty(rig.Fatals); + } +} From 90871ad4d46051f3d55d1df7d58104adbcaa8463 Mon Sep 17 00:00:00 2001 From: kuba Date: Sun, 15 Nov 2026 02:38:38 +0000 Subject: [PATCH 011/178] [Metal] Keep two read-only binding memo entries per set and count why lookups miss Demon's Souls answered 37% of its read-only binding lookups from the memo against 91-98% in the bench, with nearly every miss stored again. In DsDrawCostBench most draw misses were other ranges' entries in the range's direct-mapped slot (170k of 217k misses over the run); a command buffer binds a few thousand ranges. The memo now keeps two ways per set (2048 sets), the more recently used first, and the PERF line's read_binding_memo field says why lookups missed (empty set, other ranges, alias or which stamp field moved, live refusals) and how many stores evicted another range, for the next game run to read. DsDrawCostBench (6 runs per arm, ABBA): draw memo hit rate 91.3% -> 97.9% (remaining misses: a new command buffer's serial), draws 3.288 -> 3.272 us, dispatches 3.98 -> 3.86 us (noisy), checksums unchanged. Co-Authored-By: Claude --- .../V2/MetalReadBindingMemo.cs | 80 ++++++++++++++++--- .../V2/MetalRenderHost.ReadBindingMemo.cs | 16 +++- 2 files changed, 83 insertions(+), 13 deletions(-) diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalReadBindingMemo.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalReadBindingMemo.cs index e9e12d9a8..ebb15a19c 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalReadBindingMemo.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalReadBindingMemo.cs @@ -35,35 +35,88 @@ private struct Entry public MetalGuestRange Range; } - private const int Slots = 1024; - private readonly Entry[] _entries = new Entry[Slots]; + // Two ways per set, the more recently used first: a frame's command buffer binds a few thousand ranges, which + // direct-mapped slots lost to collisions (most of the DsDrawCostBench draws' misses before). + private const int Sets = 2048; + private readonly Entry[] _entries = new Entry[Sets * 2]; public long Hits; public long Misses; public long Stores; public long Verified; - private static int SlotOf(ulong address, ulong size, bool compute) => - (int)((((address >> 4) * 0x9E3779B97F4A7C15UL) ^ (size * 0xC2B2AE3D27D4EB4FUL) ^ (compute ? 1UL : 0UL)) >> 54) & (Slots - 1); + // Why lookups missed: an empty set, other ranges' entries in it (collisions or evictions), or this range's + // entry with another alias or stamp (each field that moved counts, so they can add up past the misses); refused + // are the caller's live refusals and windows that no longer stand. Evictions are stores over another range's entry. + public long MissEmpty, MissOtherKey, MissAlias, MissSerial, MissPartition, MissTrap, MissImageSet, MissGpuModified; + public long MissRefused, Evictions; + + private static int SetOf(ulong address, ulong size, bool compute) + { + var hash = ((address >> 4) * 0x9E3779B97F4A7C15UL) ^ (size * 0xC2B2AE3D27D4EB4FUL) ^ (compute ? 0x165667B19E3779F9UL : 0UL); + return (int)((hash ^ (hash >> 29)) >> 40) & (Sets - 1); + } + + private static bool Holds(in Entry entry, ulong address, ulong size, bool compute) => + entry.Valid && entry.Address == address && entry.Size == size && entry.Compute == compute; /// The range kept for this binding at this stamp and alias, if one is. public bool TryGet(ulong address, ulong size, bool compute, ulong alias, in Stamp stamp, out MetalGuestRange range) { - ref var entry = ref _entries[SlotOf(address, size, compute)]; - if (entry.Valid && entry.Address == address && entry.Size == size && entry.Compute == compute && - entry.Alias == alias && entry.Stamp == stamp) + var way = SetOf(address, size, compute) * 2; + ref var first = ref _entries[way]; + if (!Holds(in first, address, size, compute)) + { + ref var second = ref _entries[way + 1]; + if (Holds(in second, address, size, compute)) + { + (first, second) = (second, first); + } + else + { + MissEmpty += !first.Valid && !second.Valid ? 1 : 0; + MissOtherKey += first.Valid || second.Valid ? 1 : 0; + range = default; + return false; + } + } + + if (first.Alias == alias && first.Stamp == stamp) { - range = entry.Range; + range = first.Range; return true; } + NoteStale(in first, alias, in stamp); range = default; return false; } + private void NoteStale(in Entry entry, ulong alias, in Stamp stamp) + { + if (entry.Alias != alias) MissAlias++; + if (entry.Stamp.Serial != stamp.Serial) MissSerial++; + if (entry.Stamp.Partition != stamp.Partition) MissPartition++; + if (entry.Stamp.Trap != stamp.Trap) MissTrap++; + if (entry.Stamp.ImageSet != stamp.ImageSet) MissImageSet++; + if (entry.Stamp.GpuModified != stamp.GpuModified) MissGpuModified++; + } + public void Store(ulong address, ulong size, bool compute, ulong alias, in Stamp stamp, in MetalGuestRange range) { - ref var entry = ref _entries[SlotOf(address, size, compute)]; + var way = SetOf(address, size, compute) * 2; + if (!Holds(in _entries[way], address, size, compute)) + { + if (!Holds(in _entries[way + 1], address, size, compute)) + { + // The less recently used way goes; the new entry takes the front. + Evictions += _entries[way + 1].Valid ? 1 : 0; + } + + _entries[way + 1] = _entries[way]; + } + + ref var entry = ref _entries[way]; entry.Address = address; entry.Size = size; entry.Alias = alias; @@ -74,11 +127,16 @@ public void Store(ulong address, ulong size, bool compute, ulong alias, in Stamp Stores++; } - /// hits, misses, stores and verified hits since the last call; resets them. + /// hits, misses (and why), stores, evictions and verified hits since the last call; resets them. public string TakeCounters() { - var text = $"hits={Hits} misses={Misses} stores={Stores} verified={Verified}"; + var text = $"hits={Hits} misses={Misses} stores={Stores} verified={Verified} " + + $"miss_by=(empty={MissEmpty},other_key={MissOtherKey},alias={MissAlias},serial={MissSerial}," + + $"partition={MissPartition},trap={MissTrap},image_set={MissImageSet},gpu_modified={MissGpuModified}," + + $"refused={MissRefused}) evictions={Evictions}"; Hits = Misses = Stores = Verified = 0; + MissEmpty = MissOtherKey = MissAlias = MissSerial = MissPartition = MissTrap = MissImageSet = MissGpuModified = 0; + MissRefused = Evictions = 0; return text; } } diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.ReadBindingMemo.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.ReadBindingMemo.cs index 47a6acce8..06f2ac8ae 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.ReadBindingMemo.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.ReadBindingMemo.cs @@ -75,10 +75,22 @@ private bool TryReadBindingMemo(ulong address, ulong size, bool computeStage, ou return false; } - if (!ReadBindingMemoApplies || !_backing.TryResolveBackingAliasSpan(address, size, out var alias) || - !_readBindingMemo.TryGet(address, size, computeStage, alias, ReadBindingStamp(), out range) || + if (!ReadBindingMemoApplies || !_backing.TryResolveBackingAliasSpan(address, size, out var alias)) + { + _readBindingMemo.Misses++; + _readBindingMemo.MissRefused++; + return false; + } + + if (!_readBindingMemo.TryGet(address, size, computeStage, alias, ReadBindingStamp(), out range) || !_guestMemory.InPlaceAnswerStands(alias, size)) { + if (range.IsValid) + { + // The entry matched; the window under it no longer stands. + _readBindingMemo.MissRefused++; + } + _readBindingMemo.Misses++; range = default; return false; From c3305bc44dbd9714108fa172a2ec8d562b676905 Mon Sep 17 00:00:00 2001 From: kuba Date: Sun, 15 Nov 2026 02:41:15 +0000 Subject: [PATCH 012/178] [Metal] Name an encoder's end cause from a table instead of two strings per encoder EndEncoders formatted the cause as cause.ToString().ToLowerInvariant() for the pass profile and union-pass notes on every render and compute encoder it ended, two allocations each. The lowercase names are made once. DsDrawCostBench (6 runs per arm, ABBA; its streams end few encoders, so this is a no-change check): draws 3.286 -> 3.277 us, dispatches 4.06 -> 4.00 us, checksums unchanged. Co-Authored-By: Claude --- src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.cs | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.cs index 2587aebd1..f9cac4863 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.cs @@ -545,6 +545,10 @@ private enum PassEndCause Other, } + // The causes' names as the pass profile and union-pass notes take them, made once instead of twice per encoder end. + private static readonly string[] PassEndCauseNames = + Enum.GetValues().Select(cause => cause.ToString().ToLowerInvariant()).ToArray(); + /// Why a command buffer was committed (the flush_by field of the PERF line). internal enum MetalFlushCause : byte { @@ -566,7 +570,7 @@ private void EndEncoders(PassEndCause cause) _transferSharesCompute = false; if (_renderEncoder != 0) { - PassProfileNoteEnd(cause == PassEndCause.Transfer ? _ppTransferCause : cause.ToString().ToLowerInvariant()); + PassProfileNoteEnd(cause == PassEndCause.Transfer ? _ppTransferCause : PassEndCauseNames[(int)cause]); switch (cause) { case PassEndCause.Transfer: _passEndTransfer++; break; @@ -582,7 +586,7 @@ private void EndEncoders(PassEndCause cause) if (_computeEncoder != 0) { _encodersInBuffer++; - PassProfileNoteEnd(cause == PassEndCause.Transfer ? _ppTransferCause : cause.ToString().ToLowerInvariant()); + PassProfileNoteEnd(cause == PassEndCause.Transfer ? _ppTransferCause : PassEndCauseNames[(int)cause]); EndAndReleaseEncoder(_computeEncoder, render: false); _computeEncoder = 0; _boundComputePipeline = 0; From cc680a1e03d978319840a637bcd039e88ef9e82b Mon Sep 17 00:00:00 2001 From: kuba Date: Sun, 15 Nov 2026 02:42:31 +0000 Subject: [PATCH 013/178] [Metal] Count storage-image binds, compute encoders and the residents each encoder is told The dispatch extras of the host encode-cost plan are sized offline but not in the game: in DsDrawCostBench a storage image's resolution and acquire take about 0.3 us each (two per dispatch, about 30% of a dispatch's recording), and every compute encoder is told the submission's resident windows again (209 at the Demon's Souls run's 120 s mark). The PERF line's bind_shape gains storage_images and the WAITS line residency_named and compute_encoders, so the next game run says what memoising storage images or a residency set for the windows would save before either is built. Co-Authored-By: Claude --- .../V2/MetalRenderHost.Descriptors.cs | 10 ++++++++++ .../V2/MetalRenderHost.ReadBindingMemo.cs | 5 +++-- .../SharpEmu.Gpu.Metal/V2/MetalRenderHost.Rendering.cs | 1 + src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.cs | 1 + 4 files changed, 15 insertions(+), 2 deletions(-) diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Descriptors.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Descriptors.cs index 184e95af0..a6c5bd935 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Descriptors.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Descriptors.cs @@ -978,6 +978,7 @@ public void BindResources(IPreparedBindings prepared) var role = stage.IsStorage[index] ? ImageRole.StorageImage : ImageRole.Texture; if (stage.IsStorage[index]) { + _storageImageBinds++; request = request with { View = request.View with { LevelCount = 1 } }; stage.Requests[index] = request; } @@ -2281,6 +2282,10 @@ private void ApplyStageBindings(bool graphics) private int _encoderResidentCount; private readonly Dictionary _encoderResidentIndex = new(); private long _residencyCallsSkipped; + // Resources an encoder was told (not skipped), and compute encoders opened: what re-declaring the submission's + // residents to every new compute encoder costs (the WAITS line's residency_named and compute_encoders). + private long _residencyCallsNamed; + private long _computeEncodersOpened; private void ForgetResidentResources() { @@ -2296,6 +2301,9 @@ private void ForgetResidentResources() /// How many -useResource: calls the encoder cache skipped. public long TakeSkippedResidencyCalls() => Interlocked.Exchange(ref _residencyCallsSkipped, 0); + private string TakeResidencyNameCounters() => + $" residency_named={Interlocked.Exchange(ref _residencyCallsNamed, 0)} compute_encoders={Interlocked.Exchange(ref _computeEncodersOpened, 0)}"; + // A device-address program can dereference any mapped guest page, so the encoder that // runs one names the windows the address table spans, whether or not anything resolved // a range through them - or, with the reach profile, those holding the granules the @@ -2461,6 +2469,7 @@ private bool TryNoteResident(nint resource, nuint usage, nuint stages) _encoderResidentUsage[index] |= usage; _encoderResidentStages[index] |= stages; + _residencyCallsNamed++; return true; } @@ -2476,6 +2485,7 @@ private bool TryNoteResident(nint resource, nuint usage, nuint stages) _encoderResidentUsage[_encoderResidentCount] = usage; _encoderResidentStages[_encoderResidentCount] = stages; _encoderResidentCount++; + _residencyCallsNamed++; return true; } diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.ReadBindingMemo.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.ReadBindingMemo.cs index 06f2ac8ae..d847582cb 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.ReadBindingMemo.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.ReadBindingMemo.cs @@ -146,6 +146,7 @@ private void VerifyReadBinding(ulong address, ulong size, bool computeStage, Met private long _readOnlyBufferBinds; private long _writtenBufferBinds; private long _tinyPassDummies; + private long _storageImageBinds; // Per stage kind, the last eight Images, Samplers and Buffers arrays a snapshot bound, and how often one repeated. private const int SnapshotRefSlots = 8; @@ -205,9 +206,9 @@ private string TakeReadBindingCounters() var text = $"read_binding_memo=({_readBindingMemo.TakeCounters()}) bind_shape=(binds={_bindCalls} " + $"image_set_moves={_bindImageSetMoves} binding_epoch_moves={_bindBindingEpochMoves} " + $"snapshot_repeats=[images={_snapshotRefRepeats[0]},samplers={_snapshotRefRepeats[1]},buffers={_snapshotRefRepeats[2]}]/{_snapshotRefChecks} " + - $"buffers_read_only={_readOnlyBufferBinds} buffers_written={_writtenBufferBinds} tiny_pass_dummies={_tinyPassDummies}) {TakeStagePlanCounters()}"; + $"buffers_read_only={_readOnlyBufferBinds} buffers_written={_writtenBufferBinds} storage_images={_storageImageBinds} tiny_pass_dummies={_tinyPassDummies}) {TakeStagePlanCounters()}"; _bindCalls = _bindImageSetMoves = _bindBindingEpochMoves = _readOnlyBufferBinds = _writtenBufferBinds = 0; - _tinyPassDummies = _snapshotRefChecks = 0; + _tinyPassDummies = _snapshotRefChecks = _storageImageBinds = 0; Array.Clear(_snapshotRefRepeats); return text; } diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Rendering.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Rendering.cs index 779cb9ed0..f581dbb7f 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Rendering.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Rendering.cs @@ -1496,6 +1496,7 @@ private nint EnsureComputeEncoder(bool materializeClears) // A new encoder has none of the residency the last one was given. ForgetResidentResources(); + _computeEncodersOpened++; return _computeEncoder; } diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.cs index f9cac4863..69ec0a00e 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.cs @@ -2848,6 +2848,7 @@ public void ReportCounters() .Append(" label_barriers=").Append(TakeLabelBarriers()) .Append(" encoder_barriers=").Append(TakeEncoderBarriers()) .Append(" residency_skipped=").Append(TakeSkippedResidencyCalls()) + .Append(TakeResidencyNameCounters()) .Append(" device_address_writes=").Append(DeviceAddressWrites) .Append(TakeDeviceAddressReachCounters()) .Append(" data_slots_device=").Append(SharpEmu.ShaderCompiler.Resources.DeviceDataLoads.LearnedSlots) From 656864d2a012f6ded02e50b70ad070351480dba7 Mon Sep 17 00:00:00 2001 From: kuba Date: Sun, 15 Nov 2026 02:46:39 +0000 Subject: [PATCH 014/178] [Tools] PerfAudit contend: managed guest-memory access cost from 1-12 threads Each thread reads and writes its own 64 KiB of a real PhysicalVirtualMemory backing (r8, r36, w8, pair, emit), and calls SharedBackingViews' single-view paths directly counting refusals; the write rows rerun with HostBackingObject._managedWrites nulled to split the write-interval ledger's cost from the alias pins'. Primitives p1-p7 (shared and padded Interlocked, ThreadStatic, CurrentManagedThreadId, MemoryBarrier, shared RWLS read, private-region PVM read). --qos=ui runs the workers at user-interactive QoS. --- .../Benches.AgcBuilders.cs | 2 +- .../Benches.Contention.cs | 305 ++++++++++++++++++ tools/SharpEmu.Tools.PerfAudit/Program.cs | 1 + 3 files changed, 307 insertions(+), 1 deletion(-) create mode 100644 tools/SharpEmu.Tools.PerfAudit/Benches.Contention.cs diff --git a/tools/SharpEmu.Tools.PerfAudit/Benches.AgcBuilders.cs b/tools/SharpEmu.Tools.PerfAudit/Benches.AgcBuilders.cs index 886fa6713..d234bb253 100644 --- a/tools/SharpEmu.Tools.PerfAudit/Benches.AgcBuilders.cs +++ b/tools/SharpEmu.Tools.PerfAudit/Benches.AgcBuilders.cs @@ -24,7 +24,7 @@ internal static unsafe class AgcBuilderBenches private const ulong Dwords = 0x8000; // The guest process's image store minus the transport: the interest filter of RemoteImageStore. - private sealed class FilterStore(SplitSharedState state) : IGuestImageStore + internal sealed class FilterStore(SplitSharedState state) : IGuestImageStore { public long Landed; public bool MarkCpuWrite(ulong address, ulong size) => false; diff --git a/tools/SharpEmu.Tools.PerfAudit/Benches.Contention.cs b/tools/SharpEmu.Tools.PerfAudit/Benches.Contention.cs new file mode 100644 index 000000000..a9a042fdd --- /dev/null +++ b/tools/SharpEmu.Tools.PerfAudit/Benches.Contention.cs @@ -0,0 +1,305 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using System.Diagnostics; +using System.Globalization; +using System.Reflection; +using System.Runtime.InteropServices; +using System.Text; +using SharpEmu.Core.Cpu; +using SharpEmu.Core.Memory; +using SharpEmu.GpuRemote; +using SharpEmu.GpuSplit; +using SharpEmu.HLE; +using SharpEmu.HLE.GpuMemory; +using SharpEmu.HLE.GuestMemory; +using SharpEmu.HLE.Host; +using SharpEmu.Host.MacOS; + +namespace SharpEmu.PerfAudit; + +/// +/// Managed guest-memory accesses from many threads at once, each thread in its own 64 KiB of a real +/// PhysicalVirtualMemory backing, so only the shared bookkeeping (alias pins, write intervals) is shared. +/// ns/op is window x threads / ops (thread time per op); min/max are per thread. Select with contend; +/// --qos=ui starts the workers at user-interactive QoS, --only=a,b limits the rows. +/// +internal static unsafe class ContentionBenches +{ + private const ulong GuestBase = 0x2_0000_0000; + private const ulong ThreadStride = 0x1_0000; + public static int[] ThreadCounts = [1, 2, 4, 10, 12]; + public static double WindowMs = 200; + public static int Windows = 5; + public static bool UserInteractive; + public static string[]? Only; + + private sealed record Row(string Id, string Name, Dictionary ByThreads); + private static readonly List Rows = []; + + // A body returns the refusals (false results) of one operation: 0 or 1. + private delegate int Op(long iteration); + + [ThreadStatic] private static long _threadLocal; + + public static void Run(string[] args) + { + foreach (var a in args) + { + if (a == "--qos=ui") UserInteractive = true; + if (a.StartsWith("--only=", StringComparison.Ordinal)) Only = a[7..].Split(','); + if (a.StartsWith("--window=", StringComparison.Ordinal)) WindowMs = double.Parse(a[9..], CultureInfo.InvariantCulture); + if (a.StartsWith("--threads=", StringComparison.Ordinal)) ThreadCounts = a[10..].Split(',').Select(int.Parse).ToArray(); + } + + Console.WriteLine($"--- contend: managed guest-memory access contention (qos={(UserInteractive ? "user-interactive" : "default")}, " + + $"window {WindowMs} ms x {Windows}, threads {string.Join('/', ThreadCounts)}) ---"); + HostMemoryAuthority.Initialize(MacOSHost.CreateMemory); + var views = MacOSHost.CreateViewMemory(); + using var pvm = new PhysicalVirtualMemory(viewHost: views, backingBytes: 32UL * 1024 * 1024); + const ulong Region = 8UL << 20; + var hole = (Region + views.Granularity - 1) / views.Granularity * views.Granularity; + if (!pvm.TryHoldRangeAtOrAbove(GuestBase, hole, views.Granularity, out var address) || + !pvm.TryMapBacked(address, Region, 0, GuestPageProtection.Read | GuestPageProtection.Write, out _)) + { + throw new InvalidOperationException("PVM map failed"); + } + + using var channel = GpuRemoteChannel.Create(SharedMemoryRegion.CreateUniqueName("contend"), SplitSharedState.Layout); + var state = new SplitSharedState(channel); + state.SetPage(address + 0x40_0000); + // PageGuard needs 4 KiB host pages: under native arm64 (16 KiB) the rows run without the GPU hooks. + using var gpuMemory = Environment.SystemPageSize == 4096 ? new GuestGpuMemory(pvm) : null; + if (gpuMemory is not null) + { + gpuMemory.Register(address, Region, GuestPageProtection.Read | GuestPageProtection.Write); + gpuMemory.AttachStores(null, new AgcBuilderBenches.FilterStore(state)); + GuestGpuMemoryHook.Attach(gpuMemory); + } + + Console.WriteLine($"GPU write hooks attached={gpuMemory is not null} (host page {Environment.SystemPageSize})"); + var memory = new TrackedCpuMemory(pvm); + + // The shared-backing objects behind the PVM, for the direct rows and the ledger A/B. + const BindingFlags Any = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public; + var owner = typeof(PhysicalVirtualMemory).GetField("_backedSpace", Any)!.GetValue(pvm)!; + var sbv = (SharedBackingViews)owner.GetType().GetField("_views", Any)!.GetValue(owner)!; + var backing = (HostBackingObject)typeof(SharedBackingViews).GetField("_backing", Any)!.GetValue(sbv)!; + var managedWritesField = typeof(HostBackingObject).GetField("_managedWrites", Any) + ?? throw new MissingFieldException("HostBackingObject._managedWrites"); + var ledger = managedWritesField.GetValue(backing); + Console.WriteLine($"ledger enrolled={ledger is not null}"); + + // A private (not backed) PVM region for p7. + var privateBase = pvm.AllocateAt(GuestBase + 0x4000_0000, 16 * ThreadStride, executable: false); + + ulong Base(int thread) => address + 0x10_0000 + (ulong)thread * ThreadStride; + var resetState = new byte[0x38]; + for (var t = 0; t < 16; t++) + { + BitConverter.TryWriteBytes(resetState.AsSpan(0x10), Base(t) + 0x1000); + memory.TryWrite(Base(t) + 0x800, resetState); + } + + // ---- PVM paths (TrackedCpuMemory over PhysicalVirtualMemory, hooks attached) + void Memory(string suffix, string label) + { + Contend("r8" + suffix, "TryRead 8 B" + label, t => + { + var b = Base(t); var buf = new byte[8]; + return i => memory.TryRead(b + (ulong)((i & 255) << 3), buf) ? 0 : 1; + }); + Contend("r36" + suffix, "TryRead 0x24 B (command-buffer state)" + label, t => + { + var b = Base(t) + 0x810; var buf = new byte[0x24]; + return i => memory.TryRead(b, buf) ? 0 : 1; + }); + Contend("w8" + suffix, "TryWrite 8 B" + label, t => + { + var b = Base(t); var buf = new byte[8]; + return i => memory.TryWrite(b + (ulong)((i & 255) << 3), buf) ? 0 : 1; + }); + Contend("pair" + suffix, "TryWritePair 8 B cursor + 32 B packet" + label, t => + { + var b = Base(t); var eight = new byte[8]; var packet = new byte[32]; + return i => memory.TryWritePair(b + 0x820, eight, b + 0x1000 + (ulong)((i & 127) << 5), packet) ? 0 : 1; + }); + Contend("emit" + suffix, "emit: r36 + pair" + label, t => + { + var b = Base(t); var eight = new byte[8]; var packet = new byte[32]; var cbState = new byte[0x24]; + return i => + { + var refused = memory.TryRead(b + 0x810, cbState) ? 0 : 1; + return refused | (memory.TryWritePair(b + 0x820, eight, b + 0x1000 + (ulong)((i & 127) << 5), packet) ? 0 : 1); + }; + }); + + // ---- SharedBackingViews directly (no hooks); a false return counts as a refusal. + Contend("d-r8" + suffix, "SharedBackingViews.TryReadSingleView 8 B" + label, t => + { + var b = Base(t); var buf = new byte[8]; + return i => sbv.TryReadSingleView(b + (ulong)((i & 255) << 3), buf) ? 0 : 1; + }); + Contend("d-w8" + suffix, "SharedBackingViews.TryWriteSingleView 8 B" + label, t => + { + var b = Base(t); var buf = new byte[8]; + return i => sbv.TryWriteSingleView(b + (ulong)((i & 255) << 3), buf) ? 0 : 1; + }); + Contend("d-pair" + suffix, "SharedBackingViews.TryWritePairSingleView 8 + 32 B" + label, t => + { + var b = Base(t); var eight = new byte[8]; var packet = new byte[32]; + return i => sbv.TryWritePairSingleView(b + 0x820, eight, b + 0x1000 + (ulong)((i & 127) << 5), packet) ? 0 : 1; + }); + } + + Memory("", ""); + ReportLedger(ledger, "ledger enrolled"); + if (ledger is not null) + { + managedWritesField.SetValue(backing, null); + try { Memory("-nl", " [_managedWrites null]"); } + finally { managedWritesField.SetValue(backing, ledger); } + } + + // ---- primitives + var shared = new long[32]; + var padded = new long[32 * 32]; // 256-byte stride per thread + Contend("p1", "Interlocked.Increment, one shared long", t => i => { Interlocked.Increment(ref shared[16]); return 0; }); + Contend("p2", "Interlocked.Increment, private 256-byte-padded slot", t => + { + var slot = 32 * (t + 1); + return i => { Interlocked.Increment(ref padded[slot]); return 0; }; + }); + Contend("p3", "[ThreadStatic] read-modify-write", t => i => { _threadLocal++; return 0; }); + Contend("p4", "Environment.CurrentManagedThreadId", t => i => Environment.CurrentManagedThreadId == -1 ? 1 : 0); + Contend("p5", "Interlocked.MemoryBarrier", t => i => { Interlocked.MemoryBarrier(); return 0; }); + var rwls = new ReaderWriterLockSlim(LockRecursionPolicy.NoRecursion); + Contend("p6", "ReaderWriterLockSlim read enter/exit, shared", t => i => { rwls.EnterReadLock(); rwls.ExitReadLock(); return 0; }); + Contend("p7", "PVM.TryRead 8 B, private (not backed) region", t => + { + var b = privateBase + (ulong)t * ThreadStride; var buf = new byte[8]; + return i => pvm.TryRead(b + (ulong)((i & 255) << 3), buf) ? 0 : 1; + }); + GuestGpuMemoryHook.Attach(null); + Console.WriteLine(); + Console.WriteLine(Table()); + } + + private static void ReportLedger(object? ledger, string label) + { + if (ledger is null) return; + const BindingFlags Any = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public; + var type = ledger.GetType(); + var losses = type.GetProperty("HistoryRecordLosses", Any)?.GetValue(ledger); + var coverage = type.GetProperty("FirstCoverageLoss", Any)?.GetValue(ledger); + Console.WriteLine($"{label}: HistoryRecordLosses={losses} FirstCoverageLoss={coverage}"); + } + + private static void Contend(string id, string name, Func factory) + { + if (Only is not null && !Only.Contains(id)) return; + // Single-threaded warmup so the op reaches tier 1 before any window. + var warm = factory(0); + var watch = Stopwatch.StartNew(); + for (long i = 0; watch.Elapsed.TotalMilliseconds < Harness.WarmupMs; i++) warm(i); + + var row = new Row(id, name, []); + foreach (var threads in ThreadCounts) + { + row.ByThreads[threads] = Measure(threads, factory); + var r = row.ByThreads[threads]; + Console.WriteLine(string.Create(CultureInfo.InvariantCulture, + $"{id,-10} T={threads,-2} {r.Ns,9:F1} ns/op per-thread {r.Min,9:F1}..{r.Max,9:F1} refusals {r.Refusals} {name}")); + } + + Rows.Add(row); + } + + private static (double Ns, double Min, double Max, long Refusals) Measure(int threads, Func factory) + { + var stop = 0; + var barrier = new Barrier(threads + 1); + var elapsed = new double[threads]; + var ops = new long[threads]; + var refusals = new long[threads]; + var results = new List<(double Ns, double Min, double Max, long Refusals)>(); + var bodies = Enumerable.Range(0, threads).Select(factory).ToArray(); + + void Worker(int t) + { + var op = bodies[t]; + long iteration = 0; + for (var window = 0; window <= Windows; window++) + { + barrier.SignalAndWait(); + long count = 0, refused = 0; + var start = Stopwatch.GetTimestamp(); + while (Volatile.Read(ref stop) == 0) + { + for (var k = 0; k < 32; k++) refused += op(iteration++); + count += 32; + } + + elapsed[t] = Stopwatch.GetElapsedTime(start).TotalNanoseconds; + ops[t] = count; + refusals[t] = refused; + barrier.SignalAndWait(); + } + } + + var started = new List(); + var native = new List(); + for (var t = 0; t < threads; t++) + { + var index = t; + if (UserInteractive) + { + var thread = HostQosThread.TryStart($"contend-{index}", HostThreadQos.UserInteractive, 1 << 20, () => Worker(index), out var errno) + ?? throw new InvalidOperationException($"QoS thread start failed: errno {errno}"); + native.Add(thread); + } + else + { + var thread = new Thread(() => Worker(index), 1 << 20) { IsBackground = true, Name = $"contend-{index}" }; + thread.Start(); + started.Add(thread); + } + } + + for (var window = 0; window <= Windows; window++) + { + Volatile.Write(ref stop, 0); + barrier.SignalAndWait(); + Thread.Sleep(TimeSpan.FromMilliseconds(WindowMs)); + Volatile.Write(ref stop, 1); + barrier.SignalAndWait(); + if (window == 0) continue; // warm window + var perThread = Enumerable.Range(0, threads).Select(t => elapsed[t] / Math.Max(ops[t], 1)).ToArray(); + results.Add((elapsed.Sum() / Math.Max(ops.Sum(), 1), perThread.Min(), perThread.Max(), refusals.Sum())); + } + + foreach (var thread in started) thread.Join(); + foreach (var thread in native) thread.Join(10_000); + var sorted = results.OrderBy(r => r.Ns).ToArray(); + var median = sorted[sorted.Length / 2]; + return median with { Refusals = results.Sum(r => r.Refusals) }; + } + + private static string Table() + { + var sb = new StringBuilder(); + sb.Append(CultureInfo.InvariantCulture, $"contend arch={RuntimeInformation.ProcessArchitecture} qos={(UserInteractive ? "ui" : "default")} (ns/op, thread time per op; T=10 per-thread min..max; refusals over all windows)\n"); + sb.Append("| id | ").Append(string.Join(" | ", ThreadCounts.Select(t => $"T={t}"))).Append(" | T10/T1 | T=10 min..max | refusals | what |\n"); + sb.Append("|---|").Append(string.Concat(ThreadCounts.Select(_ => "---:|"))).Append("---:|---|---:|---|\n"); + foreach (var row in Rows) + { + sb.Append(CultureInfo.InvariantCulture, $"| {row.Id} | "); + sb.Append(string.Join(" | ", ThreadCounts.Select(t => row.ByThreads[t].Ns.ToString("F1", CultureInfo.InvariantCulture)))); + var ratio = row.ByThreads.TryGetValue(10, out var ten) && row.ByThreads.TryGetValue(1, out var one) ? ten.Ns / one.Ns : double.NaN; + var spread = row.ByThreads.TryGetValue(10, out ten) ? $"{ten.Min:F0}..{ten.Max:F0}" : "-"; + sb.Append(CultureInfo.InvariantCulture, $" | {ratio:F1}x | {spread} | {row.ByThreads.Values.Sum(v => v.Refusals)} | {row.Name} |\n"); + } + + return sb.ToString(); + } +} diff --git a/tools/SharpEmu.Tools.PerfAudit/Program.cs b/tools/SharpEmu.Tools.PerfAudit/Program.cs index e1800313a..ea6b2d256 100644 --- a/tools/SharpEmu.Tools.PerfAudit/Program.cs +++ b/tools/SharpEmu.Tools.PerfAudit/Program.cs @@ -28,6 +28,7 @@ if (On("w8")) W8Benches.Run(); if (filter.Split(',').Contains("xlate")) TranslatorBenches.Run(); if (filter.Split(',').Contains("agc")) AgcBuilderBenches.Run(); +if (filter.Split(',').Contains("contend")) ContentionBenches.Run(args); if (filter.Split(',').Contains("gword")) MetalRawBenches.GpuWordWait(); if (filter.Split(',').Contains("wranges")) WriteRangeBenches.Run(); if (filter.Split(',').Contains("labels")) LabelFilterBenches.Run(); From f7712793af48e705e21f9350ef582c96d02b2b88 Mon Sep 17 00:00:00 2001 From: kuba Date: Sun, 15 Nov 2026 03:07:54 +0000 Subject: [PATCH 015/178] [HLE] HostAccessStripes: in-flight counts on per-thread cache-line stripes A long[] with a 256-byte stride per stripe (a power of two of at least twice the processor count, at most 64), indexed by the managed thread id, two lanes per stripe on the stripe's own line. Entrants increment their stripe (a full fence) and re-check the drainer's flag; drainers set the flag with a full fence and sum the stripes. The sum is signed, so an exit on another thread still balances; a negative sum is fatal. No user yet. --- src/SharpEmu.HLE/Host/HostAccessStripes.cs | 103 ++++++++++++++ .../GuestMemory/HostAccessStripesTests.cs | 129 ++++++++++++++++++ 2 files changed, 232 insertions(+) create mode 100644 src/SharpEmu.HLE/Host/HostAccessStripes.cs create mode 100644 tests/SharpEmu.Libs.Tests/Memory/GuestMemory/HostAccessStripesTests.cs diff --git a/src/SharpEmu.HLE/Host/HostAccessStripes.cs b/src/SharpEmu.HLE/Host/HostAccessStripes.cs new file mode 100644 index 000000000..aee6257c2 --- /dev/null +++ b/src/SharpEmu.HLE/Host/HostAccessStripes.cs @@ -0,0 +1,103 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +namespace SharpEmu.HLE.Host; + +/// +/// In-flight counts split over cache-line-padded stripes, so threads that enter and exit at the +/// same time each change their own line instead of one shared counter. A thread uses the stripe +/// its managed thread id selects. Each stripe has independent counts on the +/// same line (one per kind of access a drainer waits for). +/// +/// Protocol (Dekker, both sides fully fenced): an entrant increments its stripe (a full fence), +/// then re-reads the drainer's flag and backs out if it is set. A drainer sets its flag with a +/// full fence, then sums the stripes. Either the drainer sees the increment or the entrant sees +/// the flag. The sum is signed, so an exit on another thread than its enter still balances; +/// a negative sum means an exit without an enter and is fatal. +/// +internal sealed class HostAccessStripes +{ + internal const int Lanes = 2; + internal const int MaximumStripes = 64; + // 256 bytes per stripe: whatever the array's alignment, no 128-byte line holds two stripes, + // and one stripe-width of padding before the first and after the last keeps the array + // header and neighbouring heap objects off the stripes' lines. + private const int StrideLongs = 32; + + private readonly long[] _cells; + private readonly int _mask; + + // Default-null controlled fatal path; production fails fast on an unbalanced exit. + internal Action? OnFatalForControl; + + internal HostAccessStripes() : this(DefaultStripeCount(Environment.ProcessorCount)) + { + } + + internal HostAccessStripes(int stripes) + { + if (stripes <= 0 || stripes > MaximumStripes || (stripes & (stripes - 1)) != 0) + throw new ArgumentOutOfRangeException(nameof(stripes)); + Count = stripes; + _mask = stripes - 1; + _cells = new long[(stripes + 2) * StrideLongs]; + } + + internal int Count { get; } + + /// A power of two of at least twice the processor count, at most . + internal static int DefaultStripeCount(int processors) + { + var wanted = Math.Clamp(processors, 1, MaximumStripes / 2) * 2; + var stripes = 1; + while (stripes < wanted) stripes <<= 1; + return Math.Min(stripes, MaximumStripes); + } + + /// The cell of the calling thread's stripe for . + internal int CellForCurrentThread(int lane) => CellOf(Environment.CurrentManagedThreadId & _mask, lane); + + internal int CellOf(int stripe, int lane) + { + if ((uint)stripe > (uint)_mask || (uint)lane >= Lanes) throw new ArgumentOutOfRangeException(nameof(stripe)); + return (stripe + 1) * StrideLongs + lane; + } + + /// Counts one entry on the calling thread's stripe (a full fence) and returns its cell. + internal int Enter(int lane) + { + var cell = CellForCurrentThread(lane); + Interlocked.Increment(ref _cells[cell]); + return cell; + } + + /// Counts one exit on the calling thread's stripe. + internal void Exit(int lane) => Interlocked.Decrement(ref _cells[CellForCurrentThread(lane)]); + + /// Counts one exit on a cell an returned. + internal void ExitCell(int cell) + { + if ((uint)cell >= (uint)_cells.Length || cell % StrideLongs >= Lanes || cell < StrideLongs) + throw new ArgumentOutOfRangeException(nameof(cell)); + Interlocked.Decrement(ref _cells[cell]); + } + + /// + /// The signed sum of one lane over every stripe. Callers set their flag with a full fence first. + /// A negative sum (an exit with no enter) is fatal. + /// + internal long Sum(int lane) + { + if ((uint)lane >= Lanes) throw new ArgumentOutOfRangeException(nameof(lane)); + long sum = 0; + for (var stripe = 0; stripe < Count; stripe++) sum += Volatile.Read(ref _cells[(stripe + 1) * StrideLongs + lane]); + if (sum < 0) + { + var message = $"Unbalanced access exit: stripe lane {lane} sums to {sum}."; + if (OnFatalForControl is { } fatal) fatal(message); + else Environment.FailFast(message); + } + + return sum; + } +} diff --git a/tests/SharpEmu.Libs.Tests/Memory/GuestMemory/HostAccessStripesTests.cs b/tests/SharpEmu.Libs.Tests/Memory/GuestMemory/HostAccessStripesTests.cs new file mode 100644 index 000000000..7c387a00d --- /dev/null +++ b/tests/SharpEmu.Libs.Tests/Memory/GuestMemory/HostAccessStripesTests.cs @@ -0,0 +1,129 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using System.Reflection; +using SharpEmu.HLE.Host; +using Xunit; + +namespace SharpEmu.Libs.Tests.Memory.GuestMemory; + +public sealed class HostAccessStripesTests +{ + [Theory] + [InlineData(1, 2)] + [InlineData(3, 8)] + [InlineData(10, 32)] + [InlineData(32, 64)] + [InlineData(40, 64)] + [InlineData(1000, 64)] + public void StripeCountIsAPowerOfTwoOfAtLeastTwiceTheProcessorsCappedAt64(int processors, int expected) + { + Assert.Equal(expected, HostAccessStripes.DefaultStripeCount(processors)); + } + + [Theory] + [InlineData(0)] + [InlineData(3)] + [InlineData(128)] + public void InvalidStripeCountsAreRefused(int stripes) + { + Assert.Throws(() => new HostAccessStripes(stripes)); + } + + [Fact] + public void NoTwoStripesNorTheArrayEdgesShareA128ByteLine() + { + var stripes = new HostAccessStripes(64); + var cells = (long[])typeof(HostAccessStripes).GetField("_cells", BindingFlags.Instance | BindingFlags.NonPublic)!.GetValue(stripes)!; + var previous = -1; + for (var stripe = 0; stripe < stripes.Count; stripe++) + { + for (var lane = 0; lane < HostAccessStripes.Lanes; lane++) + { + var cell = stripes.CellOf(stripe, lane); + // Whatever the array's alignment, 256 bytes from the array start (its header sits + // before element 0) and from the array end keep foreign data off the line. + Assert.True(cell * sizeof(long) >= 256, $"stripe {stripe} lane {lane} is within 256 bytes of the array start"); + Assert.True((cells.Length - cell) * sizeof(long) >= 256, $"stripe {stripe} lane {lane} is within 256 bytes of the array end"); + } + + var first = stripes.CellOf(stripe, 0); + if (previous >= 0) Assert.True((first - previous) * sizeof(long) >= 256); + previous = first; + // The lanes of one stripe share its line on purpose. + Assert.Equal(first + 1, stripes.CellOf(stripe, 1)); + } + } + + [Fact] + public void ConcurrentThreadsCountOnTheirOwnStripes() + { + var stripes = new HostAccessStripes(64); + using var entered = new CountdownEvent(8); + using var release = new ManualResetEventSlim(); + var cells = new int[8]; + var ids = new int[8]; + var threads = Enumerable.Range(0, 8).Select(index => new Thread(() => + { + ids[index] = Environment.CurrentManagedThreadId; + cells[index] = stripes.Enter(0); + entered.Signal(); + release.Wait(); + stripes.Exit(0); + })).ToArray(); + foreach (var thread in threads) thread.Start(); + Assert.True(entered.Wait(TimeSpan.FromSeconds(10))); + Assert.Equal(8, stripes.Sum(0)); + Assert.Equal(0, stripes.Sum(1)); + // Each thread counts on the stripe its managed thread id selects, one 256-byte stride per stripe. + for (var index = 0; index < cells.Length; index++) Assert.Equal(stripes.CellOf(ids[index] & 63, 0), cells[index]); + release.Set(); + foreach (var thread in threads) Assert.True(thread.Join(TimeSpan.FromSeconds(10))); + Assert.Equal(0, stripes.Sum(0)); + } + + [Fact] + public void AnExitOnAnotherThreadStillBalancesTheSignedSum() + { + var stripes = new HostAccessStripes(64); + var enteredCell = stripes.Enter(0); + var exitCell = -1; + var other = new Thread(() => + { + exitCell = stripes.CellForCurrentThread(0); + stripes.Exit(0); + }); + other.Start(); + Assert.True(other.Join(TimeSpan.FromSeconds(10))); + Assert.NotEqual(enteredCell, exitCell); + Assert.Equal(0, stripes.Sum(0)); + stripes.Enter(0); + Assert.Equal(1, stripes.Sum(0)); + stripes.Exit(0); + Assert.Equal(0, stripes.Sum(0)); + } + + [Fact] + public void ANegativeSumIsFatal() + { + var stripes = new HostAccessStripes(4); + string? fatal = null; + stripes.OnFatalForControl = message => { fatal = message; throw new InvalidOperationException(message); }; + stripes.Exit(1); + Assert.Equal(0, stripes.Sum(0)); + var error = Assert.Throws(() => stripes.Sum(1)); + Assert.Contains("Unbalanced access exit", error.Message); + Assert.NotNull(fatal); + } + + [Fact] + public void ExitCellRefusesACellNoEnterReturns() + { + var stripes = new HostAccessStripes(4); + Assert.Throws(() => stripes.ExitCell(0)); + Assert.Throws(() => stripes.ExitCell(stripes.CellOf(0, 0) + HostAccessStripes.Lanes)); + Assert.Throws(() => stripes.ExitCell(int.MaxValue)); + Assert.Throws(() => stripes.CellOf(4, 0)); + Assert.Throws(() => stripes.CellOf(0, HostAccessStripes.Lanes)); + } +} From 99478e004b9a5edbdc64258187ea196d4aae4e59 Mon Sep 17 00:00:00 2001 From: kuba Date: Sun, 15 Nov 2026 03:07:54 +0000 Subject: [PATCH 016/178] [HLE] Count alias accesses on the backing's per-thread stripes HostBackingObject.TryEnterAliasAccess/ExitAliasAccess: the closing check, a stripe increment, then the closing re-check (the same Dekker with Close as TryEnterAccess's increment). ActiveAccesses, and so TryDisposeCore's drain, now include the alias stripes; a negative stripe sum at the drain is fatal. SHARPEMU_ACCESS_STRIPES=0 sends alias accesses through TryEnterAccess again. No caller yet; SharedBackingViews follows. --- src/SharpEmu.HLE/Host/HostBackingObject.cs | 36 +++++- .../HostBackingAliasStripesTests.cs | 115 ++++++++++++++++++ 2 files changed, 150 insertions(+), 1 deletion(-) create mode 100644 tests/SharpEmu.Libs.Tests/Memory/GuestMemory/HostBackingAliasStripesTests.cs diff --git a/src/SharpEmu.HLE/Host/HostBackingObject.cs b/src/SharpEmu.HLE/Host/HostBackingObject.cs index 72471d898..89d4c627f 100644 --- a/src/SharpEmu.HLE/Host/HostBackingObject.cs +++ b/src/SharpEmu.HLE/Host/HostBackingObject.cs @@ -15,6 +15,14 @@ public sealed class HostBackingObject : IDisposable private HostBackingReleaseResult _lastRelease; private bool _isDisposed; private HostManagedWriteIntervals? _managedWrites; + // Alias accesses (SharedBackingViews' lock-free single-view reads and writes) count here, + // each thread on its own cache line, instead of on _accessState, which every thread shares. + // Null with SHARPEMU_ACCESS_STRIPES=0: alias accesses then take TryEnterAccess. + private readonly HostAccessStripes? _aliasStripes = AccessStripesEnabled ? new HostAccessStripes() : null; + internal const int AliasLane = 0; + internal static readonly bool AccessStripesEnabled = + Environment.GetEnvironmentVariable("SHARPEMU_ACCESS_STRIPES") != "0"; + internal HostAccessStripes? AliasStripes => _aliasStripes; // Optional ordinary bookkeeping only. No wait or callback during enrollment; // a concurrent first copy may allocate a discarded candidate, while warmed @@ -154,7 +162,9 @@ public HostBackingObject(ulong aliasBase, ulong size, ulong nativePageSize, public bool HasOwnedLifetime => _ownedRelease is not null; public bool IsClosing => HasOwnedLifetime && (Volatile.Read(ref _accessState) & ClosingBit) != 0; /// Count observation including briefly rejected entry bookkeeping; not native access authority. - public int ActiveAccesses => HasOwnedLifetime ? (int)Volatile.Read(ref _accessState) : 0; + public int ActiveAccesses => HasOwnedLifetime ? (int)Volatile.Read(ref _accessState) + (int)AliasAccesses : 0; + // Signed sum of the alias stripes; fatal when negative (an exit without an enter). + private long AliasAccesses => _aliasStripes?.Sum(AliasLane) ?? 0; public HostBackingReleaseResult LastRelease { get { lock (Gate) return _lastRelease; } } /// @@ -192,6 +202,30 @@ public void ExitAccess() } } + /// + /// for an alias access, counted on the calling thread's stripe. + /// Same admission against : the stripe increment is a full fence + /// before the closing re-check, and the drain sets the closing bit with a full fence before + /// it sums the stripes, so either the entrant sees Close or the drain sees the entrant. + /// Every success must exactly once, after the final access. + /// + internal bool TryEnterAliasAccess() + { + if (_aliasStripes is not { } stripes) return TryEnterAccess(); + // A legacy (not owned) lifetime has no drain here; its stripes count for the views' drains. + if (HasOwnedLifetime ? !CanStartAccessEntry() : IsDisposed) return false; + var cell = stripes.Enter(AliasLane); + if (HasOwnedLifetime ? CanStartAccessEntry() : !IsDisposed) return true; + stripes.ExitCell(cell); + return false; + } + + internal void ExitAliasAccess() + { + if (_aliasStripes is not { } stripes) { ExitAccess(); return; } + stripes.Exit(AliasLane); + } + /// Revokes new ordinary alias/descriptor accesses; never reopens admission. public void CloseAccess() { if (HasOwnedLifetime) Interlocked.Or(ref _accessState, ClosingBit); } diff --git a/tests/SharpEmu.Libs.Tests/Memory/GuestMemory/HostBackingAliasStripesTests.cs b/tests/SharpEmu.Libs.Tests/Memory/GuestMemory/HostBackingAliasStripesTests.cs new file mode 100644 index 000000000..71230956b --- /dev/null +++ b/tests/SharpEmu.Libs.Tests/Memory/GuestMemory/HostBackingAliasStripesTests.cs @@ -0,0 +1,115 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using SharpEmu.HLE.Host; +using Xunit; + +namespace SharpEmu.Libs.Tests.Memory.GuestMemory; + +// Alias accesses counted on HostBackingObject's per-thread stripes instead of its shared access +// count: Close still refuses new ones and the drain still waits for every admitted one. +// Phantom backings: nothing reads or writes the (fake) alias address. +public sealed class HostBackingAliasStripesTests +{ + private static HostBackingObject Phantom(Func release) + => new(0x10000, 4096, 4096, release); + + [Fact] + public void AHeldAliasAccessBlocksDisposeAndCloseRefusesNewOnes() + { + if (!HostBackingObject.AccessStripesEnabled) return; + var calls = 0; + var backing = Phantom(_ => { calls++; return new(HostBackingReleaseStatus.Released); }); + Assert.NotNull(backing.AliasStripes); + Assert.True(backing.TryEnterAliasAccess()); + Assert.Equal(1, backing.ActiveAccesses); + Assert.False(backing.TryDispose(TimeSpan.Zero, out var timedOut)); + Assert.Equal(HostBackingReleaseStatus.TimedOut, timedOut.Status); + Assert.True(backing.IsClosing); Assert.Equal(0, calls); + Assert.False(backing.TryEnterAliasAccess()); + Assert.False(backing.TryEnterAccess()); + Assert.Equal(1, backing.ActiveAccesses); + backing.ExitAliasAccess(); + Assert.Equal(0, backing.ActiveAccesses); + Assert.True(backing.TryDispose(TimeSpan.Zero, out _)); + Assert.Equal(1, calls); Assert.True(backing.IsDisposed); + Assert.False(backing.TryEnterAliasAccess()); + } + + [Fact] + public void AliasAndOrdinaryAccessesBothHoldTheDrain() + { + if (!HostBackingObject.AccessStripesEnabled) return; + var calls = 0; + var backing = Phantom(_ => { calls++; return new(HostBackingReleaseStatus.Released); }); + Assert.True(backing.TryEnterAccess()); + Assert.True(backing.TryEnterAliasAccess()); + Assert.Equal(2, backing.ActiveAccesses); + backing.ExitAccess(); + Assert.False(backing.TryDispose(TimeSpan.Zero, out _)); + backing.ExitAliasAccess(); + Assert.True(backing.TryDispose(TimeSpan.Zero, out _)); + Assert.Equal(1, calls); + } + + [Fact] + public void AnAliasExitWithoutAnEnterIsFatalAtTheDrain() + { + if (!HostBackingObject.AccessStripesEnabled) return; + var calls = 0; + var backing = Phantom(_ => { calls++; return new(HostBackingReleaseStatus.Released); }); + backing.AliasStripes!.OnFatalForControl = message => throw new InvalidOperationException(message); + backing.ExitAliasAccess(); + var error = Assert.Throws(() => backing.TryDispose(TimeSpan.FromSeconds(1), out _)); + Assert.Contains("Unbalanced access exit", error.Message); + Assert.Equal(0, calls); Assert.False(backing.IsDisposed); + } + + // Ten threads enter and exit alias accesses while one disposes. No access may be in flight when + // the release runs, and none may be admitted once it has started. + [Fact] + public void DisposeNeverReleasesUnderAnAdmittedAliasAccess() + { + if (!HostBackingObject.AccessStripesEnabled) return; + for (var round = 0; round < 20; round++) + { + var inFlight = 0; + var released = 0; + var violations = 0; + var admitted = 0L; + var stop = 0; + var backing = Phantom(_ => + { + Volatile.Write(ref released, 1); + Interlocked.MemoryBarrier(); + if (Volatile.Read(ref inFlight) != 0) Interlocked.Increment(ref violations); + return new(HostBackingReleaseStatus.Released); + }); + using var started = new CountdownEvent(10); + var workers = Enumerable.Range(0, 10).Select(_ => new Thread(() => + { + started.Signal(); + while (Volatile.Read(ref stop) == 0) + { + if (!backing.TryEnterAliasAccess()) continue; + Interlocked.Increment(ref inFlight); + if (Volatile.Read(ref released) != 0) Interlocked.Increment(ref violations); + Interlocked.Increment(ref admitted); + Thread.SpinWait(20); + Interlocked.Decrement(ref inFlight); + backing.ExitAliasAccess(); + } + }) { IsBackground = true }).ToArray(); + foreach (var worker in workers) worker.Start(); + Assert.True(started.Wait(TimeSpan.FromSeconds(10))); + Thread.Sleep(5); + Assert.True(backing.TryDispose(TimeSpan.FromSeconds(10), out var result), result.Status.ToString()); + Thread.Sleep(2); + Volatile.Write(ref stop, 1); + foreach (var worker in workers) Assert.True(worker.Join(TimeSpan.FromSeconds(10))); + Assert.Equal(0, violations); + Assert.True(admitted > 0); + Assert.Equal(0, backing.ActiveAccesses); + } + } +} From 91717bb9f250042f1af0679e08872618c78ffe9c Mon Sep 17 00:00:00 2001 From: kuba Date: Sun, 15 Nov 2026 03:07:54 +0000 Subject: [PATCH 017/178] [HLE] SharedBackingViews: lock-free single-view accesses pin only their stripe An alias access (every lock-free single-view read and write) took two shared atomics on the way in and two on the way out: SharedBackingViews._activeAccesses and the backing's _accessState. It now increments the calling thread's stripe once and re-reads every drainer's flag after it (copy reservation, Dispose, the backing's Close). The copy reservation and Dispose sum the stripes (Dispose now fences its flags before it does); the backing's drain already includes them. SHARPEMU_ACCESS_STRIPES=0 restores the two shared counts. Tests: a copy reservation waits for a writer paused before its bytes; ten writers never tear a 256-byte record a reservation holds (both fail when the drains ignore the stripes); readers racing Dispose; single-view accesses while another range is remapped. --- .../SharedBackingViews.Transfers.cs | 2 +- .../GuestMemory/SharedBackingViews.cs | 37 ++- .../SharedBackingAliasStripesTests.cs | 278 ++++++++++++++++++ 3 files changed, 313 insertions(+), 4 deletions(-) create mode 100644 tests/SharpEmu.Libs.Tests/Memory/GuestMemory/SharedBackingAliasStripesTests.cs diff --git a/src/SharpEmu.HLE/GuestMemory/SharedBackingViews.Transfers.cs b/src/SharpEmu.HLE/GuestMemory/SharedBackingViews.Transfers.cs index f86fa708e..4aad57357 100644 --- a/src/SharpEmu.HLE/GuestMemory/SharedBackingViews.Transfers.cs +++ b/src/SharpEmu.HLE/GuestMemory/SharedBackingViews.Transfers.cs @@ -60,7 +60,7 @@ internal bool TryReserveCopy(ulong destination, ulong source, ulong size, out Co // a lifetime-pinned receipt retrying through one) free to make progress meanwhile; // those see the reservation already and wait only if they overlap it. var spin = new SpinWait(); - while (Volatile.Read(ref _activeAccesses) != 0) spin.SpinOnce(); + while (ActiveAliasAccesses() != 0) spin.SpinOnce(); lease = new CopyLease(this, index, AliasBase + sourceOffset, AliasBase + destinationOffset); return true; } diff --git a/src/SharpEmu.HLE/GuestMemory/SharedBackingViews.cs b/src/SharpEmu.HLE/GuestMemory/SharedBackingViews.cs index 8ea3e9906..f7492eb62 100644 --- a/src/SharpEmu.HLE/GuestMemory/SharedBackingViews.cs +++ b/src/SharpEmu.HLE/GuestMemory/SharedBackingViews.cs @@ -54,8 +54,11 @@ public sealed unsafe partial class SharedBackingViews : IDisposable, ICpuMappedC // in shared memory, for a process that replicates the views. Changed under _lock (SetViewLocked/RemoveViewAtLocked). private readonly GuestViewTable? _viewTable; - // Single-view accesses in flight; Dispose waits for them before releasing the alias. + // Single-view (alias) accesses in flight; Dispose waits for them before releasing the alias. // A copy reservation also waits for these: they touch the alias without checking it. + // They count on the backing's per-thread stripes (HostBackingObject.AliasStripes), which + // also stand in for the backing's own access count; this scalar counts them only with + // SHARPEMU_ACCESS_STRIPES=0, where each also takes the backing's shared access count. private int _activeAccesses; // Lifetime pins that never touch bytes outside the locked, reservation-checked paths // (those paths, ordinary-write receipts, unlocked copies). Dispose waits for them too; @@ -1471,8 +1474,10 @@ public void Dispose() throw new InvalidOperationException("Backing view cleanup is quarantined.", _cleanupFailure); views = new List(_views.Values); } + // The flags above before the counts below: an entrant increments, then re-reads them. + Interlocked.MemoryBarrier(); var start = System.Diagnostics.Stopwatch.GetTimestamp(); - while (Volatile.Read(ref _activeAccesses) != 0 || Volatile.Read(ref _lifetimeAccesses) != 0) + while (ActiveAliasAccesses() != 0 || Volatile.Read(ref _lifetimeAccesses) != 0) { if (System.Diagnostics.Stopwatch.GetElapsedTime(start) >= TimeSpan.FromSeconds(2)) throw new TimeoutException("Backing alias accesses did not drain; storage remains owned."); @@ -1617,7 +1622,7 @@ private void PublishSnapshot() } // Resolves an access that lies inside one view to its alias address and registers - // it as in flight; the caller must decrement _activeAccesses when done. Anything + // it as in flight; the caller must ExitAliasAccess when done. Anything // else (spanning views, unmapped, disposed) is left to the locked path. private bool TryAccessSingleView(ulong address, ulong size, out ulong target) { @@ -1637,9 +1642,24 @@ private bool TryAccessSingleView(ulong address, ulong size, out ulong target) // An alias access touches backing bytes without checking copy reservations, so it is // refused while an unlocked copy is reserved, and a reservation waits for admitted ones. + // + // With stripes, one increment of the calling thread's stripe (a full fence) registers the + // access for every drainer, and every flag is re-read after it: the copy reservation + // (_copyAccessBlocked, set by Interlocked.Exchange before it sums), Dispose (_disposeRequested + // and _disposed, set before it sums) and the backing's Close (re-checked inside + // HostBackingObject.TryEnterAliasAccess). Either the drainer sees the stripe or the entrant + // sees the flag and backs out. public bool TryEnterAliasAccess() { if (Volatile.Read(ref _copyAccessBlocked) != 0) return false; + if (_backing?.AliasStripes is not null) + { + if (Volatile.Read(ref _disposed) || Volatile.Read(ref _disposeRequested) || !_backing.TryEnterAliasAccess()) return false; + if (Volatile.Read(ref _copyAccessBlocked) == 0 && !Volatile.Read(ref _disposed) && !Volatile.Read(ref _disposeRequested)) return true; + _backing.ExitAliasAccess(); + return false; + } + Interlocked.Increment(ref _activeAccesses); // Register before the gate check so a reservation waits for admitted access. if (Volatile.Read(ref _copyAccessBlocked) == 0 && TryEnterBackingAccess()) return true; @@ -1649,10 +1669,21 @@ public bool TryEnterAliasAccess() public void ExitAliasAccess() { + if (_backing?.AliasStripes is not null) + { + _backing.ExitAliasAccess(); + return; + } + _backing!.ExitAccess(); Interlocked.Decrement(ref _activeAccesses); } + // Alias accesses in flight, for the drainers (copy reservation, Dispose); they set their + // flag with a full fence first. A negative stripe sum is fatal (HostAccessStripes.Sum). + private long ActiveAliasAccesses() => + (_backing?.AliasStripes?.Sum(HostBackingObject.AliasLane) ?? 0) + Volatile.Read(ref _activeAccesses); + // Keeps the alias alive without admitting a lock-free byte access: the locked paths // (which wait for overlapping reservations first and never wait while pinned), receipts // and unlocked copies. Not refused by copy reservations, and not waited for by them. diff --git a/tests/SharpEmu.Libs.Tests/Memory/GuestMemory/SharedBackingAliasStripesTests.cs b/tests/SharpEmu.Libs.Tests/Memory/GuestMemory/SharedBackingAliasStripesTests.cs new file mode 100644 index 000000000..14e624ffd --- /dev/null +++ b/tests/SharpEmu.Libs.Tests/Memory/GuestMemory/SharedBackingAliasStripesTests.cs @@ -0,0 +1,278 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using System.Reflection; +using SharpEmu.HLE.GuestMemory; +using SharpEmu.HLE.Host; +using Xunit; +using static SharpEmu.Libs.Tests.Memory.HostViews.HostViewTestSupport; + +namespace SharpEmu.Libs.Tests.Memory.GuestMemory; + +// SharedBackingViews' lock-free single-view accesses counted on the backing's per-thread stripes: +// a copy reservation and Dispose still wait for every admitted access. +[Collection(GuestMemoryStateCollection.Name)] +public sealed unsafe class SharedBackingAliasStripesTests +{ + private const ulong Part = 256 * 1024; + private const int RecordBytes = 256; + + [Fact] + public void ACopyReservationWaitsForAWriterPausedBeforeItsBytes() + { + if (!Supported) return; + using var mapping = new Mappings(); + using var paused = new ManualResetEventSlim(); + using var resume = new ManualResetEventSlim(); + var writerId = -1; + SetCopyHook(mapping.Store, (_, _) => + { + if (Environment.CurrentManagedThreadId != Volatile.Read(ref writerId)) return; + paused.Set(); + Assert.True(resume.Wait(TimeSpan.FromSeconds(20))); + }); + var written = false; + var writer = new Thread(() => + { + Volatile.Write(ref writerId, Environment.CurrentManagedThreadId); + written = mapping.Store.TryWriteSingleView(mapping.Address + 0x100, BitConverter.GetBytes(Marker)); + }) { IsBackground = true }; + var reserved = new ManualResetEventSlim(); + var reservation = false; + Exception? failure = null; + var copier = new Thread(() => + { + try + { + // Disjoint from the paused write: only the alias pin makes it wait. + reservation = mapping.Store.TryReserveCopy(mapping.Address + 0x2_0000, mapping.Address + 0x1_0000, 64, out var lease); + reserved.Set(); + if (reservation) lease.Dispose(); + } + catch (Exception error) { failure = error; reserved.Set(); } + }) { IsBackground = true }; + try + { + writer.Start(); + Assert.True(paused.Wait(TimeSpan.FromSeconds(10))); + copier.Start(); + Assert.False(reserved.Wait(TimeSpan.FromMilliseconds(300))); + // The reservation closed lock-free access while it waits. + Assert.False(mapping.Store.TryReadSingleView(mapping.Address + 0x3_0000, new byte[8])); + } + finally + { + resume.Set(); + } + + Assert.True(writer.Join(TimeSpan.FromSeconds(10))); + Assert.True(copier.Join(TimeSpan.FromSeconds(10))); + Assert.Null(failure); + Assert.True(written); + Assert.True(reservation); + var bytes = new byte[8]; + Assert.True(mapping.Store.TryReadSingleView(mapping.Address + 0x100, bytes)); + Assert.Equal(Marker, BitConverter.ToUInt64(bytes)); + } + + // Ten writers rewrite whole records (every word the same generation) in a copy's source and + // destination while another thread copies the source over the destination under a reservation. + // A record with mixed generations means a write landed while the copy ran. + [Fact] + public void WritersNeverTearARecordACopyReservationHolds() + { + if (!Supported) return; + using var mapping = new Mappings(); + const int Writers = 10; + const int CopyBytes = 64 * 1024; + var source = mapping.Address; + var destination = mapping.Address + Part; + var stop = 0; + var failures = 0; + var writes = 0L; + using var started = new CountdownEvent(Writers); + var writers = Enumerable.Range(0, Writers).Select(index => new Thread(() => + { + var record = new byte[RecordBytes]; + started.Signal(); + for (var generation = 1UL; Volatile.Read(ref stop) == 0; generation++) + { + for (var word = 0; word < RecordBytes; word += 8) BitConverter.TryWriteBytes(record.AsSpan(word), generation); + var target = ((generation & 1) == 0 ? source : destination) + (ulong)(index * RecordBytes); + if (!mapping.Store.TryWriteSingleView(target, record) && !mapping.Store.TryWriteBacking(target, record)) + Interlocked.Increment(ref failures); + Interlocked.Increment(ref writes); + } + }) { IsBackground = true }).ToArray(); + foreach (var writer in writers) writer.Start(); + var torn = 0; + var copies = 0; + try + { + Assert.True(started.Wait(TimeSpan.FromSeconds(10))); + var deadline = DateTime.UtcNow + TimeSpan.FromMilliseconds(1500); + while (DateTime.UtcNow < deadline || copies < 50) + { + Assert.True(mapping.Store.TryReserveCopy(destination, source, CopyBytes, out var lease)); + using (lease) + { + Buffer.MemoryCopy((void*)lease.Source, (void*)lease.Destination, CopyBytes, CopyBytes); + for (var index = 0; index < Writers; index++) + { + if (!WholeRecord(lease.Destination + (ulong)(index * RecordBytes))) torn++; + if (!WholeRecord(lease.Source + (ulong)(index * RecordBytes))) torn++; + } + } + + copies++; + } + } + finally + { + Volatile.Write(ref stop, 1); + foreach (var writer in writers) Assert.True(writer.Join(TimeSpan.FromSeconds(10))); + } + + Assert.Equal(0, failures); + Assert.Equal(0, torn); + Assert.True(Volatile.Read(ref writes) > Writers); + } + + [Fact] + public void ReadersRacingDisposeEitherReadOrAreRefused() + { + if (!Supported) return; + for (var round = 0; round < 10; round++) + { + var mapping = new Mappings(); + var expected = BitConverter.GetBytes(Marker); + for (var slot = 0; slot < 8; slot++) Assert.True(mapping.Store.TryWriteBacking(mapping.Address + (ulong)(slot * 64), expected)); + var stop = 0; + var wrong = 0; + var reads = 0L; + var refusals = 0L; + using var started = new CountdownEvent(8); + var readers = Enumerable.Range(0, 8).Select(slot => new Thread(() => + { + var bytes = new byte[8]; + started.Signal(); + while (Volatile.Read(ref stop) == 0) + { + if (mapping.Store.TryReadSingleView(mapping.Address + (ulong)(slot * 64), bytes)) + { + if (BitConverter.ToUInt64(bytes) != Marker) Interlocked.Increment(ref wrong); + Interlocked.Increment(ref reads); + } + else Interlocked.Increment(ref refusals); + } + }) { IsBackground = true }).ToArray(); + foreach (var reader in readers) reader.Start(); + try + { + Assert.True(started.Wait(TimeSpan.FromSeconds(10))); + Thread.Sleep(5); + mapping.Store.Dispose(); + Assert.False(mapping.Store.TryReadSingleView(mapping.Address, new byte[8])); + Assert.False(mapping.Store.TryEnterAliasAccess()); + Thread.Sleep(5); + } + finally + { + Volatile.Write(ref stop, 1); + foreach (var reader in readers) Assert.True(reader.Join(TimeSpan.FromSeconds(10))); + mapping.Dispose(); + } + + Assert.Equal(0, wrong); + Assert.True(reads > 0); + Assert.True(refusals > 0); + } + } + + // Lock-free writes and reads in a stable view stay exact while another range is mapped and + // unmapped over and over. + [Fact] + public void SingleViewAccessesHoldWhileOtherRangesAreRemapped() + { + if (!Supported) return; + using var mapping = new Mappings(); + var churn = mapping.Address + 2 * Part; + var stop = 0; + var failures = 0; + var accesses = 0L; + var workers = Enumerable.Range(0, 4).Select(worker => new Thread(() => + { + var bytes = new byte[8]; + var slot = mapping.Address + (ulong)(worker * 64); + for (var value = 1UL; Volatile.Read(ref stop) == 0; value++) + { + if (!mapping.Store.TryWriteSingleView(slot, BitConverter.GetBytes(value)) || + !mapping.Store.TryReadSingleView(slot, bytes) || BitConverter.ToUInt64(bytes) != value) + Interlocked.Increment(ref failures); + Interlocked.Increment(ref accesses); + _ = mapping.Store.TryReadSingleView(churn + 8, bytes); + } + }) { IsBackground = true }).ToArray(); + foreach (var worker in workers) worker.Start(); + try + { + for (var round = 0; round < 200; round++) + { + Assert.True(mapping.Store.TryMapReservedRange(churn, Part, 3 * Part, HostPageProtection.ReadWrite, out _)); + Assert.True(mapping.Store.Unmap(churn, Part, out _)); + } + } + finally + { + Volatile.Write(ref stop, 1); + foreach (var worker in workers) Assert.True(worker.Join(TimeSpan.FromSeconds(10))); + } + + Assert.Equal(0, failures); + Assert.True(accesses > 0); + } + + private static bool WholeRecord(ulong address) + { + var words = (ulong*)address; + for (var word = 1; word < RecordBytes / 8; word++) + if (words[word] != words[0]) return false; + return true; + } + + private static void SetCopyHook(SharedBackingViews store, Action hook) => + typeof(SharedBackingViews).GetField("_beforeCanonicalAliasCopyForControl", BindingFlags.Instance | BindingFlags.NonPublic)! + .SetValue(store, hook); + + // Two views of Part bytes each (backing offsets 0 and Part) and a third reserved Part left + // unmapped for remapping. + private sealed class Mappings : IDisposable + { + public IHostViewMemory Host { get; } = HostViewMemory.Create(); + public SharedBackingViews Store { get; } + public ulong Address { get; } + private readonly ulong _holeSize; + private bool _disposed; + + public Mappings() + { + Store = new SharedBackingViews(Host, 4 * Part); + _holeSize = AlignUp(4 * Part, Host.Granularity); + Address = ReserveFreeHole(Host, _holeSize); + Assert.True(Host.SplitHole(Address, Part)); + Assert.True(Host.SplitHole(Address + Part, Part)); + Assert.True(Host.SplitHole(Address + 2 * Part, Part)); + Assert.True(Store.TryMapReservedRange(Address, Part, 0, HostPageProtection.ReadWrite, out _)); + Assert.True(Store.TryMapReservedRange(Address + Part, Part, Part, HostPageProtection.ReadWrite, out _)); + } + + public void Dispose() + { + if (_disposed) return; + _disposed = true; + Store.Dispose(); + Assert.True(Host.JoinHoles(Address, _holeSize)); + Assert.True(Host.FreeHole(Address, _holeSize)); + } + } +} From 5221bc469254842801c341b1122b96486f8aaec9 Mon Sep 17 00:00:00 2001 From: kuba Date: Sun, 15 Nov 2026 03:08:05 +0000 Subject: [PATCH 018/178] [HLE] Keep the write-interval ledger dormant until its first observer Every ordinary managed write paid ~16 shared atomics (admission, identity, slot, active/begun/completed counters, history) for a ledger nothing in production reads: only TryReadMappedCopy* and ExecuteOriginalWrite observe it, and they have no production caller. Until something captures a revision, reserves a publication or enrolls a read watch, a writer now only increments its own stripe of a second lane, re-reads the sticky observer flag (backing out to the full path if set) and gets a dormant token; the byte intervals inside a dormant operation need no registration. Observers set the flag with Interlocked.Exchange and refuse (never wait, counted in ObservationRefusals) while the lane's sum is not zero; once one sees zero, every dormant writer has landed and every later write takes admission, identity and history exactly as before. The switch logs one [MEM] line per backing. SHARPEMU_WRITE_INTERVALS_DORMANT=0 starts every ledger observed. Tests: dormant writes touch no slot, history or counter and do not allocate; a dormant writer paused before its bytes makes capture, read-watch enrollment and publication reservation refuse, and after it lands they succeed and writes advance identity again (fails when observers ignore the lane); a reserved publication always sees the bytes its revision read while ten writers run. Ledger tests that count intervals observe first. --- .../OrdinaryBackingWriteReservation.cs | 2 +- .../GuestMemory/SharedBackingViews.cs | 25 ++- .../HostManagedWriteIntervals.ReadWatches.cs | 4 +- .../Host/HostManagedWriteIntervals.cs | 80 ++++++- .../PvmMappedCopyWorker.SingleViewWrite.cs | 3 + .../ManagedWriteIntervalTests.cs | 34 ++- .../MappedPublicationTests.ValidationBusy.cs | 8 + .../GuestMemory/ManagedWriteDormantTests.cs | 212 ++++++++++++++++++ 8 files changed, 352 insertions(+), 16 deletions(-) create mode 100644 tests/SharpEmu.Libs.Tests/Memory/GuestMemory/ManagedWriteDormantTests.cs diff --git a/src/SharpEmu.HLE/GuestMemory/OrdinaryBackingWriteReservation.cs b/src/SharpEmu.HLE/GuestMemory/OrdinaryBackingWriteReservation.cs index cc502439f..59a14a5f9 100644 --- a/src/SharpEmu.HLE/GuestMemory/OrdinaryBackingWriteReservation.cs +++ b/src/SharpEmu.HLE/GuestMemory/OrdinaryBackingWriteReservation.cs @@ -66,7 +66,7 @@ private OrdinaryBackingWriteAdmission TryAcquire(TimeSpan timeout, bool classify if (!(classify ? TryIsOriginalCurrent(out failure) : IsOriginalCurrent)) return OrdinaryBackingWriteAdmission.OriginalChanged; operation = backing.BeginManagedWriteOperation(); - if (operation.Owner is not null && operation.Slot >= 0 && operation.Identity > 0) + if (operation.Owner is not null && (operation.Slot >= 0 && operation.Identity > 0 || HostManagedWriteIntervals.IsDormant(operation))) { admitted = true; return (classify ? TryIsOriginalCurrent(out failure) : IsOriginalCurrent) diff --git a/src/SharpEmu.HLE/GuestMemory/SharedBackingViews.cs b/src/SharpEmu.HLE/GuestMemory/SharedBackingViews.cs index f7492eb62..92b6aa78e 100644 --- a/src/SharpEmu.HLE/GuestMemory/SharedBackingViews.cs +++ b/src/SharpEmu.HLE/GuestMemory/SharedBackingViews.cs @@ -553,10 +553,12 @@ private HostBackingDiscard DiscardCanonicalAlias(ulong offset, ulong count) finally { HostBackingObject.EndManagedWrite(interval, succeeded); } } - private void CopyToCanonicalAlias(ulong destination, ReadOnlySpan source) + // dormantEnvelope: the caller holds a dormant operation token (HostManagedWriteIntervals.IsDormant), + // whose registration already makes every observer refuse, so these bytes need none of their own. + private void CopyToCanonicalAlias(ulong destination, ReadOnlySpan source, bool dormantEnvelope = false) { _singleCopy?.BeforeWrite(destination - AliasBase, (ulong)source.Length); - var interval = _backing!.BeginManagedWrite(destination - AliasBase, (ulong)source.Length); + var interval = dormantEnvelope ? default : _backing!.BeginManagedWrite(destination - AliasBase, (ulong)source.Length); var succeeded = false; if (!HostManagedWriteIntervals.AllowsBytes(interval)) throw new InvalidOperationException("Participating write lost admission."); try @@ -568,11 +570,11 @@ private void CopyToCanonicalAlias(ulong destination, ReadOnlySpan source) finally { HostBackingObject.EndManagedWrite(interval, succeeded); } } - private void CopyCanonicalAliasChunk(ulong source, ulong destination, int bytes) + private void CopyCanonicalAliasChunk(ulong source, ulong destination, int bytes, bool dormantEnvelope = false) { _singleCopy?.BeforeRead(source - AliasBase, (ulong)bytes); _singleCopy?.BeforeWrite(destination - AliasBase, (ulong)bytes); - var interval = _backing!.BeginManagedWrite(destination - AliasBase, (ulong)bytes); + var interval = dormantEnvelope ? default : _backing!.BeginManagedWrite(destination - AliasBase, (ulong)bytes); var succeeded = false; if (!HostManagedWriteIntervals.AllowsBytes(interval)) throw new InvalidOperationException("Participating write lost admission."); try { Buffer.MemoryCopy((void*)source, (void*)destination, bytes, bytes); succeeded = true; } @@ -646,7 +648,7 @@ public bool TryWriteSingleView(ulong address, ReadOnlySpan data) var succeeded = false; try { - CopyToCanonicalAlias(target, data); + CopyToCanonicalAlias(target, data, HostManagedWriteIntervals.IsDormant(interval)); succeeded = true; return true; } @@ -693,7 +695,7 @@ public bool TryCopySingleView(ulong destination, ulong source, ulong size) var succeeded = false; try { - CopyCanonicalAliasChunk(from, to, (int)size); + CopyCanonicalAliasChunk(from, to, (int)size, HostManagedWriteIntervals.IsDormant(interval)); succeeded = true; return true; } @@ -744,8 +746,9 @@ public bool TryWritePairSingleView(ulong firstAddress, ReadOnlySpan first, var succeeded = false; try { - CopyToCanonicalAlias(firstTarget, first); - CopyToCanonicalAlias(secondTarget, second); + var dormant = HostManagedWriteIntervals.IsDormant(interval); + CopyToCanonicalAlias(firstTarget, first, dormant); + CopyToCanonicalAlias(secondTarget, second, dormant); succeeded = true; return true; } @@ -790,7 +793,7 @@ public bool TryFillSingleView(ulong address, int length, TState state, G var succeeded = false; try { - filled = FillCanonicalAlias(target, length, state, fill); + filled = FillCanonicalAlias(target, length, state, fill, HostManagedWriteIntervals.IsDormant(interval)); succeeded = true; return true; } @@ -805,7 +808,7 @@ public bool TryFillSingleView(ulong address, int length, TState state, G } } - private int FillCanonicalAlias(ulong destination, int length, TState state, GuestSpanFill fill) + private int FillCanonicalAlias(ulong destination, int length, TState state, GuestSpanFill fill, bool dormantEnvelope = false) { // A fill may stop short (a file read at its end): released chunks it covers whole get // back only the bytes it did not reach, once it says how far it got. @@ -813,7 +816,7 @@ private int FillCanonicalAlias(ulong destination, int length, TState sta var produced = 0; try { - var interval = _backing!.BeginManagedWrite(destination - AliasBase, (ulong)length); + var interval = dormantEnvelope ? default : _backing!.BeginManagedWrite(destination - AliasBase, (ulong)length); var succeeded = false; if (!HostManagedWriteIntervals.AllowsBytes(interval)) throw new InvalidOperationException("Participating write lost admission."); try diff --git a/src/SharpEmu.HLE/Host/HostManagedWriteIntervals.ReadWatches.cs b/src/SharpEmu.HLE/Host/HostManagedWriteIntervals.ReadWatches.cs index 45ae613ae..f483171a1 100644 --- a/src/SharpEmu.HLE/Host/HostManagedWriteIntervals.ReadWatches.cs +++ b/src/SharpEmu.HLE/Host/HostManagedWriteIntervals.ReadWatches.cs @@ -147,6 +147,8 @@ internal void Release() } if (Volatile.Read(ref coverageIncomplete) != 0) { rejection = "watch-enrollment-coverage-incomplete"; return null; } + if (!TryObserve()) + { rejection = "watch-enrollment-observation-activating"; return null; } var exclusiveOwner = CreateAdmissionOwner(CpuMappedAdmissionOwnerKind.ReadWatchEnrollment); originalAdmission = Interlocked.CompareExchange(ref admission, PublicationBit, 0); if (originalAdmission != 0) @@ -176,7 +178,7 @@ internal void Release() // remains private until the transaction fully applies its own bytes. internal ReadWatch? TryCreatePublicationSuccessor(ReadWatch original) { - if (!original.IsUnrevokedDuringPublication(this)) return null; + if (!TryObserve() || !original.IsUnrevokedDuringPublication(this)) return null; var installed = Volatile.Read(ref readWatches); if (installed is null) return null; var revision = Volatile.Read(ref nextIdentity); diff --git a/src/SharpEmu.HLE/Host/HostManagedWriteIntervals.cs b/src/SharpEmu.HLE/Host/HostManagedWriteIntervals.cs index 35a99567d..b6c4e071f 100644 --- a/src/SharpEmu.HLE/Host/HostManagedWriteIntervals.cs +++ b/src/SharpEmu.HLE/Host/HostManagedWriteIntervals.cs @@ -32,10 +32,39 @@ private void LoseCoverage(CoverageLoss reason) Interlocked.Exchange(ref coverageIncomplete, 1); } - internal HostManagedWriteIntervals(HostBackingObject backing) => this.backing = backing; + // Dormant until the first observer. Nothing in production captures a revision, reserves a + // publication or enrolls a read watch, so until something does, an ordinary writer only + // registers itself on its own stripe of the dormant-writer lane (no admission, identity, slot, + // history or counters) and its token has Slot == DormantSlot. An observer first sets + // `observerSeen` (Interlocked.Exchange, a full fence) and then sums that lane; a writer increments + // its stripe (a full fence) and then re-reads `observerSeen`, backing out to the full path if it + // is set. So an observer that sees `observerSeen` set and a zero sum knows every dormant writer has + // landed and every later one takes the full path; while the sum is not zero it refuses (it + // never waits) and counts the refusal. Admission, identity and history then hold exactly as + // before for every write after that point. SHARPEMU_WRITE_INTERVALS_DORMANT=0 starts observed. + internal const int DormantSlot = -2; + private const int DormantLane = 1; + internal static readonly bool DormantEnabled = + Environment.GetEnvironmentVariable("SHARPEMU_WRITE_INTERVALS_DORMANT") != "0"; + private readonly HostAccessStripes dormantWriters; + private int observerSeen; // sticky + private int dormantDrained; // an observer saw `observerSeen` set and no dormant writer: none can exist again + private long observationRefusals; + internal bool IsObserved => Volatile.Read(ref observerSeen) != 0; + internal long ObservationRefusals => Volatile.Read(ref observationRefusals); + + internal HostManagedWriteIntervals(HostBackingObject backing) + { + this.backing = backing; + dormantWriters = backing.AliasStripes ?? new HostAccessStripes(); + if (!DormantEnabled) observerSeen = dormantDrained = 1; + } + internal readonly record struct Token(HostManagedWriteIntervals? Owner, int Slot, long Identity) { internal long RejectedAdmission { get; init; } + // The dormant-writer stripe cell a dormant token registered on (Slot == DormantSlot only). + internal int DormantCell { get; init; } internal bool IsPublicationBusy => Owner is not null && Slot == -1 && Identity == 0 && RejectedAdmission >= 0 && (RejectedAdmission & PublicationBit) != 0; } @@ -45,6 +74,14 @@ internal readonly record struct Token(HostManagedWriteIntervals? Owner, int Slot private Token BeginCore(ulong offset, ulong count, bool operation) { if (count == 0) return default; + if (Volatile.Read(ref observerSeen) == 0) + { + if (offset > backing.Size || count > backing.Size - offset) + { LoseCoverage(CoverageLoss.InvalidPhysicalBounds); return default; } + var cell = dormantWriters.Enter(DormantLane); // full fence before the re-read + if (Volatile.Read(ref observerSeen) == 0) return new(this, DormantSlot, 0) { DormantCell = cell }; + dormantWriters.ExitCell(cell); // an observer arrived: take the full path + } var observed = Volatile.Read(ref admission); var acquired = false; for (var attempt = 0; attempt < Capacity; attempt++) @@ -89,6 +126,13 @@ private Token BeginCore(ulong offset, ulong count, bool operation) internal bool End(Token token, bool succeeded) { if (token.Owner is null) return token.Identity == 0 && token.Slot == 0; // disabled/nonempty tracking decline + if (token.Slot == DormantSlot && token.Identity == 0 && ReferenceEquals(token.Owner, this)) + { + // No watch can exist while a dormant writer is registered, and no observer has a + // revision this write could fall inside: there is no history to record. + dormantWriters.ExitCell(token.DormantCell); + return true; + } if (!ReferenceEquals(token.Owner, this) || token.Identity <= 0 || (uint)token.Slot >= Capacity) return false; // Consume this exact operation before reuse. A copied/stale token cannot @@ -113,7 +157,33 @@ internal bool End(Token token, bool succeeded) } - internal static bool AllowsBytes(Token token) => token.Owner is null || token.Slot >= 0; + internal static bool AllowsBytes(Token token) => token.Owner is null || token.Slot >= 0 || token.Slot == DormantSlot; + // A dormant operation envelope already makes every observer refuse until it ends, so the + // byte intervals inside it need no registration of their own. + internal static bool IsDormant(Token token) => token.Owner is not null && token.Slot == DormantSlot; + + // Every observer calls this before it reads admission, identity or history. True once no + // dormant writer can be in flight; false (counted, never a wait) while one is. + private bool TryObserve() + { + if (Volatile.Read(ref dormantDrained) != 0) return true; + if (Interlocked.Exchange(ref observerSeen, 1) == 0) + { + // Once per backing, on stdout (game.log): from here on every ordinary write pays the + // full ledger again, so a production observer must not arrive unnoticed. + try { Console.Out.WriteLine($"[MEM] write-intervals observed backing={backing.Identity}: ordinary writes now take admission, identity and history"); } + catch (Exception) { } // a log failure must not change the observer's outcome + } + + if (dormantWriters.Sum(DormantLane) != 0) + { + Interlocked.Increment(ref observationRefusals); + return false; + } + + Volatile.Write(ref dormantDrained, 1); + return true; + } // Participating writers only, never a certificate for native/JIT/raw stores. // The count is acquired before allocating an interval identity; losing @@ -121,6 +191,7 @@ internal bool End(Token token, bool succeeded) internal bool TryCaptureRevision(out long revision) { revision = -1; + if (!TryObserve()) return false; if (Volatile.Read(ref coverageIncomplete) != 0 || Volatile.Read(ref admission) != 0) return false; var found = Volatile.Read(ref nextIdentity); if (found < 0 || Volatile.Read(ref admission) != 0 || Volatile.Read(ref coverageIncomplete) != 0) return false; @@ -138,6 +209,11 @@ internal bool TryReservePublication(long originalRevision, ReadOnlySpan new ReadOnlySpan((void*)Backing.AliasBase, (int)(Page * 2)).ToArray(); @@ -239,7 +249,29 @@ public void WarmedActualSingleViewWriteDoesNotAllocate() } [Fact] - public void WarmedEnrolledSingleViewFastPathWriteCompletesOneIntervalAndDoesNotAllocate() + public void WarmedDormantSingleViewFastPathWriteRegistersNoIntervalAndDoesNotAllocate() + { + using var state = new State(); var ledger = state.EnrollDormant(); byte[] bytes = [2, 4, 6, 8]; + var dormant = (bool)ledger.GetType().GetField("DormantEnabled", BindingFlags.Static | BindingFlags.NonPublic)!.GetValue(null)!; + if (!dormant) return; // SHARPEMU_WRITE_INTERVALS_DORMANT=0: the observed test covers it + Assert.False((bool)ledger.GetType().GetProperty("IsObserved", BindingFlags.Instance | BindingFlags.NonPublic)!.GetValue(ledger)!); + Assert.True(state.Views.TryWriteSingleView(State.Address + 16, bytes)); + Assert.Equal(bytes, state.Bytes().AsSpan(16, bytes.Length).ToArray()); + Assert.False(state.Views.TryWriteSingleView(State.Address + State.Page - 2, bytes)); + for (var i = 0; i < 10000; i++) Assert.True(state.Views.TryWriteSingleView(State.Address, bytes)); + var before = GC.GetAllocatedBytesForCurrentThread(); var allSucceeded = true; + for (var i = 0; i < 10000; i++) allSucceeded &= state.Views.TryWriteSingleView(State.Address, bytes); + var allocated = GC.GetAllocatedBytesForCurrentThread() - before; + Assert.True(allSucceeded); Assert.Equal(0, allocated); + // No admission, identity, slot, history or counter: the ledger is exactly as enrolled. + Assert.Equal(0, Count(ledger, "nextIdentity")); Assert.Equal(0, Count(ledger, "admission")); + Assert.Equal(0, Count(ledger, "begun")); Assert.Equal(0, Count(ledger, "completed")); + Assert.Equal(0, Count(ledger, "active")); Assert.Equal(0, Count(ledger, "aborted")); + Assert.Equal(0, Incomplete(ledger)); + } + + [Fact] + public void WarmedObservedSingleViewFastPathWriteCompletesOneIntervalAndDoesNotAllocate() { using var state = new State(); var ledger = state.Enroll(); byte[] bytes = [2, 4, 6, 8]; // An enrolled backing no longer declines the lock-free path; each write is one diff --git a/tests/SharpEmu.Host.Memory.Tests/MappedPublicationTests.ValidationBusy.cs b/tests/SharpEmu.Host.Memory.Tests/MappedPublicationTests.ValidationBusy.cs index f77c40c54..d8778114b 100644 --- a/tests/SharpEmu.Host.Memory.Tests/MappedPublicationTests.ValidationBusy.cs +++ b/tests/SharpEmu.Host.Memory.Tests/MappedPublicationTests.ValidationBusy.cs @@ -19,6 +19,11 @@ private static long ValidationWriterIdentity(object exact) => (long)exact.GetTyp .GetProperty("Identity", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)!.GetValue(exact)!; private static void EndValidationWriter(object exact, bool succeeded) => typeof(HostBackingObject) .GetMethod("EndManagedWrite", BindingFlags.Static | BindingFlags.NonPublic)!.Invoke(null, [exact, succeeded]); + private static void ObserveValidationWriters(HostBackingObject backing) + { + var writers = typeof(HostBackingObject).GetField("_managedWrites", BindingFlags.Instance | BindingFlags.NonPublic)!.GetValue(backing)!; + Assert.True((bool)writers.GetType().GetMethod("TryCaptureRevision", BindingFlags.Instance | BindingFlags.NonPublic)!.Invoke(writers, [-1L])!); + } private sealed class UnknownValidationProvider : ICpuMappedPublicationSource { @@ -106,6 +111,9 @@ public void OriginalMetadataRefusalCannotBorrowAnAdmittedWriterBusy(string failu using var other = new State(); var original = failure == "foreign" ? other.Capture() : state.Capture(); if (failure == "revoked") Assert.True(state.Host.Effect(State.Address, State.Page)); if (failure == "unknown") state.Host.Unknown(); + // A foreign original never observes this ledger; observe it so its writer is admitted + // exactly (a dormant writer holds no admission to borrow). + if (failure == "foreign") ObserveValidationWriters(state.Backing); var operation = BeginValidationWriterOperation(state.Backing); Assert.True(ValidationWriterIdentity(operation) > 0); try { diff --git a/tests/SharpEmu.Libs.Tests/Memory/GuestMemory/ManagedWriteDormantTests.cs b/tests/SharpEmu.Libs.Tests/Memory/GuestMemory/ManagedWriteDormantTests.cs new file mode 100644 index 000000000..3f8dd63a2 --- /dev/null +++ b/tests/SharpEmu.Libs.Tests/Memory/GuestMemory/ManagedWriteDormantTests.cs @@ -0,0 +1,212 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using System.Reflection; +using SharpEmu.HLE.GuestMemory; +using SharpEmu.HLE.Host; +using Xunit; +using static SharpEmu.Libs.Tests.Memory.HostViews.HostViewTestSupport; + +namespace SharpEmu.Libs.Tests.Memory.GuestMemory; + +// The write-interval ledger stays dormant until its first observer: dormant writers register only +// on their own stripe, and an observer refuses until every dormant writer has landed. +[Collection(GuestMemoryStateCollection.Name)] +public sealed unsafe class ManagedWriteDormantTests +{ + private const BindingFlags Private = BindingFlags.Instance | BindingFlags.NonPublic; + private const ulong Part = 256 * 1024; + + [Fact] + public void DormantWritesTouchNoSlotHistoryOrCounterAndDoNotAllocate() + { + if (!Supported || !HostManagedWriteIntervals.DormantEnabled) return; + using var mapping = new Mappings(); + var writers = mapping.Writers; + Assert.False(writers.IsObserved); + byte[] eight = [1, 2, 3, 4, 5, 6, 7, 8]; + var packet = new byte[32]; + for (var i = 0; i < 10000; i++) + { + Assert.True(mapping.Store.TryWriteSingleView(mapping.Address + 64, eight)); + Assert.True(mapping.Store.TryWritePairSingleView(mapping.Address + 128, eight, mapping.Address + 256, packet)); + } + + var allocated = long.MaxValue; var allSucceeded = true; + for (var round = 0; round < 5 && allocated != 0; round++) + { + var before = GC.GetAllocatedBytesForCurrentThread(); + for (var i = 0; i < 10000; i++) + { + allSucceeded &= mapping.Store.TryWriteSingleView(mapping.Address + 64, eight); + allSucceeded &= mapping.Store.TryWritePairSingleView(mapping.Address + 128, eight, mapping.Address + 256, packet); + } + + allocated = Math.Min(allocated, GC.GetAllocatedBytesForCurrentThread() - before); + } + + Assert.True(allSucceeded); Assert.Equal(0, allocated); + Assert.False(writers.IsObserved); + Assert.Equal(0, Field(writers, "nextIdentity")); + Assert.Equal(0, Field(writers, "admission")); + foreach (var name in new[] { "active", "begun", "completed", "aborted" }) Assert.Equal(0, Field(writers, name)); + foreach (var slot in Field(writers, "slots")) + Assert.Equal(0L, (long)slot!.GetType().GetField("State", Private)!.GetValue(slot)!); + foreach (var entry in Field(writers, "history")) + Assert.Equal(0L, (long)entry!.GetType().GetField("State", Private)!.GetValue(entry)!); + Assert.Equal(0, writers.ObservationRefusals); + } + + // A dormant writer paused between its registration and its bytes: a revision capture and a + // watch enrollment both refuse. Once it lands, both succeed and later writes advance identity. + [Fact] + public void ObserversRefuseWhileADormantWriterIsBetweenRegistrationAndBytes() + { + if (!Supported || !HostManagedWriteIntervals.DormantEnabled) return; + using var mapping = new Mappings(); + var writers = mapping.Writers; + using var paused = new ManualResetEventSlim(); + using var resume = new ManualResetEventSlim(); + var writerId = -1; + typeof(SharedBackingViews).GetField("_beforeCanonicalAliasCopyForControl", Private)!.SetValue(mapping.Store, (Action)((_, _) => + { + if (Environment.CurrentManagedThreadId != Volatile.Read(ref writerId)) return; + paused.Set(); + Assert.True(resume.Wait(TimeSpan.FromSeconds(20))); + })); + var written = false; + var writer = new Thread(() => + { + Volatile.Write(ref writerId, Environment.CurrentManagedThreadId); + written = mapping.Store.TryWriteSingleView(mapping.Address + 0x40, BitConverter.GetBytes(Marker)); + }) { IsBackground = true }; + HostManagedWriteIntervals.PhysicalRun[] runs = [new(0x1000, 64)]; + try + { + writer.Start(); + Assert.True(paused.Wait(TimeSpan.FromSeconds(10))); + Assert.False(writers.IsObserved); + Assert.False(writers.TryCaptureRevision(out var refusedRevision)); + Assert.Equal(-1, refusedRevision); + Assert.True(writers.IsObserved); + Assert.Null(writers.TryCreateReadWatch(runs, out var rejection, out _)); + Assert.Equal("watch-enrollment-observation-activating", rejection); + Assert.False(writers.TryReservePublication(0, runs, null, null)); + Assert.Equal(3, writers.ObservationRefusals); + Assert.Equal(0, Field(writers, "nextIdentity")); + } + finally { resume.Set(); } + + Assert.True(writer.Join(TimeSpan.FromSeconds(10))); + Assert.True(written); + Assert.True(writers.TryCaptureRevision(out var revision)); + Assert.Equal(0, revision); + var watch = writers.TryCreateReadWatch(runs, out var accepted, out _); + Assert.NotNull(watch); Assert.Null(accepted); + Assert.True(watch.IsCurrent); + // Observed now: a later write takes admission, an identity, history, and revokes the + // overlapping watch before its bytes. + Assert.True(mapping.Store.TryWriteSingleView(mapping.Address + 0x1010, BitConverter.GetBytes(Marker))); + Assert.True(Field(writers, "nextIdentity") > revision); + Assert.Equal(1, Field(writers, "completed")); + Assert.False(watch.IsCurrent); + watch.Release(); + Assert.Equal(3, writers.ObservationRefusals); + } + + // Ten writers write while an observer loops capture -> read V -> reserve. Whenever the + // reservation succeeds, the bytes under it still equal V. Starts dormant, so the first + // observations race dormant writers. + [Fact] + public void AReservedPublicationAlwaysSeesTheBytesItsRevisionRead() + { + if (!Supported) return; + using var mapping = new Mappings(); + var writers = mapping.Writers; + const int Watched = 64; + HostManagedWriteIntervals.PhysicalRun[] runs = [new(0, Watched)]; + var stop = 0; + var landed = 0L; + using var started = new CountdownEvent(10); + var threads = Enumerable.Range(0, 10).Select(index => new Thread(() => + { + var random = new System.Random(index + 1); + var bytes = new byte[8]; + started.Signal(); + while (Volatile.Read(ref stop) == 0) + { + random.NextBytes(bytes); + // One write in sixteen lands in the watched range; the rest elsewhere in the view. + var offset = random.Next(16) == 0 ? (ulong)random.Next(Watched / 8) * 8 : 0x1000 + (ulong)random.Next(0x1000) * 8; + // A write refused while the observer holds the publication simply does not land. + if (mapping.Store.TryWriteSingleView(mapping.Address + offset, bytes) || + mapping.Store.TryWriteBacking(mapping.Address + offset, bytes)) + Interlocked.Increment(ref landed); + Thread.SpinWait(random.Next(200)); + } + }) { IsBackground = true }).ToArray(); + foreach (var thread in threads) thread.Start(); + var attempts = 0; var captures = 0; var reserved = 0; var mismatches = 0; + var value = new byte[Watched]; + try + { + Assert.True(started.Wait(TimeSpan.FromSeconds(10))); + var deadline = DateTime.UtcNow + TimeSpan.FromMilliseconds(1500); + while (DateTime.UtcNow < deadline || reserved < 20 && DateTime.UtcNow < deadline + TimeSpan.FromSeconds(10)) + { + attempts++; + if (!writers.TryCaptureRevision(out var revision)) continue; + captures++; + new ReadOnlySpan((void*)mapping.Backing.AliasBase, Watched).CopyTo(value); + if (!writers.TryReservePublication(revision, runs, null, null)) continue; + try + { + reserved++; + if (!new ReadOnlySpan((void*)mapping.Backing.AliasBase, Watched).SequenceEqual(value)) mismatches++; + } + finally { writers.ReleasePublication(null); } + } + } + finally + { + Volatile.Write(ref stop, 1); + foreach (var thread in threads) Assert.True(thread.Join(TimeSpan.FromSeconds(10))); + } + + Assert.True(Volatile.Read(ref landed) > 0); + Assert.Equal(0, mismatches); + Assert.True(captures > 0, $"attempts={attempts}"); + Assert.True(reserved > 0, $"attempts={attempts} captures={captures}"); + Assert.True(writers.IsObserved); + } + + private static T Field(object owner, string name) => (T)owner.GetType().GetField(name, Private)!.GetValue(owner)!; + + private sealed class Mappings : IDisposable + { + public IHostViewMemory Host { get; } = HostViewMemory.Create(); + public SharedBackingViews Store { get; } + public ulong Address { get; } + public HostBackingObject Backing { get; } + public HostManagedWriteIntervals Writers { get; } + private readonly ulong _holeSize; + + public Mappings() + { + Store = new SharedBackingViews(Host, Part); + _holeSize = AlignUp(Part, Host.Granularity); + Address = ReserveFreeHole(Host, _holeSize); + Assert.True(Store.TryMapReservedRange(Address, Part, 0, HostPageProtection.ReadWrite, out _)); + Backing = (HostBackingObject)typeof(SharedBackingViews).GetField("_backing", Private)!.GetValue(Store)!; + // The macOS view host enrolls every backing when it is created. + Backing.EnrollManagedWrites(); + Writers = Backing.ManagedWrites!; + } + + public void Dispose() + { + Store.Dispose(); + Assert.True(Host.FreeHole(Address, _holeSize)); + } + } +} From 2264599548afce9ddf6830b9efb7b12a09d8d93d Mon Sep 17 00:00:00 2001 From: kuba Date: Sun, 15 Nov 2026 03:20:38 +0000 Subject: [PATCH 019/178] [HLE] Pair write landed: announce lazily covered ranges as a single write does GuestGpuMemory.MarkCpuWriteLanded(first, second) tested Covers, while the single-write overload and the pre-write MarkCpuWrite test CoversWrites, so a pair write into a range only a lazy registration covers (the PRT aperture) was announced before it landed but never after: an upload between the two kept the old bytes and left the pages clean. The new test (a pair must reach the stores exactly as its two writes do) failed before the fix on arm64 and x64. --- src/SharpEmu.HLE/GpuMemory/GuestGpuMemory.cs | 6 +++-- .../Memory/GpuMemory/GuestGpuMemoryTests.cs | 22 +++++++++++++++++++ 2 files changed, 26 insertions(+), 2 deletions(-) diff --git a/src/SharpEmu.HLE/GpuMemory/GuestGpuMemory.cs b/src/SharpEmu.HLE/GpuMemory/GuestGpuMemory.cs index 81a487e8c..48e129eac 100644 --- a/src/SharpEmu.HLE/GpuMemory/GuestGpuMemory.cs +++ b/src/SharpEmu.HLE/GpuMemory/GuestGpuMemory.cs @@ -261,8 +261,10 @@ public void MarkCpuWriteLanded(ulong address, ulong size) // in that order, as they do from two calls. public void MarkCpuWriteLanded(ulong firstAddress, ulong firstSize, ulong secondAddress, ulong secondSize) { - var firstCovered = firstSize != 0 && Covers(firstAddress, firstSize); - var secondCovered = secondSize != 0 && Covers(secondAddress, secondSize); + // CoversWrites, as the single-write overload and the pre-write MarkCpuWrite test: a range + // only a lazy registration covers is announced before it lands, so it must be after too. + var firstCovered = firstSize != 0 && CoversWrites(firstAddress, firstSize); + var secondCovered = secondSize != 0 && CoversWrites(secondAddress, secondSize); if (!firstCovered && !secondCovered) { return; diff --git a/tests/SharpEmu.Libs.Tests/Memory/GpuMemory/GuestGpuMemoryTests.cs b/tests/SharpEmu.Libs.Tests/Memory/GpuMemory/GuestGpuMemoryTests.cs index 0f82310a3..b212a0fed 100644 --- a/tests/SharpEmu.Libs.Tests/Memory/GpuMemory/GuestGpuMemoryTests.cs +++ b/tests/SharpEmu.Libs.Tests/Memory/GpuMemory/GuestGpuMemoryTests.cs @@ -260,6 +260,28 @@ public void RegisterLazyRange_CoversWritesAndFaultsWithoutRegisteringSpans() _memory.Dispose(); } + // A pair write lands as its two writes would: a range only a lazy registration covers is + // announced after it lands too, as the single-write overload and the pre-write mark do. + [Fact] + public void PairWriteLandedReachesTheStoresForALazilyCoveredRangeAsTwoWritesDo() + { + _memory.RegisterLazyRange(0x100000, 0x10000); + _memory.MarkCpuWriteLanded(0x104000, 0x8); + _memory.MarkCpuWriteLanded(0x105000, 0x20); + var singles = _stores.Calls.ToArray(); + Assert.NotEmpty(singles); + + _stores.Calls.Clear(); + _memory.MarkCpuWriteLanded(0x104000, 0x8, 0x105000, 0x20); + Assert.Equal(singles, _stores.Calls); + + _stores.Calls.Clear(); + _memory.UnregisterLazyRange(0x100000, 0x10000); + _memory.MarkCpuWriteLanded(0x104000, 0x8, 0x105000, 0x20); + Assert.Empty(_stores.Calls); + _memory.Dispose(); + } + [Fact] public void Register_MarksTheMappedContentWrittenOnTheGpuQueue() { From b6aff34d919948f66c63bbc6ba9d46d52b5e77e1 Mon Sep 17 00:00:00 2001 From: kuba Date: Sun, 15 Nov 2026 03:20:38 +0000 Subject: [PATCH 020/178] [Agc] CbSetShRegistersDirect: all runs in one reservation and one write Each run of consecutive registers took a command-buffer state read, a cursor write and a packet write: Demon's Souls calls this ~560 times a frame with 5-8 runs. When the buffer already has room for every run's packet, they are reserved in place together and committed with the cursor as one pair write (1 read + 1 pair per call). Without that room the runs go one at a time exactly as before, each reaching the full callback with its own size. SHARPEMU_AGC_COALESCE=0 always takes the run-by-run path. Test: coalesced and run-by-run output compared byte for byte (memory, cursor, return, callback requests, leaf decline) for the DS shape (unsorted, a duplicate, 7 runs) with plenty of room, exactly enough, reserved dwords, one dword short (callback), room for the first runs only, the same in a leaf, and a full buffer. --- .../Agc/AgcExports.RegisterPackets.cs | 55 +++++- .../Agc/AgcShRegistersCoalesceTests.cs | 176 ++++++++++++++++++ 2 files changed, 230 insertions(+), 1 deletion(-) create mode 100644 tests/SharpEmu.Libs.Tests/Agc/AgcShRegistersCoalesceTests.cs diff --git a/src/SharpEmu.Libs/Agc/AgcExports.RegisterPackets.cs b/src/SharpEmu.Libs/Agc/AgcExports.RegisterPackets.cs index 8dda38746..73a59a268 100644 --- a/src/SharpEmu.Libs/Agc/AgcExports.RegisterPackets.cs +++ b/src/SharpEmu.Libs/Agc/AgcExports.RegisterPackets.cs @@ -13,6 +13,11 @@ public static partial class AgcExports private const uint CbSetShRegisterRangeMarker = 0x6875000D; + // SHARPEMU_AGC_COALESCE=0 emits CbSetShRegistersDirect's runs one allocation and write at a + // time again. Not readonly so the differential test can compare both paths in one process. + internal static bool CoalesceShRegisterRuns = + Environment.GetEnvironmentVariable("SHARPEMU_AGC_COALESCE") != "0"; + [SysAbiExport( Nid = "UZbQjYAwwXM", ExportName = "sceAgcCbSetShRegistersDirect", @@ -75,9 +80,57 @@ public static int CbSetShRegistersDirect(CpuContext ctx) } } + var count = (int)registerCount; + // Every run's packet lands at the next cursor position, so when the buffer already has + // room for all of them they are one reservation, one state read and one write (cursor + // and packets together). Without that room the runs go one at a time below, each + // reaching the buffer's full callback with its own size, exactly as before. + if (CoalesceShRegisterRuns) + { + uint totalDwords = 0; + var runCount = 0; + for (var start = 0; start < count; runCount++) + { + var end = start + 1; + while (end < count && registers[end].Offset == registers[end - 1].Offset + 1) end++; + totalDwords += (uint)(end - start) + 2; // at most 3 x 4096 dwords + start = end; + } + + if (TryReserveCommandDwordsInPlace(ctx, commandBufferAddress, totalDwords, out var batchAddress, out var nextCursor)) + { + runs = runCount; + if (profile) + { + sourceOverlap = batchAddress < registersAddress + registerCount * 8UL && + registersAddress < batchAddress + totalDwords * 4UL; + } + + packet = System.Buffers.ArrayPool.Shared.Rent((int)totalDwords); + var cursor = 0; + for (var start = 0; start < count;) + { + var end = start + 1; + while (end < count && registers[end].Offset == registers[end - 1].Offset + 1) end++; + packet[cursor++] = Pm4((uint)(end - start) + 2, ItSetShReg, 0); + packet[cursor++] = registers[start].Offset & 0xFFFFu; + for (var index = start; index < end; index++) packet[cursor++] = registers[index].Value; + start = end; + } + + if (!TryCommitCommandDwords(ctx, commandBufferAddress, nextCursor, batchAddress, packet.AsSpan(0, cursor))) + { + outcome = Diagnostics.HleCallShapeProfile.ShRegistersOutcome.WriteFailed; + return ReturnPointer(ctx, 0); + } + + outcome = Diagnostics.HleCallShapeProfile.ShRegistersOutcome.Written; + return ReturnPointer(ctx, batchAddress); + } + } + ulong firstCommandAddress = 0; var startIndex = 0; - var count = (int)registerCount; while (startIndex < count) { var endIndex = startIndex + 1; diff --git a/tests/SharpEmu.Libs.Tests/Agc/AgcShRegistersCoalesceTests.cs b/tests/SharpEmu.Libs.Tests/Agc/AgcShRegistersCoalesceTests.cs new file mode 100644 index 000000000..1d14130b6 --- /dev/null +++ b/tests/SharpEmu.Libs.Tests/Agc/AgcShRegistersCoalesceTests.cs @@ -0,0 +1,176 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using System.Buffers.Binary; +using SharpEmu.HLE; +using SharpEmu.Libs.Agc; +using Xunit; + +namespace SharpEmu.Libs.Tests.Agc; + +// sceAgcCbSetShRegistersDirect with its runs coalesced into one reservation and one write must +// leave exactly the bytes, cursor, return value and full-callback calls of the run-by-run path. +[Collection(AgcCommandBufferChainCollection.Name)] +public sealed class AgcShRegistersCoalesceTests +{ + private const ulong BaseAddress = 0x2_7000_0000; + private const ulong CommandBuffer = BaseAddress + 0x100; + private const ulong Registers = BaseAddress + 0x200; + private const ulong Packets = BaseAddress + 0x1000; + private const ulong CallbackSpace = BaseAddress + 0x2000; + private const int MemoryBytes = 0x4000; + + // The Demon's Souls shape: unsorted, a duplicated register, 7 runs of up to 4 registers. + private static readonly (uint Offset, uint Value)[] DsShape = + [ + (0x41, 0xA1), (0x10, 0x01), (0x12, 0x03), (0x80, 0xB0), (0x11, 0x02), (0x40, 0xA0), + (0x09, 0x0F), (0x12, 0x33), (0x83, 0xB3), (0x81, 0xB1), (0x100, 0xC0), (0x82, 0xB2), + (0x08, 0x0E), (0x30, 0xD0), + ]; + + // Total dwords for DsShape: 14 registers + 2 x 7 runs. + private const uint DsShapeDwords = 14 + 2 * 7; + + [Theory] + [InlineData(1024u, 0u, false)] // plenty of room + [InlineData(DsShapeDwords, 0u, false)] // exactly the room every run needs + [InlineData(DsShapeDwords + 4, 4u, false)] // exactly, with reserved dwords + [InlineData(DsShapeDwords - 1, 0u, false)] // nearly full: the last run reaches the callback + [InlineData(10u, 0u, false)] // the callback fires after the first runs + [InlineData(DsShapeDwords - 1, 0u, true)] // nearly full in a leaf: declines as before + [InlineData(0u, 0u, false)] // full: the first run reaches the callback + public void CoalescedRunsMatchTheRunByRunPathByteForByte(uint roomDwords, uint reservedDwords, bool leaf) + { + var perRun = Run(coalesce: false, DsShape, roomDwords, reservedDwords, leaf); + var coalesced = Run(coalesce: true, DsShape, roomDwords, reservedDwords, leaf); + Assert.Equal(perRun.Result, coalesced.Result); + Assert.Equal(perRun.Rax, coalesced.Rax); + Assert.Equal(perRun.Declined, coalesced.Declined); + Assert.Equal(perRun.Callbacks, coalesced.Callbacks); + Assert.Equal(perRun.Memory, coalesced.Memory); + if (roomDwords >= DsShapeDwords + reservedDwords) + { + // Room for every run: one reservation from the cursor, no callback. + Assert.Empty(coalesced.Callbacks); + Assert.Equal(Packets, coalesced.Rax); + Assert.Equal(Packets + DsShapeDwords * 4, BinaryPrimitives.ReadUInt64LittleEndian(coalesced.Memory.AsSpan((int)(CommandBuffer + 0x10 - BaseAddress)))); + } + else if (!leaf) + { + Assert.NotEmpty(coalesced.Callbacks); + } + } + + [Theory] + [InlineData(1)] + [InlineData(5)] + [InlineData(32)] + public void ContiguousAndSingleRegisterListsMatch(int registers) + { + var list = Enumerable.Range(0, registers).Select(index => ((uint)(0x200 - index), 0x1000u + (uint)index)).ToArray(); + var perRun = Run(coalesce: false, list, 1024, 0, false); + var coalesced = Run(coalesce: true, list, 1024, 0, false); + Assert.Equal(perRun.Rax, coalesced.Rax); + Assert.Equal(perRun.Memory, coalesced.Memory); + Assert.Empty(coalesced.Callbacks); + } + + private sealed record Outcome(int Result, ulong Rax, bool Declined, uint[] Callbacks, byte[] Memory); + + private static Outcome Run(bool coalesce, (uint Offset, uint Value)[] registers, uint roomDwords, uint reservedDwords, bool leaf) + { + var memory = new FakeCpuMemory(BaseAddress, MemoryBytes); + WriteUInt64(memory, CommandBuffer + 0x10, Packets); + WriteUInt64(memory, CommandBuffer + 0x18, Packets + roomDwords * 4UL); + WriteUInt64(memory, CommandBuffer + 0x20, 0x1234); + WriteUInt64(memory, CommandBuffer + 0x28, 0x5678); + WriteUInt32(memory, CommandBuffer + 0x30, reservedDwords); + for (var index = 0; index < registers.Length; index++) + { + WriteUInt32(memory, Registers + (ulong)index * 8, registers[index].Offset); + WriteUInt32(memory, Registers + (ulong)index * 8 + 4, registers[index].Value); + } + + var context = new CpuContext(memory, Generation.Gen5) + { + [CpuRegister.Rdi] = CommandBuffer, + [CpuRegister.Rsi] = Registers, + [CpuRegister.Rdx] = (ulong)registers.Length, + }; + context.DeclineGuestCallbacks = leaf; + var scheduler = new SpaceCallbackScheduler(memory); + var previousScheduler = GuestThreadExecution.Scheduler; + var previousCoalesce = AgcExports.CoalesceShRegisterRuns; + try + { + GuestThreadExecution.Scheduler = scheduler; + AgcExports.CoalesceShRegisterRuns = coalesce; + var result = AgcExports.CbSetShRegistersDirect(context); + var bytes = new byte[MemoryBytes]; + Assert.True(memory.TryRead(BaseAddress, bytes)); + return new(result, context[CpuRegister.Rax], context.GuestCallbackDeclined, scheduler.Requests.ToArray(), bytes); + } + finally + { + AgcExports.CoalesceShRegisterRuns = previousCoalesce; + GuestThreadExecution.Scheduler = previousScheduler; + } + } + + private static void WriteUInt32(FakeCpuMemory memory, ulong address, uint value) + { + Span bytes = stackalloc byte[sizeof(uint)]; + BinaryPrimitives.WriteUInt32LittleEndian(bytes, value); + Assert.True(memory.TryWrite(address, bytes)); + } + + private static void WriteUInt64(FakeCpuMemory memory, ulong address, ulong value) + { + Span bytes = stackalloc byte[sizeof(ulong)]; + BinaryPrimitives.WriteUInt64LittleEndian(bytes, value); + Assert.True(memory.TryWrite(address, bytes)); + } + + // The buffer's full callback: records the dwords asked for and hands over a fresh 0x400-byte + // block each time, as a guest's chaining callback would. + private sealed class SpaceCallbackScheduler(FakeCpuMemory memory) : IGuestThreadScheduler + { + public List Requests { get; } = []; + public bool SupportsGuestContextTransfer => false; + + public bool TryCallGuestFunction(CpuContext callerContext, ulong entryPoint, ulong bufferAddress, + ulong requiredDwords, ulong userData, ulong stackAddress, ulong stackSize, string reason, + out ulong returnValue, out string? error) + { + Assert.Equal(0x1234UL, entryPoint); + Assert.Equal(CommandBuffer, bufferAddress); + Assert.Equal(0x5678UL, userData); + var block = CallbackSpace + (ulong)Requests.Count * 0x400; + Requests.Add((uint)requiredDwords); + WriteUInt64(memory, CommandBuffer + 0x10, block); + WriteUInt64(memory, CommandBuffer + 0x18, block + 0x400); + returnValue = 0; + error = null; + return true; + } + + public void RegisterGuestThreadContext(ulong threadHandle, CpuContext context) => throw new NotSupportedException(); + public bool TryStartThread(CpuContext creatorContext, GuestThreadStartRequest request, out string? error) => throw new NotSupportedException(); + public bool TryJoinThread(CpuContext callerContext, ulong threadHandle, out ulong returnValue, out string? error) => throw new NotSupportedException(); + public void Pump(CpuContext callerContext, string reason) => throw new NotSupportedException(); + public int WakeBlockedThreads(string wakeKey, int maxCount = int.MaxValue) => throw new NotSupportedException(); + public bool HasPendingGuestExceptionForCurrentThread() => false; + public bool TrySetGuestThreadPriority(ulong guestThreadHandle, int guestPriority) => throw new NotSupportedException(); + public bool TrySetGuestThreadAffinity(ulong guestThreadHandle, ulong affinityMask) => throw new NotSupportedException(); + public IReadOnlyList SnapshotThreads() => throw new NotSupportedException(); + public bool TryCallGuestFunction(CpuContext callerContext, ulong entryPoint, ulong firstArgument, ulong secondArgument, + ulong stackAddress, ulong stackSize, string reason, out string? error) => throw new NotSupportedException(); + public bool TryCallGuestFunction(CpuContext callerContext, ulong entryPoint, ulong firstArgument, ulong secondArgument, + ulong thirdArgument, ulong fourthArgument, ulong stackAddress, ulong stackSize, string reason, + out ulong returnValue, out string? error) => throw new NotSupportedException(); + public bool TryCallGuestContinuation(CpuContext callerContext, GuestCpuContinuation continuation, string reason, + out string? error) => throw new NotSupportedException(); + public bool TryRaiseGuestException(CpuContext callerContext, ulong threadHandle, ulong handler, int exceptionType, + out string? error) => throw new NotSupportedException(); + } +} From cbb304bcb2fff877d7d4422955212747c50bf640 Mon Sep 17 00:00:00 2001 From: kuba Date: Sun, 15 Nov 2026 06:03:13 +0000 Subject: [PATCH 021/178] [Metal] Count why held label copies land and what barrier each landing pays label_land, label_batch, label_barrier, label_mix, label_force_by, label_force_range and label_in_encoder_refused on the WAITS line. The landing cause is passed through OrderAfterDeferredCopies and kept with _landDeferredLabels; held copies carry their kind (command-processor write, end-of-pipe label, other). No behaviour change. --- .../V2/MetalCommandStream.cs | 44 +++-- .../V2/MetalRenderHost.DepthOnlyJoin.cs | 5 +- .../V2/MetalRenderHost.GdsTransfers.cs | 4 +- .../V2/MetalRenderHost.KernelFills.cs | 2 +- .../V2/MetalRenderHost.LabelLanding.cs | 186 ++++++++++++++++++ .../V2/MetalRenderHost.Rendering.cs | 6 +- .../V2/MetalRenderHost.StagedStorage.cs | 10 +- .../V2/MetalRenderHost.SubsetJoin.cs | 2 +- .../V2/MetalRenderHost.ThreadDispatch.cs | 2 +- .../SharpEmu.Gpu.Metal/V2/MetalRenderHost.cs | 18 +- 10 files changed, 247 insertions(+), 32 deletions(-) create mode 100644 src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.LabelLanding.cs diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalCommandStream.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalCommandStream.cs index 1edfa9eca..74d9554a3 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalCommandStream.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalCommandStream.cs @@ -930,7 +930,7 @@ private bool TryEncodeEndOfPipeLabel(in EndOfPipeWrite write) var copy = new DeferredLabelCopy( staging.Buffer, staging.Offset, destination.Buffer, destination.Offset, bytes, write.Destination, - CpuVisible: !LabelBarrierByCacheAction || WritesBackForCpu(write.Kind)); + CpuVisible: !LabelBarrierByCacheAction || WritesBackForCpu(write.Kind), Kind: LabelCopyKind.EndOfPipe); var serial = EncodeOrderedCopy(in copy, write.Destination, CommandProcessorWriteHistory.Enabled ? GpuClobberDiagnostics.LandedKind(write.Kind) : null, bytes == sizeof(uint) ? (uint)write.Value : write.Value, @@ -1048,7 +1048,7 @@ private ulong EncodeOrderedCopies( // A copy that cannot wait lands after the held ones: copies land in stream order. if (LabelsAtCommit && _deferredLabelCopies.Count != 0) { - OrderAfterDeferredCopies(0, ulong.MaxValue); + OrderAfterDeferredCopies(0, ulong.MaxValue, LabelLandCause.CannotWait); } var context = ((IMetalImageCacheOwner)this).BeginTransfer(MetalTransferCause.EndOfPipeLabel); @@ -1286,7 +1286,8 @@ private bool TryEncodeCommandProcessorWrite(ulong address, ReadOnlySpan so source.CopyTo(payload); var copy = new DeferredLabelCopy( - staging.Buffer, staging.Offset, destination.Buffer, destination.Offset, source.Length, address); + staging.Buffer, staging.Offset, destination.Buffer, destination.Offset, source.Length, address, + Kind: LabelCopyKind.CpWrite); var recordHistory = CommandProcessorWriteHistory.Enabled; var serial = EncodeOrderedCopy(in copy, address, recordHistory ? "landed:" + kind : null, recordHistory ? FirstValue(source) : 0, MetalGpuWriteOrigin.Copy, "cp write", kind, size); @@ -1389,7 +1390,8 @@ private bool TryEncodeCommandProcessorQwords(ulong address, int count, ulong str } copies[index] = new DeferredLabelCopy( - 0, 0, destination.Buffer, destination.Offset, sizeof(ulong), address + (ulong)index * strideBytes); + 0, 0, destination.Buffer, destination.Offset, sizeof(ulong), address + (ulong)index * strideBytes, + Kind: LabelCopyKind.CpWrite); } var staging = _guestMemory.Allocate((ulong)count * sizeof(ulong), sizeof(ulong), out var payload); @@ -1620,7 +1622,8 @@ private readonly record struct DeferredLabelCopy( ulong DestinationOffset, int Bytes, ulong GuestAddress, - bool CpuVisible = true); + bool CpuVisible = true, + LabelCopyKind Kind = LabelCopyKind.Other); private readonly List _deferredLabelCopies = []; private bool _encodingDeferredLabels; @@ -1802,10 +1805,12 @@ private void EncodeLabelBarrier(nint commandBuffer, ReadOnlySpan - internal void OrderAfterDeferredCopies(ulong address, ulong size) + internal void OrderAfterDeferredCopies(ulong address, ulong size, LabelLandCause cause = LabelLandCause.Other) { // A fill the open pass holds is ordered the same way (MetalRenderHost.DeferredFills.cs). LandDeferredFillsOver(address, size); + _labelTouchClass = -1; if (_deferredLabelCopies.Count == 0 || (_computeEncoder == 0 && !LabelsAtCommit) || (size != ulong.MaxValue && !DeferredLabelCopiesTouch(address, size))) { return; } + if (size != ulong.MaxValue) + { + NoteLabelForce(size); + } + // Held to the commit, a copy whose bytes this work binds lands here instead: the work // reads or writes them, and must see the copy, or overwrite it, in stream order. _landDeferredLabels = true; + _labelLandCause = cause; if (_computeEncoder != 0 || _renderEncoder != 0) { EndEncoders(PassEndCause.Other); @@ -2079,10 +2092,17 @@ internal void OrderAfterDeferredCopies(ulong address, ulong size) EncodeDeferredLabelCopies(); } - private void EncodeDeferredLabelCopies() + // boundary: what the landing is counted as when no site asked for it (copies held to encoder boundaries). + private void EncodeDeferredLabelCopies(LabelLandCause boundary = LabelLandCause.Other) { - if (_deferredLabelCopies.Count == 0 || _encodingDeferredLabels) + if (_encodingDeferredLabels) + { + return; + } + + if (_deferredLabelCopies.Count == 0) { + _labelLandCause = LabelLandCause.None; return; } @@ -2092,14 +2112,16 @@ private void EncodeDeferredLabelCopies() } _landDeferredLabels = false; + var cause = _labelLandCause == LabelLandCause.None ? boundary : _labelLandCause; + _labelLandCause = LabelLandCause.None; _encodingDeferredLabels = true; try { var copies = _deferredLabelCopies.Count; - EncodeLabelCopies( - EnsureCommandBuffer(), - System.Runtime.InteropServices.CollectionsMarshal.AsSpan(_deferredLabelCopies)); + var held = System.Runtime.InteropServices.CollectionsMarshal.AsSpan(_deferredLabelCopies); + NoteLabelLanding(held, cause); + EncodeLabelCopies(EnsureCommandBuffer(), held); ClearHeldLabelCopies(); // The barrier and the blit encoder are gap the pass profile cannot sample. if (PassProfileEnabled) diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.DepthOnlyJoin.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.DepthOnlyJoin.cs index 93acae32a..e6d04e30a 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.DepthOnlyJoin.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.DepthOnlyJoin.cs @@ -105,7 +105,7 @@ private bool TryJoinDepthOnly(in RenderingState state, MetalPipelineEntry? upcom if (_deferredLabelCopies.Count != 0 && BindsDeferredCopyDestination()) { // The pass this begins is the boundary the copies land at, even when they wait for the commit. - _landDeferredLabels = true; + RequestLabelLanding(LabelLandCause.Join); _depthOnlyJoinsDeferredCopies++; return false; } @@ -197,7 +197,8 @@ internal void BeginDeviceRangeOrdering(MetalStageBindings stage) /// A range the stage's device-address program reaches, ordered after the held copies over it. internal void OrderDeviceRange(MetalStageBindings stage, ulong address, ulong size) { - OrderAfterDeferredCopies(address, size); + OrderAfterDeferredCopies(address, size, + size == ulong.MaxValue ? LabelLandCause.DaUnplanned : LabelLandCause.DaPlanned); if (stage.DeviceRangeCount == stage.DeviceRanges.Length) { Array.Resize(ref stage.DeviceRanges, Math.Max(4, stage.DeviceRanges.Length * 2)); diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.GdsTransfers.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.GdsTransfers.cs index f5e2aa255..fef2e6365 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.GdsTransfers.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.GdsTransfers.cs @@ -103,7 +103,7 @@ private bool TryCopyGdsOnGpu(ulong destination, ulong source, ulong size, bool d } FlushGpuWrites(source, size, MetalWritebackCause.GuestCopy); - OrderAfterDeferredCopies(source, size); + OrderAfterDeferredCopies(source, size, LabelLandCause.Transfer); (sourceBuffer, sourceOffset, destinationBuffer, destinationOffset) = (origin.Buffer, origin.Offset, gds, destination); } else @@ -114,7 +114,7 @@ private bool TryCopyGdsOnGpu(ulong destination, ulong source, ulong size, bool d return false; } - OrderAfterDeferredCopies(destination, size); + OrderAfterDeferredCopies(destination, size, LabelLandCause.Transfer); (sourceBuffer, sourceOffset, destinationBuffer, destinationOffset) = (gds, source, target.Buffer, target.Offset); } diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.KernelFills.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.KernelFills.cs index f9f5c3a30..587b90bc7 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.KernelFills.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.KernelFills.cs @@ -510,7 +510,7 @@ private void EncodeDestinationBefore(KernelCopyCheck check) return; } - OrderAfterDeferredCopies(check.Destination, size); + OrderAfterDeferredCopies(check.Destination, size, LabelLandCause.Transfer); OrderAfterStagedStores(check.Destination, size); var context = ((IMetalImageCacheOwner)this).BeginTransfer(MetalTransferCause.GuestCopy); var encoder = MetalNative.Send(context.CommandBuffer, SelBlitEncoder); diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.LabelLanding.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.LabelLanding.cs new file mode 100644 index 000000000..07aa13ec9 --- /dev/null +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.LabelLanding.cs @@ -0,0 +1,186 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +namespace SharpEmu.Gpu.Metal.V2; + +/// +/// Why held label copies landed, and what they were, for the WAITS line: the counts that say +/// which landings the frame could do without and which barrier each one paid. +/// +/// +/// label_land what landed the held copies: the commit, a storage binding that reads or writes them, a planned or +/// unplanned device-address range, indirect arguments, a persistent-thread kernel, a staged gather, a +/// join, a transfer, a copy that could not wait, a compute encoder opening, the image cache, other. +/// label_batch copies per landing. +/// label_barrier what ordered the landing: a shared event, a device-only event, the encoder fence alone, or a +/// dispatch inside the open compute encoder. +/// label_mix the landed copies: command-processor writes, causal ones, CPU-visible and device-only end-of-pipe +/// labels, and the rest (GDS stores, occlusion dumps). +/// label_force_by the first held copy a forcing range overlapped, and label_force_range that range's size. +/// label_in_encoder_refused why a landing with a compute encoder open did not fold into it. +/// +internal sealed partial class MetalRenderHost +{ + internal enum LabelLandCause : byte + { + None, + Commit, + BindRead, + BindWritten, + DaPlanned, + DaUnplanned, + Indirect, + Persistent, + Gather, + Join, + Transfer, + CannotWait, + EnsureCompute, + Image, + Other, + } + + // What a held copy is: it decides whether the copy needs the shared event (CpuVisible) and is counted by label_mix. + private enum LabelCopyKind : byte + { + Other, + CpWrite, + CpCausal, + EndOfPipe, + } + + private static readonly string[] LabelLandNames = + ["commit", "bind_read", "bind_written", "da_planned", "da_unplanned", "indirect", "persistent", "gather", "join", + "transfer", "cannot_wait", "ensure_compute", "image", "other"]; + + private static readonly string[] LabelBatchNames = ["1", "2-5", "6-15", "16+"]; + private static readonly string[] LabelBarrierNames = ["shared", "device", "fence_only", "in_encoder"]; + private static readonly string[] LabelMixNames = ["cp", "cp_causal", "eop_cpu", "eop_dev", "other"]; + private static readonly string[] LabelForceByNames = ["cp", "eop_cpu", "eop_dev", "other"]; + private static readonly string[] LabelForceRangeNames = ["<64K", "<16M", "<1G", ">=1G"]; + private static readonly string[] LabelRefusedNames = ["occlusion", "scatter", "no_fence", "staged"]; + + private const int BarrierKindShared = 0, BarrierKindDevice = 1, BarrierKindFenceOnly = 2, BarrierKindInEncoder = 3; + + private readonly long[] _labelLand = new long[LabelLandNames.Length]; + private readonly long[] _labelBatch = new long[LabelBatchNames.Length]; + private readonly long[] _labelBarrierKinds = new long[LabelBarrierNames.Length]; + private readonly long[] _labelMix = new long[LabelMixNames.Length]; + private readonly long[] _labelForceBy = new long[LabelForceByNames.Length]; + private readonly long[] _labelForceRange = new long[LabelForceRangeNames.Length]; + private readonly long[] _labelInEncoderRefused = new long[LabelRefusedNames.Length]; + + // What asked for the held copies to land next (set with _landDeferredLabels), None for a plain boundary. + private LabelLandCause _labelLandCause; + + // The label_force_by class of the copy the last DeferredLabelCopiesTouch(address, size) found, -1 for none. + private int _labelTouchClass = -1; + + // The landing cause a site asks for with _landDeferredLabels; the first one asked keeps it until the copies land. + private void RequestLabelLanding(LabelLandCause cause) + { + _landDeferredLabels = true; + if (_labelLandCause == LabelLandCause.None) + { + _labelLandCause = cause; + } + } + + private static int LabelMixIndex(in DeferredLabelCopy copy) => copy.Kind switch + { + LabelCopyKind.CpWrite => 0, + LabelCopyKind.CpCausal => 1, + LabelCopyKind.EndOfPipe => copy.CpuVisible ? 2 : 3, + _ => 4, + }; + + private static int LabelForceIndex(in DeferredLabelCopy copy) => copy.Kind switch + { + LabelCopyKind.CpWrite or LabelCopyKind.CpCausal => 0, + LabelCopyKind.EndOfPipe => copy.CpuVisible ? 1 : 2, + _ => 3, + }; + + // A range that forced the held copies to land: the first copy it overlapped, and how wide it was. + private void NoteLabelForce(ulong size) + { + if (_labelTouchClass >= 0) + { + _labelForceBy[_labelTouchClass]++; + } + + _labelForceRange[size switch + { + < 64UL << 10 => 0, + < 16UL << 20 => 1, + < 1UL << 30 => 2, + _ => 3, + }]++; + } + + // One landing of held copies: why, how many, and what they were. + private void NoteLabelLanding(ReadOnlySpan copies, LabelLandCause cause) + { + _labelLand[(int)(cause == LabelLandCause.None ? LabelLandCause.Other : cause) - 1]++; + _labelBatch[copies.Length switch + { + 1 => 0, + <= 5 => 1, + <= 15 => 2, + _ => 3, + }]++; + foreach (ref readonly var copy in copies) + { + _labelMix[LabelMixIndex(in copy)]++; + } + } + + private string TakeLabelLandingCounters() + { + var text = new System.Text.StringBuilder(256); + Append(text, "label_land", LabelLandNames, _labelLand); + Append(text, "label_batch", LabelBatchNames, _labelBatch); + Append(text, "label_barrier", LabelBarrierNames, _labelBarrierKinds); + Append(text, "label_mix", LabelMixNames, _labelMix); + Append(text, "label_force_by", LabelForceByNames, _labelForceBy); + Append(text, "label_force_range", LabelForceRangeNames, _labelForceRange); + Append(text, "label_in_encoder_refused", LabelRefusedNames, _labelInEncoderRefused); + return text.ToString(); + + static void Append(System.Text.StringBuilder text, string field, string[] names, long[] counts) + { + text.Append(' ').Append(field).Append("=["); + for (var index = 0; index < names.Length; index++) + { + if (index != 0) text.Append(','); + text.Append(names[index]).Append(':').Append(Interlocked.Exchange(ref counts[index], 0)); + } + + text.Append(']'); + } + } + + /// Landings per cause since the last take, for tests; same order as minus None. + internal long[] TakeLabelLandCounts() + { + var counts = new long[_labelLand.Length]; + for (var index = 0; index < counts.Length; index++) counts[index] = Interlocked.Exchange(ref _labelLand[index], 0); + return counts; + } + + /// label_barrier since the last take: shared, device, fence_only, in_encoder. + internal long[] TakeLabelBarrierKinds() + { + var counts = new long[_labelBarrierKinds.Length]; + for (var index = 0; index < counts.Length; index++) counts[index] = Interlocked.Exchange(ref _labelBarrierKinds[index], 0); + return counts; + } + + /// label_in_encoder_refused since the last take: occlusion, scatter, no_fence, staged. + internal long[] TakeLabelInEncoderRefusals() + { + var counts = new long[_labelInEncoderRefused.Length]; + for (var index = 0; index < counts.Length; index++) counts[index] = Interlocked.Exchange(ref _labelInEncoderRefused[index], 0); + return counts; + } +} diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Rendering.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Rendering.cs index f581dbb7f..e34f5170d 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Rendering.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Rendering.cs @@ -1454,7 +1454,7 @@ private nint EnsureComputeEncoder(bool materializeClears) EndRendering(); EncodeStagedStores(); - EncodeDeferredLabelCopies(); + EncodeDeferredLabelCopies(LabelLandCause.EnsureCompute); } // Only the clears this dispatch can see are encoded ahead of it; the rest keep @@ -2110,7 +2110,7 @@ public void Dispatch(uint groupsX, uint groupsY, uint groupsZ) // Everything held lands ahead of such a dispatch instead. if (LabelsAtCommit && _deferredLabelCopies.Count != 0 && _pendingComputePipeline is { PersistentThreads: true }) { - OrderAfterDeferredCopies(0, ulong.MaxValue); + OrderAfterDeferredCopies(0, ulong.MaxValue, LabelLandCause.Persistent); } var encoder = EnsureComputeEncoder(); @@ -2214,7 +2214,7 @@ public bool TryDispatchIndirect(ulong argumentsAddress, ReadOnlySpan physic } // The GPU reads the group counts where the dispatch sits in the stream. - OrderAfterDeferredCopies(argumentsAddress, 3 * sizeof(uint)); + OrderAfterDeferredCopies(argumentsAddress, 3 * sizeof(uint), LabelLandCause.Indirect); TraceIndirectDispatch(argumentsAddress); var started = DrawTimingStart(); var encoder = EnsureComputeEncoder(); diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.StagedStorage.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.StagedStorage.cs index 6856510de..fd25dbacb 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.StagedStorage.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.StagedStorage.cs @@ -29,7 +29,7 @@ private MetalGuestRange ResolveStorageBuffer(ulong address, ulong size, bool wri { inPlaceAlias = 0; using var phaseScope = SharpEmu.Libs.VideoOut.RenderPhaseProfile.MeasureDetail(SharpEmu.Libs.VideoOut.RenderPhaseProfile.Phase.StorageDeferredLabels); - OrderAfterDeferredCopies(address, size); + OrderAfterDeferredCopies(address, size, written ? LabelLandCause.BindWritten : LabelLandCause.BindRead); phaseScope.SwitchPhase(SharpEmu.Libs.VideoOut.RenderPhaseProfile.Phase.StorageSharedLookup); var staged = StagedStorage; if (staged.TryShare(address, size, written, out var shared)) @@ -94,7 +94,7 @@ private MetalGuestRange ResolveStorageBuffer(ulong address, ulong size, bool wri if (gathered) { pristine = _guestMemory.Allocate(staging.Size, 256, out _); - OrderAfterDeferredCopies(address, staging.Size); + OrderAfterDeferredCopies(address, staging.Size, LabelLandCause.Gather); var context = ((IMetalImageCacheOwner)this).BeginTransfer(MetalTransferCause.GuestCopy); staged.EncodeGather(context.CommandBuffer, address, staging, pristine, context); if (context.WantsEncodedLabels) @@ -127,7 +127,7 @@ private MetalGuestRange ResolveStorageBuffer(ulong address, ulong size, bool wri // (MetalImageCache.ResolveUploadSource): the GPU copies them in from the windows, behind that work. void IMetalImageCacheOwner.GatherStagedRange(ulong address, in MetalGuestRange staging) { - OrderAfterDeferredCopies(address, staging.Size); + OrderAfterDeferredCopies(address, staging.Size, LabelLandCause.Gather); var context = ((IMetalImageCacheOwner)this).BeginTransfer(MetalTransferCause.GuestCopy); StagedStorage.EncodeGather(context.CommandBuffer, address, staging, default, context); if (context.WantsEncodedLabels) @@ -161,7 +161,7 @@ private MetalGuestRange StageWrittenOnGpu(ulong address, ulong size) } var pristine = _guestMemory.Allocate(staging.Size, 256, out _); - OrderAfterDeferredCopies(address, staging.Size); + OrderAfterDeferredCopies(address, staging.Size, LabelLandCause.Gather); var context = ((IMetalImageCacheOwner)this).BeginTransfer(MetalTransferCause.GuestCopy); if (StagedStorage.TryEncodeWholeGather(context.CommandBuffer, address, staging, pristine, context)) { @@ -329,7 +329,7 @@ private unsafe void FillStagedRange(MetalStagedRangeCache.Entry entry, MetalStag // The CPU staged what guest memory holds now. Bytes the GPU has yet to write // there are copied in by the GPU, behind that work. entry.Gathered = true; - OrderAfterDeferredCopies(entry.Address, size); + OrderAfterDeferredCopies(entry.Address, size, LabelLandCause.Gather); var context = ((IMetalImageCacheOwner)this).BeginTransfer(MetalTransferCause.GuestCopy); _stagedRanges!.Touch(entry, context.SubmissionSerial); staged.EncodeGather(context.CommandBuffer, entry.Address, entry.Staging, entry.Pristine, context); diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.SubsetJoin.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.SubsetJoin.cs index e08a9dc83..fcb6b977a 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.SubsetJoin.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.SubsetJoin.cs @@ -182,7 +182,7 @@ private bool TryJoinColorSubset(in RenderingState state, MetalPipelineEntry? upc // device-address program is checked against the ranges binding ordered. if (_deferredLabelCopies.Count != 0 && BindsDeferredCopyDestination()) { - _landDeferredLabels = true; + RequestLabelLanding(LabelLandCause.Join); return RefuseSubsetJoin("copies"); } diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.ThreadDispatch.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.ThreadDispatch.cs index 46dfcc153..f80527669 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.ThreadDispatch.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.ThreadDispatch.cs @@ -105,7 +105,7 @@ public unsafe bool TryDispatchThreadsIndirect( } // The GPU reads the thread counts where the dispatch sits in the stream. - OrderAfterDeferredCopies(argumentsAddress, 3 * sizeof(uint)); + OrderAfterDeferredCopies(argumentsAddress, 3 * sizeof(uint), LabelLandCause.Indirect); var started = DrawTimingStart(); var encoder = EnsureComputeEncoder(); var entry = _pendingComputePipeline ?? diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.cs index 69ec0a00e..f735d4524 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.cs @@ -374,7 +374,8 @@ private nint OpenCommandBuffer() } // Everything the cache and the transfers encode needs the encoders closed first. - void IMetalImageCacheOwner.LandHeldCopies(ulong address, ulong size) => OrderAfterDeferredCopies(address, size); + void IMetalImageCacheOwner.LandHeldCopies(ulong address, ulong size) => + OrderAfterDeferredCopies(address, size, LabelLandCause.Image); IMetalSubmissionContext IMetalImageCacheOwner.BeginTransfer(MetalTransferCause cause) => BeginTransferTouching(cause, 0, 0); @@ -479,7 +480,11 @@ nint IMetalSubmissionContext.TryShareComputeEncoder(ulong guestAddress, ulong si if (DeferredLabelCopiesTouch(guestAddress, size) || (_stagedStorageCopies is { Count: > 0 } staged && staged.HasRecordedStoresOver(guestAddress, size))) { - _landDeferredLabels |= DeferredLabelCopiesTouch(guestAddress, size); + if (DeferredLabelCopiesTouch(guestAddress, size)) + { + RequestLabelLanding(LabelLandCause.Transfer); + } + ((IMetalSubmissionContext)this).ReleaseSharedEncoder(); return 0; } @@ -639,7 +644,7 @@ private ulong FlushCommandBuffer(PassEndCause cause, MetalFlushCause why) } _flushCauses[(int)why]++; - _landDeferredLabels = true; + RequestLabelLanding(LabelLandCause.Commit); _passEndFlushReason = reason; EndEncoders(cause); _passEndFlushReason = null; @@ -1642,7 +1647,7 @@ public void FillGuestMemory(ulong address, ulong size, uint value, bool allowHos } // A label held for the commit over these bytes lands first, so the fill overwrites it in stream order. - OrderAfterDeferredCopies(address, size); + OrderAfterDeferredCopies(address, size, LabelLandCause.Transfer); if (TryDeferFillToPassEnd(address, size, value, in range) || TryFillInComputeEncoder(address, size, value, in range)) { @@ -1798,8 +1803,8 @@ public void CopyGuestMemory(ulong destination, ulong source, ulong size, bool al FlushGpuWrites(source, size, MetalWritebackCause.GuestCopy); // A label held for the commit over the source or the destination lands first, as a boundary used to land it. - OrderAfterDeferredCopies(source, size); - OrderAfterDeferredCopies(destination, size); + OrderAfterDeferredCopies(source, size, LabelLandCause.Transfer); + OrderAfterDeferredCopies(destination, size, LabelLandCause.Transfer); if (TryCopyInComputeEncoder(destination, source, size, in target, in origin)) { _imageCache.InvalidateMemoryFromGpu(destination, size); @@ -2846,6 +2851,7 @@ public void ReportCounters() .Append(" scheduled_labels=").Append(TakeScheduledLabelSubmissions()) .Append(" keep_warm=").Append(Interlocked.Exchange(ref _keepWarmSubmissions, 0)) .Append(" label_barriers=").Append(TakeLabelBarriers()) + .Append(TakeLabelLandingCounters()) .Append(" encoder_barriers=").Append(TakeEncoderBarriers()) .Append(" residency_skipped=").Append(TakeSkippedResidencyCalls()) .Append(TakeResidencyNameCounters()) From 86235c6852475dc599220a61eca6fd7c476a59da Mon Sep 17 00:00:00 2001 From: kuba Date: Sun, 15 Nov 2026 06:03:13 +0000 Subject: [PATCH 022/178] [Tests] Benchmark the GPU cost of what a label landing puts between two dispatches SHARPEMU_LABEL_SEPARATOR_BENCH_OUTPUT: 200 pairs of tiny dispatches separated by nothing, an encoder split, a split with a blit, a device event, a shared event, or a word-copy dispatch inside the open encoder. M4: 0 / 21 / 50 / 46 / 111 / 0.8 us per pair. --- .../MetalEndOfPipeOrderTests.NonDrawBench.cs | 181 ++++++++++++++++++ 1 file changed, 181 insertions(+) diff --git a/tests/SharpEmu.Gpu.Metal.Tests/MetalEndOfPipeOrderTests.NonDrawBench.cs b/tests/SharpEmu.Gpu.Metal.Tests/MetalEndOfPipeOrderTests.NonDrawBench.cs index 57e19a6a3..a524121d6 100644 --- a/tests/SharpEmu.Gpu.Metal.Tests/MetalEndOfPipeOrderTests.NonDrawBench.cs +++ b/tests/SharpEmu.Gpu.Metal.Tests/MetalEndOfPipeOrderTests.NonDrawBench.cs @@ -116,4 +116,185 @@ void Measure(string name, bool computeOpen, Action call) architecture = System.Runtime.InteropServices.RuntimeInformation.ProcessArchitecture.ToString(), results }, new JsonSerializerOptions { WriteIndented = true })); } + + // SHARPEMU_LABEL_SEPARATOR_BENCH_OUTPUT=: the GPU time of 200 pairs of tiny dispatches with each thing a + // held-copy landing can put between the two of a pair: nothing, an encoder split (the fence chain), a split with a + // blit encoder, the same with a device-only event before the blit, with a shared event, and a word-copy dispatch + // inside the open encoder between two memory barriers. One command buffer per case, GPUStartTime to GPUEndTime, + // cases interleaved per round; per pair is the case's time over 200, and the separator's cost is that minus the + // case with nothing. + [Fact] + public void MeasureLabelSeparatorsWhenRequested() + { + var path = Environment.GetEnvironmentVariable("SHARPEMU_LABEL_SEPARATOR_BENCH_OUTPUT"); + if (path is null || !RequireDevice()) return; + const int pairs = 200; + const int rounds = 13; + const int warmup = 3; + var device = Device.Value; + var pool = SharpEmu.Gpu.Metal.MetalNative.objc_autoreleasePoolPush(); + try + { + var queue = MetalNative.Send(device, MetalNative.Selector("newCommandQueue")); + var tick = SeparatorBenchPipeline(device, + "kernel void bench(device uint* words [[buffer(0)]], uint index [[thread_position_in_grid]]) { words[index] += 1u; }"); + var copy = SeparatorBenchPipeline(device, + "kernel void bench(device const uint* source [[buffer(0)]], device uint* destination [[buffer(1)]], " + + "uint index [[thread_position_in_grid]]) { if (index < 2u) destination[index] = source[index]; }"); + var selNewBuffer = MetalNative.Selector("newBufferWithLength:options:"); + var words = MetalNative.SendNewBuffer(device, selNewBuffer, 4096, 0); + var staging = MetalNative.SendNewBuffer(device, selNewBuffer, 4096, 0); + var labels = MetalNative.SendNewBuffer(device, selNewBuffer, 4096, 0); + var fence = MetalNative.Send(device, MetalNative.Selector("newFence")); + var selCommandBuffer = MetalNative.Selector("commandBuffer"); + var selCompute = MetalNative.Selector("computeCommandEncoder"); + var selBlit = MetalNative.Selector("blitCommandEncoder"); + var selPipeline = MetalNative.Selector("setComputePipelineState:"); + var selSetBuffer = MetalNative.Selector("setBuffer:offset:atIndex:"); + var selDispatch = MetalNative.Selector("dispatchThreadgroups:threadsPerThreadgroup:"); + var selWaitFence = MetalNative.Selector("waitForFence:"); + var selUpdateFence = MetalNative.Selector("updateFence:"); + var selEnd = MetalNative.Selector("endEncoding"); + var selCopy = MetalNative.Selector("copyFromBuffer:sourceOffset:toBuffer:destinationOffset:size:"); + var selSignal = MetalNative.Selector("encodeSignalEvent:value:"); + var selWait = MetalNative.Selector("encodeWaitForEvent:value:"); + var selBarrier = MetalNative.Selector("memoryBarrierWithScope:"); + var selRelease = MetalNative.Selector("release"); + var group = new MtlSize { Width = 1, Height = 1, Depth = 1 }; + var threads = new MtlSize { Width = 64, Height = 1, Depth = 1 }; + string[] cases = ["none", "split", "split_blit", "device_event", "shared_event", "in_encoder"]; + var samples = cases.ToDictionary(name => name, _ => new List()); + + nint OpenCompute(nint commandBuffer) + { + var encoder = MetalNative.Send(commandBuffer, selCompute); + MetalNative.SendVoid(encoder, selWaitFence, fence); + MetalNative.SendVoid(encoder, selPipeline, tick); + MetalNative.SendSetBuffer(encoder, selSetBuffer, words, 0, 0); + return encoder; + } + + void EndCompute(nint encoder) + { + MetalNative.SendVoid(encoder, selUpdateFence, fence); + MetalNative.SendVoid(encoder, selEnd); + } + + void Blit(nint commandBuffer) + { + var blit = MetalNative.Send(commandBuffer, selBlit); + MetalNative.SendVoid(blit, selWaitFence, fence); + MetalNative.SendCopyBuffer(blit, selCopy, staging, 0, labels, 0, 8); + MetalNative.SendVoid(blit, selUpdateFence, fence); + MetalNative.SendVoid(blit, selEnd); + } + + for (var round = 0; round < rounds; round++) + { + for (var which = 0; which < cases.Length; which++) + { + var name = cases[(which + round) % cases.Length]; + var commandBuffer = MetalNative.Send(queue, selCommandBuffer); + var @event = name switch + { + "device_event" => MetalNative.Send(device, MetalNative.Selector("newEvent")), + "shared_event" => MetalNative.Send(device, MetalNative.Selector("newSharedEvent")), + _ => 0, + }; + var value = 0UL; + var encoder = OpenCompute(commandBuffer); + for (var pair = 0; pair < pairs; pair++) + { + MetalNative.SendDispatch(encoder, selDispatch, group, threads); + switch (name) + { + case "none": + break; + case "in_encoder": + SharpEmu.Gpu.Metal.V2.MetalV2Native.SendMemoryBarrierScope(encoder, selBarrier, SharpEmu.Gpu.Metal.V2.Mtl.BarrierScopeBuffers); + MetalNative.SendVoid(encoder, selPipeline, copy); + MetalNative.SendSetBuffer(encoder, selSetBuffer, staging, 0, 0); + MetalNative.SendSetBuffer(encoder, selSetBuffer, labels, 0, 1); + MetalNative.SendDispatch(encoder, selDispatch, group, threads); + SharpEmu.Gpu.Metal.V2.MetalV2Native.SendMemoryBarrierScope(encoder, selBarrier, SharpEmu.Gpu.Metal.V2.Mtl.BarrierScopeBuffers); + MetalNative.SendVoid(encoder, selPipeline, tick); + MetalNative.SendSetBuffer(encoder, selSetBuffer, words, 0, 0); + break; + default: + EndCompute(encoder); + if (@event != 0) + { + value++; + SharpEmu.Gpu.Metal.V2.MetalV2Native.SendEventValue(commandBuffer, selSignal, @event, value); + SharpEmu.Gpu.Metal.V2.MetalV2Native.SendEventValue(commandBuffer, selWait, @event, value); + } + + if (name != "split") + { + Blit(commandBuffer); + } + + encoder = OpenCompute(commandBuffer); + break; + } + + MetalNative.SendDispatch(encoder, selDispatch, group, threads); + } + + EndCompute(encoder); + MetalNative.SendVoid(commandBuffer, MetalNative.Selector("commit")); + MetalNative.SendVoid(commandBuffer, MetalNative.Selector("waitUntilCompleted")); + Assert.Equal(4u, (uint)MetalNative.SendUInteger(commandBuffer, MetalNative.Selector("status"))); + var elapsed = MetalNative.SendDouble(commandBuffer, MetalNative.Selector("GPUEndTime")) - + MetalNative.SendDouble(commandBuffer, MetalNative.Selector("GPUStartTime")); + if (@event != 0) MetalNative.SendVoid(@event, selRelease); + if (round >= warmup) samples[name].Add(elapsed * 1e6 / pairs); + } + } + + var none = Median(samples["none"]); + var results = cases.Select(name => new + { + name, + microsecondsPerPairMedian = Median(samples[name]), + microsecondsPerPairBest = samples[name].Min(), + separatorMicroseconds = Median(samples[name]) - none, + }).ToList(); + foreach (var result in results) + { + output.WriteLine($"SEPARATOR {result.name}: {result.microsecondsPerPairMedian:F2} us/pair " + + $"(best {result.microsecondsPerPairBest:F2}), separator {result.separatorMicroseconds:F2} us"); + } + + File.WriteAllText(path, JsonSerializer.Serialize(new { + architecture = System.Runtime.InteropServices.RuntimeInformation.ProcessArchitecture.ToString(), pairs, + rounds = rounds - warmup, results }, new JsonSerializerOptions { WriteIndented = true })); + foreach (var handle in new[] { words, staging, labels, fence, tick, copy, queue }) MetalNative.SendVoid(handle, selRelease); + } + finally + { + SharpEmu.Gpu.Metal.MetalNative.objc_autoreleasePoolPop(pool); + } + + static double Median(List values) + { + var sorted = values.Order().ToList(); + return sorted[sorted.Count / 2]; + } + } + + private static nint SeparatorBenchPipeline(nint device, string body) + { + var options = MetalNative.Send(MetalNative.Send(MetalNative.Class("MTLCompileOptions"), MetalNative.Selector("alloc")), MetalNative.Selector("init")); + MetalNative.ApplyMslCompileOptions(options); + nint error = 0; + var library = MetalNative.Send(device, MetalNative.Selector("newLibraryWithSource:options:error:"), + MetalNative.NsString("#include \nusing namespace metal;\n" + body), options, ref error); + Assert.True(library != 0, MetalNative.DescribeError(error)); + var function = MetalNative.Send(library, MetalNative.Selector("newFunctionWithName:"), MetalNative.NsString("bench")); + nint pipelineError = 0; + var pipeline = MetalNative.Send(device, MetalNative.Selector("newComputePipelineStateWithFunction:error:"), function, ref pipelineError); + Assert.True(pipeline != 0, MetalNative.DescribeError(pipelineError)); + return pipeline; + } } From d8242a8201bd7a828cc7ef56a7c3a881d7353147 Mon Sep 17 00:00:00 2001 From: kuba Date: Sun, 15 Nov 2026 06:03:19 +0000 Subject: [PATCH 023/178] [Metal] Count meshlet rebuilds by reason, split build time, trace builds Step 0 of the meshlet cache plan, diagnostics only: meshlet_builds_by (new, changed, recurring against the key's last 8 hashes, kept past removal), meshlet_hash_kb, meshlet_build_kb, meshlet_build_split_ms (read, build, alloc), meshlet_entries and meshlet_evictions on the PERF line; SHARPEMU_METAL_MESHLET_TRACE=1 prints the first 200 builds. --- .../V2/MetalMeshletCache.cs | 130 +++++++++++++++++- .../MetalMeshletCacheTests.cs | 130 ++++++++++++++++++ 2 files changed, 258 insertions(+), 2 deletions(-) create mode 100644 tests/SharpEmu.Gpu.Metal.Tests/MetalMeshletCacheTests.cs diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalMeshletCache.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalMeshletCache.cs index 6b0f57dca..ccdb29206 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalMeshletCache.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalMeshletCache.cs @@ -228,6 +228,15 @@ public enum Fallback OverBudget, } + /// Why a build ran: the key was never seen (or its history was cleared), the bytes hash + /// to a value the key has not had in its last builds, or to one it has. + public enum BuildReason + { + New, + Changed, + Recurring, + } + public readonly record struct Meshlets(nint Buffer, uint Count, uint VertexBase, uint PrimitiveBase); private readonly record struct Key( @@ -247,9 +256,47 @@ private sealed class Entry public ulong LastUsedTick; } + // The hashes each key was built from, newest last, kept past the entry's removal so a rebuild + // can tell content the key had before from content it never had. Diagnostic only. + private sealed class HashRing + { + private readonly ulong[] _hashes = new ulong[HashHistoryDepth]; + private int _count; + private int _next; + + public bool Contains(ulong hash) + { + for (var i = 0; i < _count; i++) + { + if (_hashes[i] == hash) + { + return true; + } + } + + return false; + } + + public void Add(ulong hash) + { + _hashes[_next] = hash; + _next = (_next + 1) % HashHistoryDepth; + _count = Math.Min(_count + 1, HashHistoryDepth); + } + } + + private const int HashHistoryDepth = 8; + private const int HashHistoryKeyLimit = 4096; + private const int TraceLineLimit = 200; + private static readonly bool Disabled = Environment.GetEnvironmentVariable("SHARPEMU_METAL_MESHLETS") == "0"; + // SHARPEMU_METAL_MESHLET_TRACE=1 prints one [METAL-V2][MESHLET] build line per build, the first + // TraceLineLimit of them: address, index count and width, reason, old and new hash, serial. + private static readonly bool TraceBuilds = + Environment.GetEnvironmentVariable("SHARPEMU_METAL_MESHLET_TRACE") == "1"; + private readonly MetalGuestMemory _guestMemory; private readonly ICpuMemory _memory; private readonly Dictionary _entries = []; @@ -258,6 +305,8 @@ private sealed class Entry private readonly System.IO.Hashing.XxHash3 _hasher = new(); private uint[] _indices = []; private readonly List<(nint Buffer, ulong Serial)> _retired = []; + private readonly Dictionary _history = []; + private int _traceLines; private ulong _bytes; private ulong _tick; @@ -267,6 +316,13 @@ private sealed class Entry private long _hashTicks; private long _builds; private long _validationsSkipped; + private readonly long[] _buildsBy = new long[Enum.GetValues().Length]; + private long _hashBytes; + private long _buildBytes; + private long _readTicks; + private long _builderTicks; + private long _allocTicks; + private long _evictions; public MetalMeshletCache(MetalGuestMemory guestMemory, ICpuMemory memory) { @@ -318,7 +374,9 @@ public bool TryGet( } _hashTicks += System.Diagnostics.Stopwatch.GetTimestamp() - hashStarted; + _hashBytes += (long)rangeBytes; + var oldHash = 0UL; if (_entries.TryGetValue(key, out var entry)) { if (entry.Hash == hash) @@ -330,6 +388,7 @@ public bool TryGet( return true; } + oldHash = entry.Hash; Remove(key, entry); } @@ -367,8 +426,10 @@ public bool TryGet( } } + var readDone = System.Diagnostics.Stopwatch.GetTimestamp(); var built = _scratch; MeshletBuilder.BuildInto(indices, maxVertices, maxPrimitives, built); + var builderDone = System.Diagnostics.Stopwatch.GetTimestamp(); var wordCount = built.WordCount; var size = (ulong)wordCount * sizeof(uint); if (!MakeRoom(size, completedSerial)) @@ -398,13 +459,63 @@ public bool TryGet( _entries[key] = entry; _bytes += size; Touch(entry, submissionSerial); - _buildTicks += System.Diagnostics.Stopwatch.GetTimestamp() - buildStarted; + var buildDone = System.Diagnostics.Stopwatch.GetTimestamp(); + _buildTicks += buildDone - buildStarted; + _readTicks += readDone - buildStarted; + _builderTicks += builderDone - readDone; + _allocTicks += buildDone - builderDone; + _buildBytes += (long)rangeBytes; + NoteBuild(key, hash, oldHash, submissionSerial); _builds++; _draws++; meshlets = new Meshlets(buffer, entry.Count, entry.VertexBase, entry.PrimitiveBase); return true; } + // Counts the build by reason (and traces it) against the key's hash history. + private void NoteBuild(Key key, ulong hash, ulong oldHash, ulong serial) + { + BuildReason reason; + if (!_history.TryGetValue(key, out var ring)) + { + if (_history.Count >= HashHistoryKeyLimit) + { + _history.Clear(); + } + + ring = new HashRing(); + _history[key] = ring; + reason = BuildReason.New; + } + else + { + reason = ring.Contains(hash) ? BuildReason.Recurring : BuildReason.Changed; + } + + if (reason != BuildReason.Recurring) + { + ring.Add(hash); + } + + _buildsBy[(int)reason]++; + if (TraceBuilds && _traceLines < TraceLineLimit) + { + _traceLines++; + Console.Error.WriteLine( + $"[METAL-V2][MESHLET] build address=0x{key.Address:X} count={key.IndexCount} bits={(key.Index32 ? 32 : 16)} " + + $"reason={reason.ToString().ToLowerInvariant()} old_hash=0x{oldHash:X16} new_hash=0x{hash:X16} serial={serial}"); + } + } + + /// Builds counted in this window for . + internal long Builds(BuildReason reason) => _buildsBy[(int)reason]; + + /// Entries evicted for room in this window. + internal long Evictions => _evictions; + + /// Live entries. + internal int EntryCount => _entries.Count; + private void Touch(Entry entry, ulong serial) { entry.LastUsedSerial = serial; @@ -461,6 +572,7 @@ private bool MakeRoom(ulong size, ulong completedSerial) } Remove(victimKey!.Value, victim); + _evictions++; } return true; @@ -496,13 +608,27 @@ public string TakeCounters() $"meshlet_draws={_draws} meshlet_validations_skipped={_validationsSkipped} meshlet_builds={_builds} meshlet_mb={_bytes / (1024 * 1024)} " + $"meshlet_build_ms={(_buildTicks * 1000.0 / frequency).ToString("F1", culture)} " + $"meshlet_hash_ms={(_hashTicks * 1000.0 / frequency).ToString("F1", culture)} " + - $"meshlet_fallbacks={string.Join('/', _fallbacks)}"; + $"meshlet_fallbacks={string.Join('/', _fallbacks)} " + + $"meshlet_builds_by=[new={_buildsBy[(int)BuildReason.New]} changed={_buildsBy[(int)BuildReason.Changed]} " + + $"recurring={_buildsBy[(int)BuildReason.Recurring]}] " + + $"meshlet_hash_kb={_hashBytes / 1024} meshlet_build_kb={_buildBytes / 1024} " + + $"meshlet_build_split_ms=[read={Ms(_readTicks)} build={Ms(_builderTicks)} alloc={Ms(_allocTicks)}] " + + $"meshlet_entries={_entries.Count} meshlet_evictions={_evictions}"; _draws = 0; _builds = 0; _validationsSkipped = 0; _buildTicks = 0; _hashTicks = 0; Array.Clear(_fallbacks); + Array.Clear(_buildsBy); + _hashBytes = 0; + _buildBytes = 0; + _readTicks = 0; + _builderTicks = 0; + _allocTicks = 0; + _evictions = 0; return text; + + string Ms(long ticks) => (ticks * 1000.0 / frequency).ToString("F2", culture); } } diff --git a/tests/SharpEmu.Gpu.Metal.Tests/MetalMeshletCacheTests.cs b/tests/SharpEmu.Gpu.Metal.Tests/MetalMeshletCacheTests.cs new file mode 100644 index 000000000..2af82bac0 --- /dev/null +++ b/tests/SharpEmu.Gpu.Metal.Tests/MetalMeshletCacheTests.cs @@ -0,0 +1,130 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using SharpEmu.Gpu.Metal.V2; +using Xunit; +using Xunit.Abstractions; + +namespace SharpEmu.Gpu.Metal.Tests; + +/// +/// The meshlet cache over a small guest backing: why it builds, which built meshlets it hands +/// back for the bytes at a range, and when a buffer it no longer needs can be written again. +/// Buffers come from the device, so every test is behind the exclusive device gate. +/// +public sealed unsafe class MetalMeshletCacheTests(ITestOutputHelper output) +{ + private const ulong RangeAddress = MetalGuestWindowGranuleTests.GuestBase + 0x10000; + private const uint MaxVertices = 64; + private const uint MaxPrimitives = 32; + + private static readonly Lazy Device = new(MetalNative.MTLCreateSystemDefaultDevice); + + private sealed class Rig : IDisposable + { + public readonly MetalGuestWindowGranuleTests.Backing Backing = new(); + public readonly MetalGuestMemory Memory; + public readonly MetalMeshletCache Cache; + + public Rig() + { + Memory = new MetalGuestMemory( + Device.Value, Backing, new MetalGuestWindowGranuleTests.BackingMemory(Backing), + MetalGuestWindowGranuleTests.GranuleBytes, MetalGuestWindowGranuleTests.MaxWindowBytes); + Cache = new MetalMeshletCache(Memory, new MetalGuestWindowGranuleTests.BackingMemory(Backing)); + } + + public void Write(uint[] indices, ulong address = RangeAddress) + { + var bytes = new byte[indices.Length * sizeof(uint)]; + Buffer.BlockCopy(indices, 0, bytes, 0, bytes.Length); + Assert.True(Backing.TryWriteBacking(address, bytes)); + } + + public MetalMeshletCache.Meshlets Get(uint indexCount, ulong serial, ulong completed, ulong address = RangeAddress) + { + Assert.True(Cache.TryGet(address, indexCount, true, MaxVertices, MaxPrimitives, serial, completed, out var meshlets)); + return meshlets; + } + + public void Dispose() + { + Memory.Dispose(); + Backing.Dispose(); + } + } + + // A triangle list of `triangles` triangles over a vertex pool, shaped by the seed. + private static uint[] Indices(int seed, int triangles = 300) + { + var random = new Random(seed); + var indices = new uint[triangles * 3]; + for (var i = 0; i < indices.Length; i++) + { + indices[i] = (uint)random.Next(0, 400); + } + + return indices; + } + + // The words the cache handed back, as the mesh prologue would read them. + private static uint[] Words(MetalMeshletCache.Meshlets meshlets, int triangles) + { + var contents = MetalNative.Send(meshlets.Buffer, MetalNative.Selector("contents")); + return new ReadOnlySpan((void*)contents, (int)meshlets.PrimitiveBase + triangles).ToArray(); + } + + private static void AssertBuiltFrom(uint[] indices, MetalMeshletCache.Meshlets meshlets) + { + var expected = MeshletBuilder.Build(indices, MaxVertices, MaxPrimitives); + Assert.Equal(expected.MeshletCount, meshlets.Count); + Assert.Equal(expected.VertexBase, meshlets.VertexBase); + Assert.Equal(expected.PrimitiveBase, meshlets.PrimitiveBase); + Assert.Equal(expected.Words, Words(meshlets, indices.Length / 3)); + } + + // Content A, then B, then A again at one range, each under a new submission: the first build + // finds a key it never saw, the second a hash the key never had, the third one it had. + [Fact] + public void RebuildReasonsAreCountedByKind() + { + if (!RequireDevice()) + { + return; + } + + using var rig = new Rig(); + var a = Indices(1); + var b = Indices(2); + rig.Write(a); + AssertBuiltFrom(a, rig.Get((uint)a.Length, 1, 0)); + rig.Write(b); + AssertBuiltFrom(b, rig.Get((uint)b.Length, 2, 1)); + rig.Write(a); + AssertBuiltFrom(a, rig.Get((uint)a.Length, 3, 2)); + + Assert.Equal(1, rig.Cache.Builds(MetalMeshletCache.BuildReason.New)); + Assert.Equal(1, rig.Cache.Builds(MetalMeshletCache.BuildReason.Changed)); + Assert.Equal(1, rig.Cache.Builds(MetalMeshletCache.BuildReason.Recurring)); + Assert.Equal(0, rig.Cache.Evictions); + var counters = rig.Cache.TakeCounters(); + output.WriteLine(counters); + Assert.Contains("meshlet_builds_by=[new=1 changed=1 recurring=1]", counters); + Assert.Contains("meshlet_evictions=0", counters); + Assert.Contains($"meshlet_hash_kb={3 * a.Length * sizeof(uint) / 1024}", counters); + Assert.Equal(0, rig.Cache.Builds(MetalMeshletCache.BuildReason.New)); + } + + private bool RequireDevice() + { + if (Environment.GetEnvironmentVariable("SHARPEMU_TEST_REQUIRE_DEVICE") != "1") + { + output.WriteLine("Meshlet buffers are created on the device only behind the exclusive device gate."); + return false; + } + + Assert.True(OperatingSystem.IsMacOS()); + Assert.NotEqual(0, Device.Value); + return true; + } +} From c2d5a2f7f386748952cd94c319354d5f986a6fab Mon Sep 17 00:00:00 2001 From: kuba Date: Sun, 15 Nov 2026 06:07:39 +0000 Subject: [PATCH 024/178] [Metal] Keep up to four meshlet versions per index range Step 1 of the meshlet cache plan: a key holds up to four built versions, each found again only by a full-range hash equal to the current bytes, so content that cycles through a few index patterns at one range stops rebuilding. A miss retires the least recently used version through the existing completion-guarded release; the same- submission skip returns the version that submission validated. PERF adds meshlet_version_hits (hits one version per key would have rebuilt) and meshlet_versions. SHARPEMU_METAL_MESHLET_VERSIONS=0 keeps one version per key. --- .../V2/MetalMeshletCache.cs | 133 +++++++++++++--- .../MetalMeshletCacheTests.cs | 149 +++++++++++++++++- 2 files changed, 254 insertions(+), 28 deletions(-) diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalMeshletCache.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalMeshletCache.cs index ccdb29206..552d3f3f2 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalMeshletCache.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalMeshletCache.cs @@ -209,7 +209,8 @@ private static void NextGeneration(Scratch scratch) /// /// Meshlets of the indexed triangle-list draws a non-GS mesh pipeline runs, built once per /// index range and validated against the guest bytes on every use: an index buffer the guest -/// rewrites in place hashes differently and is rebuilt. Entries live in shared Metal buffers +/// rewrites in place hashes differently and is rebuilt, unless one of the few versions the +/// range kept has that full-range hash. Entries live in shared Metal buffers /// the residency set names, under a byte budget with least-recently-used eviction of entries /// no in-flight submission can still read. /// @@ -242,8 +243,10 @@ public enum BuildReason private readonly record struct Key( ulong Address, uint IndexCount, bool Index32, uint MaxVertices, uint MaxPrimitives); + // One built version of a key's index range. private sealed class Entry { + public required Key Key; public required nint Buffer; public required nint Contents; public required ulong Bytes; @@ -256,6 +259,18 @@ private sealed class Entry public ulong LastUsedTick; } + // The versions a key holds: content that cycles through a few index patterns at one range + // (meshes taking turns in a transient slot) finds its earlier meshlets again by full-range + // hash instead of rebuilding them. Validated is the version the last hash matched or built, + // the one the same-submission skip hands back. + private sealed class Slot + { + public readonly List Versions = new(MaxVersionsPerKey); + public Entry? Validated; + } + + private const int MaxVersionsPerKey = 4; + // The hashes each key was built from, newest last, kept past the entry's removal so a rebuild // can tell content the key had before from content it never had. Diagnostic only. private sealed class HashRing @@ -297,9 +312,15 @@ public void Add(ulong hash) private static readonly bool TraceBuilds = Environment.GetEnvironmentVariable("SHARPEMU_METAL_MESHLET_TRACE") == "1"; + // SHARPEMU_METAL_MESHLET_VERSIONS=0 keeps one version per key, replaced on every change. + private static readonly int DefaultMaxVersions = + SharpEmu.ShaderCompiler.PerfSwitches.Enabled("SHARPEMU_METAL_MESHLET_VERSIONS") ? MaxVersionsPerKey : 1; + private readonly MetalGuestMemory _guestMemory; private readonly ICpuMemory _memory; - private readonly Dictionary _entries = []; + private readonly Dictionary _slots = []; + private readonly int _maxVersions; + private int _versionCount; private readonly byte[] _chunk = new byte[HashChunkBytes]; private readonly MeshletBuilder.Scratch _scratch = new(); private readonly System.IO.Hashing.XxHash3 _hasher = new(); @@ -323,11 +344,14 @@ public void Add(ulong hash) private long _builderTicks; private long _allocTicks; private long _evictions; + private long _versionHits; - public MetalMeshletCache(MetalGuestMemory guestMemory, ICpuMemory memory) + /// Versions kept per key, 1 to 4; the env setting when null. + public MetalMeshletCache(MetalGuestMemory guestMemory, ICpuMemory memory, int? maxVersions = null) { _guestMemory = guestMemory; _memory = memory; + _maxVersions = Math.Clamp(maxVersions ?? DefaultMaxVersions, 1, MaxVersionsPerKey); } public static bool IsDisabled => Disabled; @@ -357,7 +381,8 @@ public bool TryGet( // does not rewrite an index range between the draws one command buffer records, and // hashing the bytes on every use was the cost that mattered (tens of milliseconds a // frame on the worker). Ranges the GPU writes never get here. - if (_entries.TryGetValue(key, out var validated) && validated.ValidatedSerial == submissionSerial) + _slots.TryGetValue(key, out var slot); + if (slot?.Validated is { } validated && validated.ValidatedSerial == submissionSerial) { Touch(validated, submissionSerial); meshlets = new Meshlets(validated.Buffer, validated.Count, validated.VertexBase, validated.PrimitiveBase); @@ -376,20 +401,46 @@ public bool TryGet( _hashTicks += System.Diagnostics.Stopwatch.GetTimestamp() - hashStarted; _hashBytes += (long)rangeBytes; + // Only a version built from bytes with this full-range hash is handed back. var oldHash = 0UL; - if (_entries.TryGetValue(key, out var entry)) + if (slot is not null) { - if (entry.Hash == hash) + foreach (var version in slot.Versions) { - entry.ValidatedSerial = submissionSerial; - Touch(entry, submissionSerial); - meshlets = new Meshlets(entry.Buffer, entry.Count, entry.VertexBase, entry.PrimitiveBase); + if (version.Hash != hash) + { + continue; + } + + if (version != slot.Validated) + { + // A hit one version per key would have rebuilt. + _versionHits++; + } + + slot.Validated = version; + version.ValidatedSerial = submissionSerial; + Touch(version, submissionSerial); + meshlets = new Meshlets(version.Buffer, version.Count, version.VertexBase, version.PrimitiveBase); _draws++; return true; } - oldHash = entry.Hash; - Remove(key, entry); + oldHash = slot.Validated?.Hash ?? 0; + if (slot.Versions.Count >= _maxVersions) + { + // The least recently used version makes way; it is released once its last use completes. + var oldest = slot.Versions[0]; + foreach (var version in slot.Versions) + { + if (version.LastUsedTick < oldest.LastUsedTick) + { + oldest = version; + } + } + + Remove(oldest); + } } var buildStarted = System.Diagnostics.Stopwatch.GetTimestamp(); @@ -445,8 +496,9 @@ public bool TryGet( built.CopyTo(new Span((void*)contents, wordCount)); } - entry = new Entry + var entry = new Entry { + Key = key, Buffer = buffer, Contents = contents, Bytes = size, @@ -456,7 +508,16 @@ public bool TryGet( PrimitiveBase = built.PrimitiveBase, ValidatedSerial = submissionSerial, }; - _entries[key] = entry; + // MakeRoom may have evicted the key's last version, so the slot is looked up again. + if (!_slots.TryGetValue(key, out slot)) + { + slot = new Slot(); + _slots[key] = slot; + } + + slot.Versions.Add(entry); + slot.Validated = entry; + _versionCount++; _bytes += size; Touch(entry, submissionSerial); var buildDone = System.Diagnostics.Stopwatch.GetTimestamp(); @@ -513,8 +574,17 @@ private void NoteBuild(Key key, ulong hash, ulong oldHash, ulong serial) /// Entries evicted for room in this window. internal long Evictions => _evictions; - /// Live entries. - internal int EntryCount => _entries.Count; + /// Keys with at least one live version. + internal int EntryCount => _slots.Count; + + /// Live versions over all keys. + internal int VersionCount => _versionCount; + + /// Hits in this window on a version other than the key's last validated one. + internal long VersionHits => _versionHits; + + /// Buffers removed from the cache and waiting for their last use to complete. + internal int RetiredCount => _retired.Count; private void Touch(Entry entry, ulong serial) { @@ -555,14 +625,15 @@ private bool MakeRoom(ulong size, ulong completedSerial) while (_bytes + size > BudgetBytes) { - Key? victimKey = null; Entry? victim = null; - foreach (var (key, entry) in _entries) + foreach (var slot in _slots.Values) { - if (entry.LastUsedSerial <= completedSerial && (victim is null || entry.LastUsedTick < victim.LastUsedTick)) + foreach (var entry in slot.Versions) { - victimKey = key; - victim = entry; + if (entry.LastUsedSerial <= completedSerial && (victim is null || entry.LastUsedTick < victim.LastUsedTick)) + { + victim = entry; + } } } @@ -571,7 +642,7 @@ private bool MakeRoom(ulong size, ulong completedSerial) return false; } - Remove(victimKey!.Value, victim); + Remove(victim); _evictions++; } @@ -580,9 +651,21 @@ private bool MakeRoom(ulong size, ulong completedSerial) // The buffer may still be bound by recorded work, so it is released only once the // serial it was last used under has completed. - private void Remove(Key key, Entry entry) + private void Remove(Entry entry) { - _entries.Remove(key); + var slot = _slots[entry.Key]; + slot.Versions.Remove(entry); + if (slot.Validated == entry) + { + slot.Validated = null; + } + + if (slot.Versions.Count == 0) + { + _slots.Remove(entry.Key); + } + + _versionCount--; _bytes -= entry.Bytes; _retired.Add((entry.Buffer, entry.LastUsedSerial)); } @@ -613,7 +696,8 @@ public string TakeCounters() $"recurring={_buildsBy[(int)BuildReason.Recurring]}] " + $"meshlet_hash_kb={_hashBytes / 1024} meshlet_build_kb={_buildBytes / 1024} " + $"meshlet_build_split_ms=[read={Ms(_readTicks)} build={Ms(_builderTicks)} alloc={Ms(_allocTicks)}] " + - $"meshlet_entries={_entries.Count} meshlet_evictions={_evictions}"; + $"meshlet_entries={_slots.Count} meshlet_evictions={_evictions} " + + $"meshlet_version_hits={_versionHits} meshlet_versions={_versionCount}"; _draws = 0; _builds = 0; _validationsSkipped = 0; @@ -627,6 +711,7 @@ public string TakeCounters() _builderTicks = 0; _allocTicks = 0; _evictions = 0; + _versionHits = 0; return text; string Ms(long ticks) => (ticks * 1000.0 / frequency).ToString("F2", culture); diff --git a/tests/SharpEmu.Gpu.Metal.Tests/MetalMeshletCacheTests.cs b/tests/SharpEmu.Gpu.Metal.Tests/MetalMeshletCacheTests.cs index 2af82bac0..5b0bd2c8c 100644 --- a/tests/SharpEmu.Gpu.Metal.Tests/MetalMeshletCacheTests.cs +++ b/tests/SharpEmu.Gpu.Metal.Tests/MetalMeshletCacheTests.cs @@ -26,12 +26,12 @@ private sealed class Rig : IDisposable public readonly MetalGuestMemory Memory; public readonly MetalMeshletCache Cache; - public Rig() + public Rig(int? maxVersions = null) { Memory = new MetalGuestMemory( Device.Value, Backing, new MetalGuestWindowGranuleTests.BackingMemory(Backing), MetalGuestWindowGranuleTests.GranuleBytes, MetalGuestWindowGranuleTests.MaxWindowBytes); - Cache = new MetalMeshletCache(Memory, new MetalGuestWindowGranuleTests.BackingMemory(Backing)); + Cache = new MetalMeshletCache(Memory, new MetalGuestWindowGranuleTests.BackingMemory(Backing), maxVersions); } public void Write(uint[] indices, ulong address = RangeAddress) @@ -84,7 +84,8 @@ private static void AssertBuiltFrom(uint[] indices, MetalMeshletCache.Meshlets m } // Content A, then B, then A again at one range, each under a new submission: the first build - // finds a key it never saw, the second a hash the key never had, the third one it had. + // finds a key it never saw, the second a hash the key never had, the third one it had. One + // version per key, so the third lookup builds. [Fact] public void RebuildReasonsAreCountedByKind() { @@ -93,7 +94,7 @@ public void RebuildReasonsAreCountedByKind() return; } - using var rig = new Rig(); + using var rig = new Rig(maxVersions: 1); var a = Indices(1); var b = Indices(2); rig.Write(a); @@ -115,6 +116,146 @@ public void RebuildReasonsAreCountedByKind() Assert.Equal(0, rig.Cache.Builds(MetalMeshletCache.BuildReason.New)); } + [Fact] + public void AReturningIndexPatternReusesItsEarlierMeshlets() + { + if (!RequireDevice()) + { + return; + } + + using var rig = new Rig(maxVersions: 4); + var a = Indices(1); + var b = Indices(2); + rig.Write(a); + var first = rig.Get((uint)a.Length, 1, 0); + rig.Write(b); + var second = rig.Get((uint)b.Length, 2, 1); + rig.Write(a); + var third = rig.Get((uint)a.Length, 3, 2); + + Assert.NotEqual(first.Buffer, second.Buffer); + Assert.Equal(first, third); + AssertBuiltFrom(a, third); + Assert.Equal(1, rig.Cache.VersionHits); + Assert.Equal(2, rig.Cache.VersionCount); + Assert.Equal(1, rig.Cache.EntryCount); + var counters = rig.Cache.TakeCounters(); + Assert.Contains("meshlet_builds=2 ", counters); + Assert.Contains("meshlet_version_hits=1 meshlet_versions=2", counters); + } + + // Contents cycling through and back over one range, one lookup per submission: whatever + // version is handed back holds exactly the meshlets of the bytes there now. + [Fact] + public void AChangedRangeNeverReturnsAnotherVersion() + { + if (!RequireDevice()) + { + return; + } + + using var rig = new Rig(maxVersions: 4); + var contents = Enumerable.Range(10, 6).Select(seed => Indices(seed)).ToArray(); + var order = new[] { 0, 1, 2, 0, 3, 1, 4, 5, 0, 2, 2, 5, 1, 3, 0 }; + var serial = 1UL; + foreach (var index in order) + { + rig.Write(contents[index]); + AssertBuiltFrom(contents[index], rig.Get((uint)contents[index].Length, serial, serial - 1)); + serial++; + } + + Assert.True(rig.Cache.VersionCount <= 4); + Assert.True(rig.Cache.VersionHits > 0); + } + + // Five contents at one range under submissions that have not completed: the key keeps four + // versions, and the one that made way is released only once its last submission completes. + [Fact] + public void VersionsPerKeyAreBoundedAndRetiredOnlyAfterCompletion() + { + if (!RequireDevice()) + { + return; + } + + using var rig = new Rig(maxVersions: 4); + var contents = Enumerable.Range(20, 5).Select(seed => Indices(seed)).ToArray(); + for (var index = 0; index < contents.Length; index++) + { + rig.Write(contents[index]); + rig.Get((uint)contents[index].Length, (ulong)index + 1, 0); + } + + Assert.Equal(4, rig.Cache.VersionCount); + Assert.Equal(1, rig.Cache.RetiredCount); + // Its last use was submission 1: still bound while nothing completed. + rig.Write(contents[4]); + rig.Get((uint)contents[4].Length, 6, 0); + Assert.Equal(1, rig.Cache.RetiredCount); + rig.Get((uint)contents[4].Length, 7, 1); + Assert.Equal(0, rig.Cache.RetiredCount); + + // The first content is gone and is built again; the others are still versions of the key. + rig.Write(contents[0]); + rig.Get((uint)contents[0].Length, 8, 1); + Assert.Contains("meshlet_builds=6 ", rig.Cache.TakeCounters()); + } + + [Fact] + public void TheSameSubmissionSkipReturnsTheVersionItValidated() + { + if (!RequireDevice()) + { + return; + } + + using var rig = new Rig(maxVersions: 4); + var a = Indices(1); + var b = Indices(2); + rig.Write(a); + var first = rig.Get((uint)a.Length, 1, 0); + rig.Write(b); + var second = rig.Get((uint)b.Length, 2, 1); + rig.Write(a); + Assert.Equal(first, rig.Get((uint)a.Length, 3, 2)); + _ = rig.Cache.TakeCounters(); + + // Later draws of submission 3 skip the hash and get the version submission 3 validated, + // not the one built last. + var again = rig.Get((uint)a.Length, 3, 2); + Assert.Equal(first, again); + Assert.NotEqual(second, again); + var counters = rig.Cache.TakeCounters(); + Assert.Contains("meshlet_validations_skipped=1 meshlet_builds=0 ", counters); + Assert.Contains("meshlet_hash_kb=0 ", counters); + } + + [Fact] + public void WithVersionsOffOneEntryPerKey() + { + if (!RequireDevice()) + { + return; + } + + using var rig = new Rig(maxVersions: 1); + var a = Indices(1); + var b = Indices(2); + var serial = 1UL; + foreach (var content in new[] { a, b, a, b }) + { + rig.Write(content); + AssertBuiltFrom(content, rig.Get((uint)content.Length, serial, serial - 1)); + Assert.Equal(1, rig.Cache.VersionCount); + serial++; + } + + Assert.Equal(0, rig.Cache.VersionHits); + Assert.Contains("meshlet_builds=4 ", rig.Cache.TakeCounters()); + } + private bool RequireDevice() { if (Environment.GetEnvironmentVariable("SHARPEMU_TEST_REQUIRE_DEVICE") != "1") From 5378a1f79545c85751bdb539da5f5a13e485cc12 Mon Sep 17 00:00:00 2001 From: kuba Date: Sun, 15 Nov 2026 06:07:55 +0000 Subject: [PATCH 025/178] [Metal] Land device-ordered held label copies inside the open compute encoder A batch of held copies with no CPU-visible copy lands as one scatter dispatch between two memory barriers in the open compute encoder, at a forced landing or as EnsureComputeEncoder opens one, instead of ending the encoder for an event barrier and a copy encoder. The encoder waited on the encoder fence at its start, so the copies land after all earlier work in device order and before all later work, as the device-only event gave. Refused (counted) without the fence chain, with occlusion prefix sums owed, or with staged stores still to write back (they land at the encoder end and must not overwrite a later copy). A CPU-visible copy keeps the shared event. SHARPEMU_METAL_V2_LABELS_IN_ENCODER=0 off, =verify reads folded words back. --- .../V2/MetalCommandStream.cs | 6 + .../V2/MetalRenderHost.LabelScatter.cs | 209 ++++++++++++++++-- .../V2/MetalRenderHost.Rendering.cs | 26 ++- .../MetalEndOfPipeOrderTests.LabelFold.cs | 158 +++++++++++++ .../MetalEndOfPipeOrderTests.cs | 2 + 5 files changed, 377 insertions(+), 24 deletions(-) create mode 100644 tests/SharpEmu.Gpu.Metal.Tests/MetalEndOfPipeOrderTests.LabelFold.cs diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalCommandStream.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalCommandStream.cs index 74d9554a3..78b64f5c4 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalCommandStream.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalCommandStream.cs @@ -2084,6 +2084,12 @@ internal void OrderAfterDeferredCopies(ulong address, ulong size, LabelLandCause // reads or writes them, and must see the copy, or overwrite it, in stream order. _landDeferredLabels = true; _labelLandCause = cause; + if (_computeEncoder != 0 && TryLandHeldCopiesInComputeEncoder()) + { + // Copies the CPU need not see first land in the open compute encoder (MetalRenderHost.LabelScatter.cs). + return; + } + if (_computeEncoder != 0 || _renderEncoder != 0) { EndEncoders(PassEndCause.Other); diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.LabelScatter.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.LabelScatter.cs index 56c0366a7..d52502ca6 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.LabelScatter.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.LabelScatter.cs @@ -64,8 +64,39 @@ private unsafe bool TryEncodeLabelScatter(nint commandBuffer, ReadOnlySpan copies, out MetalGuestRange list, out int sources, out int buffers, out int count) + { + list = default; + count = 0; + buffers = 0; // The buffers copied from come first, then those copied into; none may be both. - var sources = 0; + sources = 0; var sourceHint = 0; foreach (ref readonly var copy in copies) { @@ -73,19 +104,17 @@ private unsafe bool TryEncodeLabelScatter(nint commandBuffer, ReadOnlySpan= 0 || !NoteLabelScatterBuffer(copy.DestinationBuffer, sources, ref buffers, ref destinationHint)) { - _labelScatterDeclined++; return false; } } @@ -95,14 +124,11 @@ private unsafe bool TryEncodeLabelScatter(nint commandBuffer, ReadOnlySpanBatches of held copies landed inside the open compute encoder. + internal long LabelsFolded => Interlocked.Read(ref _labelsFolded); + + /// SHARPEMU_METAL_V2_LABELS_IN_ENCODER=verify: folded words that did not hold their value at completion. + internal static long LabelFoldVerifyMismatches => Interlocked.Read(ref _labelFoldVerifyMismatches); + + // Whether these held copies may land inside a compute encoder. A CPU-visible copy is the normal case of not folding + // and is not a refusal; the rest are counted (label_in_encoder_refused). + private bool MayFoldHeldCopies(ReadOnlySpan copies) + { + if (!LabelsInEncoder || copies.IsEmpty || !LabelBarrierByCacheAction) + { + return false; + } + + foreach (ref readonly var copy in copies) + { + if (copy.CpuVisible) + { + return false; + } + } + + if (EncoderOrdering != EncoderOrderingMode.Fence) + { + // Without the fence chain the encoder may start before the work ahead of it has finished. + _labelInEncoderRefused[2]++; + return false; + } + + if (_oqPendingReductions.Count != 0) + { + // An occlusion prefix sum still owed is encoded with no encoder open, ahead of the copies that read it. + _labelInEncoderRefused[0]++; + return false; + } + + if (_stagedStorageCopies is { Count: > 0 } staged && staged.HasRecordedStores) + { + // Staged stores are written back when the encoder ends; a held copy over them has to land after them. + _labelInEncoderRefused[3]++; + return false; + } + + return true; + } + + // Lands every held copy as one dispatch in the open compute encoder; false leaves them held (counted). + private bool TryLandHeldCopiesInComputeEncoder() + { + var copies = System.Runtime.InteropServices.CollectionsMarshal.AsSpan(_deferredLabelCopies); + if (_computeEncoder == 0 || _renderEncoder != 0 || _encodingDeferredLabels || !MayFoldHeldCopies(copies)) + { + return false; + } + + if (!TryBuildLabelScatter(copies, out var list, out var sources, out var buffers, out var count)) + { + _labelInEncoderRefused[1]++; + return false; + } + + var cause = _labelLandCause == LabelLandCause.None ? LabelLandCause.Other : _labelLandCause; + _landDeferredLabels = false; + _labelLandCause = LabelLandCause.None; + NoteLabelLanding(copies, cause); + if (LabelsInEncoderVerify) + { + VerifyFoldedCopies(copies); + } + + var encoder = _computeEncoder; + NoteRecordedWork(); + MetalV2Native.SendMemoryBarrierScope(encoder, SelComputeMemoryBarrier, Mtl.BarrierScopeBuffers | Mtl.BarrierScopeTextures); + EncodeLabelScatterDispatch(encoder, in list, sources, buffers, count); + MetalV2Native.SendMemoryBarrierScope(encoder, SelComputeMemoryBarrier, Mtl.BarrierScopeBuffers | Mtl.BarrierScopeTextures); + // The next guest dispatch binds its own pipeline again; its buffers are bound per dispatch. + _boundComputePipeline = 0; + _labelBarrierKinds[BarrierKindInEncoder]++; + _labelsFolded++; + var held = copies.Length; + ClearHeldLabelCopies(); + if (PassProfileEnabled) + { + PassProfileNoteWork($"label-fold n={held}", "transfer"); + } + return true; } + // =verify: what each folded word holds once the submission completes, the last copy into a word winning. + private unsafe void VerifyFoldedCopies(ReadOnlySpan copies) + { + var expected = new Dictionary(); + foreach (ref readonly var copy in copies) + { + var staging = (byte*)MetalNative.Send(copy.StagingBuffer, SelLabelFoldContents); + if (staging == null) + { + continue; + } + + for (var offset = 0; offset < copy.Bytes; offset += sizeof(uint)) + { + expected[copy.GuestAddress + (ulong)offset] = *(uint*)(staging + copy.StagingOffset + (ulong)offset); + } + } + + _completions.Enqueue(SubmissionSerial, () => + { + Span word = stackalloc byte[sizeof(uint)]; + foreach (var (address, value) in expected) + { + if (_memory.TryRead(address, word) && System.Buffers.Binary.BinaryPrimitives.ReadUInt32LittleEndian(word) != value) + { + Interlocked.Increment(ref _labelFoldVerifyMismatches); + MetalV2Diagnostics.WarnOnce("label-fold-verify", + $"A label copy folded into a compute encoder did not hold its value at completion: address=0x{address:X16} " + + $"expected=0x{value:X8} found=0x{System.Buffers.Binary.BinaryPrimitives.ReadUInt32LittleEndian(word):X8}."); + } + } + }); + } + + private static readonly nint SelLabelFoldContents = MetalNative.Selector("contents"); + // Consecutive copies mostly share their buffers (an occlusion dump's blocks, a pass's dumps), so the // buffer found last answers first. private int FindLabelScatterBuffer(nint buffer, int first, int count, ref int hint) diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Rendering.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Rendering.cs index e34f5170d..3a0ec929f 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Rendering.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Rendering.cs @@ -1444,6 +1444,7 @@ private void EndComputeEncoder() private nint EnsureComputeEncoder(bool materializeClears) { NoteRecordedWork(); + var foldAtOpen = false; if (_computeEncoder == 0) { if (_renderingActive) @@ -1454,7 +1455,14 @@ private nint EnsureComputeEncoder(bool materializeClears) EndRendering(); EncodeStagedStores(); - EncodeDeferredLabelCopies(LabelLandCause.EnsureCompute); + // Copies that land here and need no shared event land in the encoder this opens, after its fence wait + // (MetalRenderHost.LabelScatter.cs), instead of in a copy encoder of their own ahead of it. + foldAtOpen = _deferredLabelCopies.Count != 0 && (!LabelsAtCommit || _landDeferredLabels) && + !_encodingDeferredLabels && MayFoldHeldCopies(System.Runtime.InteropServices.CollectionsMarshal.AsSpan(_deferredLabelCopies)); + if (!foldAtOpen) + { + EncodeDeferredLabelCopies(LabelLandCause.EnsureCompute); + } } // Only the clears this dispatch can see are encoded ahead of it; the rest keep @@ -1497,6 +1505,22 @@ private nint EnsureComputeEncoder(bool materializeClears) // A new encoder has none of the residency the last one was given. ForgetResidentResources(); _computeEncodersOpened++; + if (foldAtOpen && _deferredLabelCopies.Count != 0 && (!LabelsAtCommit || _landDeferredLabels)) + { + if (_labelLandCause == LabelLandCause.None) + { + _labelLandCause = LabelLandCause.EnsureCompute; + } + + if (!TryLandHeldCopiesInComputeEncoder()) + { + // The scatter declined the batch: it lands as before, ahead of an encoder of its own. + EndComputeEncoder(); + EncodeDeferredLabelCopies(LabelLandCause.EnsureCompute); + return EnsureComputeEncoder(materializeClears); + } + } + return _computeEncoder; } diff --git a/tests/SharpEmu.Gpu.Metal.Tests/MetalEndOfPipeOrderTests.LabelFold.cs b/tests/SharpEmu.Gpu.Metal.Tests/MetalEndOfPipeOrderTests.LabelFold.cs new file mode 100644 index 000000000..7a31e1f00 --- /dev/null +++ b/tests/SharpEmu.Gpu.Metal.Tests/MetalEndOfPipeOrderTests.LabelFold.cs @@ -0,0 +1,158 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using System.Diagnostics; +using SharpEmu.Gpu.Metal.V2; +using SharpEmu.Libs.Gpu.GpuCommands; +using Xunit; + +namespace SharpEmu.Gpu.Metal.Tests; + +// Held copies the CPU need not see before the work ahead of them land as a dispatch in the open compute encoder +// (MetalRenderHost.LabelScatter.cs); one the CPU must see keeps the shared event. +public sealed unsafe partial class MetalEndOfPipeOrderTests +{ + // A device-only label, then a store over its bytes, then a later label the next dispatch binds: each lands inside the + // open compute encoder, in stream order, with no barrier. + [Fact] + public void DeviceOrderedHeldCopiesLandInTheOpenComputeEncoderInStreamOrder() + { + if (!RequireDevice()) return; + using var rig = new Rig(Device.Value); + var host = rig.Host; + Assert.True(host.LabelsAtCommit); + Assert.True(host.LabelsInEncoder); + const ulong second = GuestBase + 0x10000; + _ = host.TakeLabelBarriers(); + _ = host.TakeLabelBarrierKinds(); + + _ = host.EnsureComputeEncoder(); + host.RecordEndOfPipe(new EndOfPipeWrite(EndOfPipeWriteKind.Write64, 1, WindowedLabel, 0x11)); + Assert.Equal(1, host.DeferredLabelCopyCount); + var folded = host.LabelsFolded; + + // A fill over the label's bytes (a dispatch in the encoder) lands the label first, inside the encoder. + host.FillBufferInOrder(WindowedLabel, 0x2000, 0x77); + Assert.True(host.ComputeEncoderOpen); + Assert.Equal(0, host.DeferredLabelCopyCount); + Assert.Equal(folded + 1, host.LabelsFolded); + + // The next dispatch binds a label recorded after the fill: it lands ahead of it, still in the encoder. + host.RecordEndOfPipe(new EndOfPipeWrite(EndOfPipeWriteKind.Write32, 1, second, 0x22)); + host.OrderAfterDeferredCopies(second, 4); + Assert.True(host.ComputeEncoderOpen); + Assert.Equal(0, host.DeferredLabelCopyCount); + Assert.Equal(folded + 2, host.LabelsFolded); + Assert.Equal(0L, host.TakeLabelBarriers()); + Assert.Equal(new long[] { 0, 0, 0, 2 }, host.TakeLabelBarrierKinds()); + + host.FlushCommandBuffer(); + WaitForGpu(host, host.LastWorkSerial); + WaitForCompletions(host); + Assert.Equal(0x0000007700000077UL, rig.Backing.Read64(WindowedLabel)); + Assert.Equal(0x22u, rig.Backing.Read32(second)); + } + + // A held label the guest asked to be written back for the CPU is never folded: the batch it is in ends the encoder + // and lands behind the shared event, with the device-only label held before it. + [Fact] + public void ABatchWithACpuVisibleLabelIsNotFoldedAndTakesTheSharedEvent() + { + if (!RequireDevice()) return; + using var rig = new Rig(Device.Value); + var host = rig.Host; + _ = host.TakeLabelBarriers(); + _ = host.TakeLabelBarrierKinds(); + + _ = host.EnsureComputeEncoder(); + host.RecordEndOfPipe(new EndOfPipeWrite(EndOfPipeWriteKind.Write64, 1, WindowedLabel, 1)); + host.RecordEndOfPipe(new EndOfPipeWrite(EndOfPipeWriteKind.WriteBack64, 1, LaterLabel, 2)); + var folded = host.LabelsFolded; + host.OrderAfterDeferredCopies(WindowedLabel, 8); + Assert.False(host.ComputeEncoderOpen); + Assert.Equal(0, host.DeferredLabelCopyCount); + Assert.Equal(folded, host.LabelsFolded); + Assert.Equal(1L, host.TakeLabelBarriers()); + Assert.Equal(new long[] { 1, 0, 0, 0 }, host.TakeLabelBarrierKinds()); + + host.FlushCommandBuffer(); + WaitForGpu(host, host.LastWorkSerial); + WaitForCompletions(host); + Assert.Equal(1UL, rig.Backing.Read64(WindowedLabel)); + Assert.Equal(2UL, rig.Backing.Read64(LaterLabel)); + } + + // Without the encoder fence chain an encoder may start before the work ahead of it finished, so nothing is folded + // (counted as no_fence); with the fold switched off nothing is folded either. Both land behind the device event. + [Theory] + [InlineData(true)] + [InlineData(false)] + public void TheFoldIsRefusedWithoutTheFenceChainAndWhenSwitchedOff(bool noFence) + { + if (!RequireDevice()) return; + using var rig = new Rig(Device.Value); + var host = rig.Host; + if (noFence) + { + host.EncoderOrdering = MetalRenderHost.EncoderOrderingMode.None; + } + else + { + host.LabelsInEncoder = false; + } + + _ = host.TakeLabelInEncoderRefusals(); + _ = host.TakeLabelBarrierKinds(); + _ = host.EnsureComputeEncoder(); + host.RecordEndOfPipe(new EndOfPipeWrite(EndOfPipeWriteKind.Write64, 1, WindowedLabel, 5)); + var folded = host.LabelsFolded; + host.OrderAfterDeferredCopies(WindowedLabel, 8); + Assert.False(host.ComputeEncoderOpen); + Assert.Equal(folded, host.LabelsFolded); + Assert.Equal(noFence ? 1L : 0L, host.TakeLabelInEncoderRefusals()[2]); + Assert.Equal(new long[] { 0, 1, 0, 0 }, host.TakeLabelBarrierKinds()); + + host.FlushCommandBuffer(); + WaitForGpu(host, host.LastWorkSerial); + WaitForCompletions(host); + Assert.Equal(5UL, rig.Backing.Read64(WindowedLabel)); + } + + // A write-back label recorded after a GPU store is seen by the CPU only once the store is too: 500 times, the CPU + // polls the label and reads the store's last word as soon as it sees it. + [Fact] + public void ACpuVisibleLabelIsNeverSeenBeforeTheStoreAheadOfIt() + { + if (!RequireDevice()) return; + using var rig = new Rig(Device.Value); + var host = rig.Host; + const ulong filled = GuestBase + 0x10000; + const ulong size = 0x4000; + var early = 0; + for (var attempt = 1; attempt <= 500; attempt++) + { + _ = host.EnsureComputeEncoder(); + host.FillBufferInOrder(filled, size, (uint)attempt); + host.RecordEndOfPipe(new EndOfPipeWrite(EndOfPipeWriteKind.WriteBack64, 1, WindowedLabel, (ulong)attempt)); + // Forced while the encoder is open, as a dispatch binding the label would. + host.OrderAfterDeferredCopies(WindowedLabel, 8); + var serial = host.FlushCommandBuffer(); + var started = Stopwatch.GetTimestamp(); + while (rig.Backing.Read64(WindowedLabel) != (ulong)attempt) + { + Assert.True(Stopwatch.GetElapsedTime(started) < TimeSpan.FromSeconds(10), $"label {attempt} never landed"); + Thread.SpinWait(8); + } + + if (rig.Backing.Read32(filled + size - sizeof(uint)) != (uint)attempt) + { + early++; + } + + WaitForGpu(host, serial); + WaitForCompletions(host); + } + + Assert.Equal(0, early); + } +} diff --git a/tests/SharpEmu.Gpu.Metal.Tests/MetalEndOfPipeOrderTests.cs b/tests/SharpEmu.Gpu.Metal.Tests/MetalEndOfPipeOrderTests.cs index 0a92dc354..b52aa86cd 100644 --- a/tests/SharpEmu.Gpu.Metal.Tests/MetalEndOfPipeOrderTests.cs +++ b/tests/SharpEmu.Gpu.Metal.Tests/MetalEndOfPipeOrderTests.cs @@ -220,6 +220,8 @@ public void AFillOverAHeldLabelEndsTheOpenComputeEncoderFirst() host.LabelsAtCommit = false; // The fill after the boundary is a blit, not a dispatch in a compute encoder opened for it. host.CopiesShareCompute = false; + // The device-only label would land inside the encoder instead (DeviceOrderedHeldCopiesLandInTheOpenComputeEncoderInStreamOrder). + host.LabelsInEncoder = false; Assert.True(host.DefersCopiesInCompute); _ = host.EnsureComputeEncoder(); From a9c17935e78106b6ab926a07eba8bba7d2dc35c2 Mon Sep 17 00:00:00 2001 From: kuba Date: Sun, 15 Nov 2026 06:09:37 +0000 Subject: [PATCH 026/178] [Metal] Pool meshlet buffers so rebuilds leave the resident list alone Step 2 of the meshlet cache plan: a buffer whose entry goes is kept, still resident, in a free pool by capacity (quarter steps of a power of two, from 4 KiB; 32 MiB of free buffers at most) once the submission that last used it has completed, and the next build of that class writes into it. A rebuild then neither creates nor releases a Metal buffer, so the shared resident list keeps its version and the next encoder names nothing again. PERF adds meshlet_pool_hits, meshlet_pool_mb and meshlet_resident_churn (buffers created or released). SHARPEMU_METAL_MESHLET_POOL=0 creates and releases per build as before. --- .../V2/MetalMeshletCache.cs | 99 +++++++++- .../MetalMeshletCacheTests.cs | 174 +++++++++++++++++- 2 files changed, 258 insertions(+), 15 deletions(-) diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalMeshletCache.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalMeshletCache.cs index 552d3f3f2..2de6c95d6 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalMeshletCache.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalMeshletCache.cs @@ -313,6 +313,17 @@ public void Add(ulong hash) Environment.GetEnvironmentVariable("SHARPEMU_METAL_MESHLET_TRACE") == "1"; // SHARPEMU_METAL_MESHLET_VERSIONS=0 keeps one version per key, replaced on every change. + // SHARPEMU_METAL_MESHLET_POOL=0 creates a buffer per build and releases it when its entry goes, + // each a change of the resident list, as before. + private static readonly bool DefaultPool = + SharpEmu.ShaderCompiler.PerfSwitches.Enabled("SHARPEMU_METAL_MESHLET_POOL"); + + // Pooled buffers come in quarter steps of a power of two, from MinPooledBytes, so a rebuild + // of about the same size finds a free buffer of its class; free buffers past PoolBudgetBytes + // are released. + private const ulong MinPooledBytes = 4 * 1024; + private const ulong PoolBudgetBytes = 32UL * 1024 * 1024; + private static readonly int DefaultMaxVersions = SharpEmu.ShaderCompiler.PerfSwitches.Enabled("SHARPEMU_METAL_MESHLET_VERSIONS") ? MaxVersionsPerKey : 1; @@ -325,7 +336,11 @@ public void Add(ulong hash) private readonly MeshletBuilder.Scratch _scratch = new(); private readonly System.IO.Hashing.XxHash3 _hasher = new(); private uint[] _indices = []; - private readonly List<(nint Buffer, ulong Serial)> _retired = []; + private readonly List<(nint Buffer, nint Contents, ulong Bytes, ulong Serial)> _retired = []; + private readonly bool _pool; + // Free buffers by capacity: their last use completed, they stay resident, nothing reads them. + private readonly Dictionary> _free = []; + private ulong _freeBytes; private readonly Dictionary _history = []; private int _traceLines; private ulong _bytes; @@ -345,10 +360,14 @@ public void Add(ulong hash) private long _allocTicks; private long _evictions; private long _versionHits; + private long _poolHits; + private long _residentChurn; /// Versions kept per key, 1 to 4; the env setting when null. - public MetalMeshletCache(MetalGuestMemory guestMemory, ICpuMemory memory, int? maxVersions = null) + /// Whether buffers are pooled; the env setting when null. + public MetalMeshletCache(MetalGuestMemory guestMemory, ICpuMemory memory, int? maxVersions = null, bool? pool = null) { + _pool = pool ?? DefaultPool; _guestMemory = guestMemory; _memory = memory; _maxVersions = Math.Clamp(maxVersions ?? DefaultMaxVersions, 1, MaxVersionsPerKey); @@ -482,7 +501,7 @@ public bool TryGet( MeshletBuilder.BuildInto(indices, maxVertices, maxPrimitives, built); var builderDone = System.Diagnostics.Stopwatch.GetTimestamp(); var wordCount = built.WordCount; - var size = (ulong)wordCount * sizeof(uint); + var size = _pool ? SizeClass((ulong)wordCount * sizeof(uint)) : (ulong)wordCount * sizeof(uint); if (!MakeRoom(size, completedSerial)) { ReleaseRetired(completedSerial); @@ -490,7 +509,13 @@ public bool TryGet( return false; } - var buffer = _guestMemory.CreateMeshletBuffer(size, out var contents); + if (_pool) + { + // Entries evicted for room whose last use completed are free for this build. + ReleaseRetired(completedSerial); + } + + var buffer = TakeBuffer(size, out var contents); unsafe { built.CopyTo(new Span((void*)contents, wordCount)); @@ -586,6 +611,40 @@ private void NoteBuild(Key key, ulong hash, ulong oldHash, ulong serial) /// Buffers removed from the cache and waiting for their last use to complete. internal int RetiredCount => _retired.Count; + /// Builds in this window that reused a pooled buffer. + internal long PoolHits => _poolHits; + + /// Meshlet buffers created or released in this window: each changes the resident list. + internal long ResidentChurn => _residentChurn; + + /// The capacity a pooled buffer for has: the next quarter step + /// of the power of two at or below it, at least . + internal static ulong SizeClass(ulong bytes) + { + if (bytes <= MinPooledBytes) + { + return MinPooledBytes; + } + + var step = (1UL << (63 - System.Numerics.BitOperations.LeadingZeroCount(bytes))) / 4; + return (bytes + step - 1) / step * step; + } + + // A free pooled buffer of exactly this capacity, else a new one. + private nint TakeBuffer(ulong bytes, out nint contents) + { + if (_pool && _free.TryGetValue(bytes, out var free) && free.TryPop(out var pooled)) + { + _freeBytes -= bytes; + _poolHits++; + contents = pooled.Contents; + return pooled.Buffer; + } + + _residentChurn++; + return _guestMemory.CreateMeshletBuffer(bytes, out contents); + } + private void Touch(Entry entry, ulong serial) { entry.LastUsedSerial = serial; @@ -667,18 +726,37 @@ private void Remove(Entry entry) _versionCount--; _bytes -= entry.Bytes; - _retired.Add((entry.Buffer, entry.LastUsedSerial)); + _retired.Add((entry.Buffer, entry.Contents, entry.Bytes, entry.LastUsedSerial)); } + // With the pool, a buffer whose last use completed goes back to it, still resident, so the + // resident list does not change; it is released only when the pool is full. private void ReleaseRetired(ulong completedSerial) { for (var i = _retired.Count - 1; i >= 0; i--) { - if (_retired[i].Serial <= completedSerial) + var retired = _retired[i]; + if (retired.Serial > completedSerial) { - _guestMemory.ReleaseMeshletBuffer(_retired[i].Buffer); - _retired.RemoveAt(i); + continue; } + + _retired.RemoveAt(i); + if (_pool && _freeBytes + retired.Bytes <= PoolBudgetBytes) + { + if (!_free.TryGetValue(retired.Bytes, out var free)) + { + free = new Stack<(nint Buffer, nint Contents)>(); + _free[retired.Bytes] = free; + } + + free.Push((retired.Buffer, retired.Contents)); + _freeBytes += retired.Bytes; + continue; + } + + _guestMemory.ReleaseMeshletBuffer(retired.Buffer); + _residentChurn++; } } @@ -697,7 +775,8 @@ public string TakeCounters() $"meshlet_hash_kb={_hashBytes / 1024} meshlet_build_kb={_buildBytes / 1024} " + $"meshlet_build_split_ms=[read={Ms(_readTicks)} build={Ms(_builderTicks)} alloc={Ms(_allocTicks)}] " + $"meshlet_entries={_slots.Count} meshlet_evictions={_evictions} " + - $"meshlet_version_hits={_versionHits} meshlet_versions={_versionCount}"; + $"meshlet_version_hits={_versionHits} meshlet_versions={_versionCount} " + + $"meshlet_pool_hits={_poolHits} meshlet_pool_mb={_freeBytes / (1024 * 1024)} meshlet_resident_churn={_residentChurn}"; _draws = 0; _builds = 0; _validationsSkipped = 0; @@ -712,6 +791,8 @@ public string TakeCounters() _allocTicks = 0; _evictions = 0; _versionHits = 0; + _poolHits = 0; + _residentChurn = 0; return text; string Ms(long ticks) => (ticks * 1000.0 / frequency).ToString("F2", culture); diff --git a/tests/SharpEmu.Gpu.Metal.Tests/MetalMeshletCacheTests.cs b/tests/SharpEmu.Gpu.Metal.Tests/MetalMeshletCacheTests.cs index 5b0bd2c8c..d921969b8 100644 --- a/tests/SharpEmu.Gpu.Metal.Tests/MetalMeshletCacheTests.cs +++ b/tests/SharpEmu.Gpu.Metal.Tests/MetalMeshletCacheTests.cs @@ -26,12 +26,12 @@ private sealed class Rig : IDisposable public readonly MetalGuestMemory Memory; public readonly MetalMeshletCache Cache; - public Rig(int? maxVersions = null) + public Rig(int? maxVersions = null, bool? pool = null) { Memory = new MetalGuestMemory( Device.Value, Backing, new MetalGuestWindowGranuleTests.BackingMemory(Backing), MetalGuestWindowGranuleTests.GranuleBytes, MetalGuestWindowGranuleTests.MaxWindowBytes); - Cache = new MetalMeshletCache(Memory, new MetalGuestWindowGranuleTests.BackingMemory(Backing), maxVersions); + Cache = new MetalMeshletCache(Memory, new MetalGuestWindowGranuleTests.BackingMemory(Backing), maxVersions, pool); } public void Write(uint[] indices, ulong address = RangeAddress) @@ -41,9 +41,22 @@ public void Write(uint[] indices, ulong address = RangeAddress) Assert.True(Backing.TryWriteBacking(address, bytes)); } - public MetalMeshletCache.Meshlets Get(uint indexCount, ulong serial, ulong completed, ulong address = RangeAddress) + public void Write16(uint[] indices, ulong address = RangeAddress) { - Assert.True(Cache.TryGet(address, indexCount, true, MaxVertices, MaxPrimitives, serial, completed, out var meshlets)); + var bytes = new byte[indices.Length * sizeof(ushort)]; + for (var i = 0; i < indices.Length; i++) + { + BitConverter.TryWriteBytes(bytes.AsSpan(i * sizeof(ushort)), checked((ushort)indices[i])); + } + + Assert.True(Backing.TryWriteBacking(address, bytes)); + } + + public MetalMeshletCache.Meshlets Get( + uint indexCount, ulong serial, ulong completed, ulong address = RangeAddress, bool index32 = true, + uint maxVertices = MaxVertices, uint maxPrimitives = MaxPrimitives) + { + Assert.True(Cache.TryGet(address, indexCount, index32, maxVertices, maxPrimitives, serial, completed, out var meshlets)); return meshlets; } @@ -74,9 +87,17 @@ private static uint[] Words(MetalMeshletCache.Meshlets meshlets, int triangles) return new ReadOnlySpan((void*)contents, (int)meshlets.PrimitiveBase + triangles).ToArray(); } - private static void AssertBuiltFrom(uint[] indices, MetalMeshletCache.Meshlets meshlets) + // Triangles of three fresh vertices each, the values offset by `offset`: every offset builds + // the same number of words, so its buffers share one pool class, but hashes differently. + private static uint[] Strip(uint offset, int triangles = 300) => + Enumerable.Range(0, triangles * 3).Select(i => offset + (uint)i).ToArray(); + + // The oracle is the builder as it is today (MeshletBuilder.Build into fresh arrays): the cache's + // words, written into a buffer that may hold an older build, must equal it word for word. + private static void AssertBuiltFrom( + uint[] indices, MetalMeshletCache.Meshlets meshlets, uint maxVertices = MaxVertices, uint maxPrimitives = MaxPrimitives) { - var expected = MeshletBuilder.Build(indices, MaxVertices, MaxPrimitives); + var expected = MeshletBuilder.Build(indices, maxVertices, maxPrimitives); Assert.Equal(expected.MeshletCount, meshlets.Count); Assert.Equal(expected.VertexBase, meshlets.VertexBase); Assert.Equal(expected.PrimitiveBase, meshlets.PrimitiveBase); @@ -256,6 +277,147 @@ public void WithVersionsOffOneEntryPerKey() Assert.Contains("meshlet_builds=4 ", rig.Cache.TakeCounters()); } + [Theory] + [InlineData(true)] + [InlineData(false)] + public void BuildIntoMatchesTheReferenceBuilderBitForBit(bool index32) + { + if (!RequireDevice()) + { + return; + } + + // A few keys (count and limits) rebuilt with new random content, one version per key and + // every earlier submission complete: most builds write over a pooled buffer that held + // another build of its class. + using var rig = new Rig(maxVersions: 1, pool: true); + var random = new Random(index32 ? 7 : 8); + var shapes = new (int Triangles, int Range, uint Vertices, uint Primitives)[] + { + (0, 300, 64, 32), (7, 300, 3, 1), (600, 300, 64, 32), (600, 60000, 128, 256), + (3000, 300, 255, 255), (3000, 60000, 30, 10), (1999, 2000, 64, 126), + }; + for (var serial = 1UL; serial <= 140; serial++) + { + var (triangles, range, vertices, primitives) = shapes[random.Next(shapes.Length)]; + var indices = Enumerable.Range(0, triangles * 3).Select(_ => (uint)random.Next(0, range)).ToArray(); + if (index32) + { + rig.Write(indices); + } + else + { + rig.Write16(indices); + } + + var meshlets = rig.Get((uint)indices.Length, serial, serial - 1, index32: index32, maxVertices: vertices, + maxPrimitives: primitives); + AssertBuiltFrom(indices, meshlets, vertices, primitives); + } + + Assert.True(rig.Cache.PoolHits > 0, rig.Cache.TakeCounters()); + } + + // A rebuild under submission 3 while submissions 1 and 2 are in flight gets a new buffer; once + // submission 1 completes, the buffer it read is reused, never the one submission 3 can read. + [Fact] + public void APooledBufferIsNotReusedWhileASubmissionCanReadIt() + { + if (!RequireDevice()) + { + return; + } + + using var rig = new Rig(maxVersions: 1, pool: true); + var contents = Enumerable.Range(1, 4).Select(k => Strip((uint)k * 10000)).ToArray(); + rig.Write(contents[0]); + var first = rig.Get((uint)contents[0].Length, 1, 0); + rig.Write(contents[1]); + var second = rig.Get((uint)contents[1].Length, 2, 0); + rig.Write(contents[2]); + var third = rig.Get((uint)contents[2].Length, 3, 0); + Assert.Equal(3, new[] { first.Buffer, second.Buffer, third.Buffer }.Distinct().Count()); + Assert.Equal(0, rig.Cache.PoolHits); + Assert.Equal(2, rig.Cache.RetiredCount); + + // Submission 1 completed: its buffer is free, submission 2's is not, and 3's is in use. + rig.Write(contents[3]); + var fourth = rig.Get((uint)contents[3].Length, 4, 1); + Assert.Equal(first.Buffer, fourth.Buffer); + Assert.Equal(1, rig.Cache.PoolHits); + AssertBuiltFrom(contents[3], fourth); + + // Nothing more completed: the next rebuild cannot take submission 2's or 3's buffer. + rig.Write(contents[0]); + var fifth = rig.Get((uint)contents[0].Length, 5, 1); + Assert.DoesNotContain(fifth.Buffer, new[] { second.Buffer, third.Buffer, fourth.Buffer }); + AssertBuiltFrom(contents[0], fifth); + } + + // Rebuilds served from the pool leave the resident list as it was: no buffer is created or + // released, so the list's version does not move and the next encoder names nothing new. + [Fact] + public void ARebuildFromThePoolLeavesTheResidentListUnchanged() + { + if (!RequireDevice()) + { + return; + } + + using var rig = new Rig(maxVersions: 1, pool: true); + var contents = Enumerable.Range(1, 6).Select(k => Strip((uint)k * 10000)).ToArray(); + rig.Write(contents[0]); + rig.Get((uint)contents[0].Length, 1, 0); + rig.Write(contents[1]); + rig.Get((uint)contents[1].Length, 2, 1); + _ = rig.Cache.TakeCounters(); + + var before = rig.Memory.ResidentBuffers.ToArray(); + var version = rig.Memory.ResidentVersion; + for (var serial = 3UL; serial <= 6; serial++) + { + var content = contents[(int)serial - 1]; + rig.Write(content); + var meshlets = rig.Get((uint)content.Length, serial, serial - 1); + AssertBuiltFrom(content, meshlets); + if (rig.Memory.ResidencySet == 0) + { + Assert.Contains(meshlets.Buffer, rig.Memory.ResidentBuffers.ToArray()); + } + } + + Assert.Equal(4, rig.Cache.PoolHits); + Assert.Equal(0, rig.Cache.ResidentChurn); + var after = rig.Memory.ResidentBuffers.ToArray(); + Assert.Equal(version, rig.Memory.ResidentVersion); + Assert.Equal(before, after); + output.WriteLine($"residency set {(rig.Memory.ResidencySet != 0 ? "on" : "off")}, resident {after.Length}: " + + rig.Cache.TakeCounters()); + + // Without the pool every rebuild creates a buffer and releases one. + using var unpooled = new Rig(maxVersions: 1, pool: false); + for (var serial = 1UL; serial <= 4; serial++) + { + var content = contents[(int)serial - 1]; + unpooled.Write(content); + unpooled.Get((uint)content.Length, serial, serial - 1); + } + + Assert.Equal(0, unpooled.Cache.PoolHits); + // Four creates, and the first two buffers released once their submissions completed. + Assert.Equal(6, unpooled.Cache.ResidentChurn); + } + + [Theory] + [InlineData(0UL, 4096UL)] + [InlineData(4096UL, 4096UL)] + [InlineData(4097UL, 5120UL)] + [InlineData(16384UL, 16384UL)] + [InlineData(16385UL, 20480UL)] + [InlineData(1048577UL, 1310720UL)] + public void PooledBuffersComeInQuarterStepsOfAPowerOfTwo(ulong bytes, ulong capacity) => + Assert.Equal(capacity, MetalMeshletCache.SizeClass(bytes)); + private bool RequireDevice() { if (Environment.GetEnvironmentVariable("SHARPEMU_TEST_REQUIRE_DEVICE") != "1") From 28ef6070f45e00a7648db4721c1c694108c7920a Mon Sep 17 00:00:00 2001 From: kuba Date: Sun, 15 Nov 2026 06:17:25 +0000 Subject: [PATCH 027/178] [GPU] Keep only causal command-processor writes CPU-visible The interpreter flags a WRITE_DATA (or qword run) causal when, since its queue's previous one, a read was answered from a value not yet landed (a wait met by a recorded label or store, its own last store, COPY_DATA of a pending value, an operand read from a pending label, a COND_EXEC taking an owed operand as zero) or it emitted a partial flush, cache action or acquire. The Metal host holds a causal write CPU-visible, and every later write behind it until the held copies land; any other write is device-ordered, so a batch of them lands inside the open compute encoder. Callers that cannot tell stay causal. SHARPEMU_METAL_V2_CP_WRITE_DEVICE_ORDER=0 off; =verify keeps every write CPU-visible and counts cp_write_order_suspects. --- .../GpuCommandInterpreter.Events.cs | 2 +- .../GpuCommandInterpreter.Labels.cs | 8 +-- .../GpuCommandInterpreter.Memory.cs | 5 +- .../GpuCommandInterpreter.Waits.cs | 14 ++++ .../Gpu/GpuCommands/GpuCommandInterpreter.cs | 31 +++++++++ .../Gpu/GpuCommands/ICommandStreamHost.cs | 13 ++++ .../V2/MetalCommandStream.cs | 45 ++++++++---- .../V2/MetalRenderHost.LabelLanding.cs | 46 +++++++++++++ .../MetalEndOfPipeOrderTests.LabelFold.cs | 68 +++++++++++++++++++ .../GpuCommands/CommandStreamQueueTests.cs | 34 ++++++++++ .../GpuCommands/CommandStreamTestSupport.cs | 15 ++++ 11 files changed, 259 insertions(+), 22 deletions(-) diff --git a/src/SharpEmu.Libs/Gpu/GpuCommands/GpuCommandInterpreter.Events.cs b/src/SharpEmu.Libs/Gpu/GpuCommands/GpuCommandInterpreter.Events.cs index 05897042c..f9b65cc1b 100644 --- a/src/SharpEmu.Libs/Gpu/GpuCommands/GpuCommandInterpreter.Events.cs +++ b/src/SharpEmu.Libs/Gpu/GpuCommands/GpuCommandInterpreter.Events.cs @@ -189,7 +189,7 @@ internal void AcquireMemory(uint coherControl, uint gcrControl) Interlocked.Increment(ref _acquireBarriers); _acquireMemoryBarriers.Increment(); Diagnostics.DispatchRunTally.NoteSync(); - _host.EmitGlobalBarrier(); + EmitOrderingBarrier(); } _host.ReleaseShaderWrites(); diff --git a/src/SharpEmu.Libs/Gpu/GpuCommands/GpuCommandInterpreter.Labels.cs b/src/SharpEmu.Libs/Gpu/GpuCommands/GpuCommandInterpreter.Labels.cs index c78145ff9..87f184e16 100644 --- a/src/SharpEmu.Libs/Gpu/GpuCommands/GpuCommandInterpreter.Labels.cs +++ b/src/SharpEmu.Libs/Gpu/GpuCommands/GpuCommandInterpreter.Labels.cs @@ -396,7 +396,7 @@ internal void ReleaseMemory( if (eopEventType != 0x28 || gcrControl != 0) { Diagnostics.DispatchRunTally.NoteSync(); - _host.EmitGlobalBarrier(); + EmitOrderingBarrier(); _host.ReleaseShaderWrites(); } @@ -407,7 +407,7 @@ internal void ReleaseMemory( if (ReleaseMemGcrNeedsBarrier(eopEventType, gcrControl)) { Diagnostics.DispatchRunTally.NoteSync(); - _host.EmitGlobalBarrier(); + EmitOrderingBarrier(); _host.ReleaseShaderWrites(); } @@ -461,7 +461,7 @@ internal void RaiseEvent(uint eventType, uint eventIndex, ulong eventAddress) case 0x0F: case 0x10: Diagnostics.DispatchRunTally.NoteSync(); - _host.EmitGlobalBarrier(); + EmitOrderingBarrier(); if (eventType == PsPartialFlushEvent) { _host.ReleaseShaderWrites(); @@ -479,7 +479,7 @@ internal void RaiseEvent(uint eventType, uint eventIndex, ulong eventAddress) } Diagnostics.DispatchRunTally.NoteSync(); - _host.EmitGlobalBarrier(); + EmitOrderingBarrier(); if (eventType == CacheFlushAndInvalidateEvent) { _host.ReleaseShaderWrites(); diff --git a/src/SharpEmu.Libs/Gpu/GpuCommands/GpuCommandInterpreter.Memory.cs b/src/SharpEmu.Libs/Gpu/GpuCommands/GpuCommandInterpreter.Memory.cs index 4c41aa006..1ffe5a8f8 100644 --- a/src/SharpEmu.Libs/Gpu/GpuCommands/GpuCommandInterpreter.Memory.cs +++ b/src/SharpEmu.Libs/Gpu/GpuCommands/GpuCommandInterpreter.Memory.cs @@ -88,7 +88,7 @@ internal void WriteCommandProcessorBytes(ulong destination, ReadOnlySpan s NotePendingBytes(destination, source); } - _host.RecordCommandProcessorWrite(destination, source, kind); + _host.RecordCommandProcessorWrite(destination, source, kind, TakeCommandProcessorWriteCausal()); using var trailingScope = RenderPhaseProfile.MeasureDetail(RenderPhaseProfile.Phase.CommandCpBookkeeping); _lastWriteLength = 0; @@ -169,7 +169,7 @@ private void WriteCommandProcessorQwords(ulong destination, int count, ulong str } NotePacketBlockWrite(); - _host.RecordCommandProcessorQwords(destination, count, strideBytes, value, kind); + _host.RecordCommandProcessorQwords(destination, count, strideBytes, value, kind, TakeCommandProcessorWriteCausal()); _lastWriteAddress = destination + (ulong)(count - 1) * strideBytes; _lastWriteValue = value; @@ -394,6 +394,7 @@ internal void TransferData( if (byteCount is sizeof(uint) or sizeof(ulong) && PendingLabelLookup is { } lookup && lookup(sourceOrImmediate, byteCount == sizeof(ulong), out var pendingValue)) { + NoteCausalRead(); PendingLabelRecorded?.Invoke(destination, (int)byteCount, pendingValue); } diff --git a/src/SharpEmu.Libs/Gpu/GpuCommands/GpuCommandInterpreter.Waits.cs b/src/SharpEmu.Libs/Gpu/GpuCommands/GpuCommandInterpreter.Waits.cs index 971266e8e..67c49d2ae 100644 --- a/src/SharpEmu.Libs/Gpu/GpuCommands/GpuCommandInterpreter.Waits.cs +++ b/src/SharpEmu.Libs/Gpu/GpuCommands/GpuCommandInterpreter.Waits.cs @@ -69,14 +69,19 @@ internal void WaitOnMemory(uint compareFunction, ulong address, ulong reference, } } + // Met by a value not yet in memory (a recorded label or store this host lands later): what this queue writes + // next must not reach the guest before that value does (TakeCommandProcessorWriteCausal). + var pendingAnswer = deferred; if (!satisfied && TryReadOwnWrite(address, is64Bit, out var ownValue)) { _ = WaitOperation.TryCompare(ownValue, reference, mask, compareFunction, out satisfied); + pendingAnswer = satisfied; } if (!satisfied && PendingLabelLookup is { } pending && pending(address, is64Bit, out var labelValue)) { _ = WaitOperation.TryCompare(labelValue, reference, mask, compareFunction, out satisfied); + pendingAnswer = satisfied; } if (!satisfied && !deferred) @@ -87,6 +92,13 @@ internal void WaitOnMemory(uint compareFunction, ulong address, ulong reference, _ = WaitOperation.TryCompare(value, reference, mask, compareFunction, out satisfied); } + if (satisfied && (pendingAnswer || + (PendingLabelLookup is { } stillPending && stillPending(address, is64Bit, out _)))) + { + // A host read (its overlay of recorded stores) may have answered from a value still pending too. + NoteCausalRead(); + } + if (!satisfied) { if (DsTrace.Gpu) @@ -435,6 +447,8 @@ internal uint ConditionalExecutePacket(in PacketContext packet, ReadOnlySpanReads answered from a value not yet landed, on any queue (SHARPEMU_METAL_V2_CP_WRITE_DEVICE_ORDER=verify). + public static long PendingValueReads => Interlocked.Read(ref _pendingValueReads); + + private void NoteCausalRead() + { + _cpWriteCausal = true; + Interlocked.Increment(ref _pendingValueReads); + } + + private void EmitOrderingBarrier() + { + _cpWriteCausal = true; + _host.EmitGlobalBarrier(); + } + + private bool TakeCommandProcessorWriteCausal() + { + var causal = _cpWriteCausal; + _cpWriteCausal = false; + return causal; + } + // The last packets this interpreter walked, so a stream that leaves its // packet boundaries says how it got there instead of only where it stopped. private readonly PacketTraceEntry[] _packetTrace = new PacketTraceEntry[32]; @@ -1041,6 +1071,7 @@ internal bool TryReadOperandOrSuspend(ulong address, Span destination) if (destination.Length is sizeof(uint) or sizeof(ulong) && PendingLabelLookup is { } pending && pending(address, destination.Length == sizeof(ulong), out var labelValue)) { + NoteCausalRead(); if (destination.Length == sizeof(ulong)) { BinaryPrimitives.WriteUInt64LittleEndian(destination, labelValue); diff --git a/src/SharpEmu.Libs/Gpu/GpuCommands/ICommandStreamHost.cs b/src/SharpEmu.Libs/Gpu/GpuCommands/ICommandStreamHost.cs index acd239cea..111f693b2 100644 --- a/src/SharpEmu.Libs/Gpu/GpuCommands/ICommandStreamHost.cs +++ b/src/SharpEmu.Libs/Gpu/GpuCommands/ICommandStreamHost.cs @@ -361,6 +361,19 @@ void RecordCommandProcessorWrite(ulong address, ReadOnlySpan source, strin } } + /// + /// from a queue that knows whether the + /// write is causal: since that queue's previous one it read a value not yet landed, or flushed, wrote back or + /// acquired. Only a causal write says the work before it is done, so only it has to reach the guest no sooner than + /// the labels before it; a host that cannot tell them apart treats every write as causal. + /// + void RecordCommandProcessorWrite(ulong address, ReadOnlySpan source, string kind, bool causal) => + RecordCommandProcessorWrite(address, source, kind); + + /// with the causal flag. + void RecordCommandProcessorQwords(ulong address, int count, ulong strideBytes, ulong value, string kind, bool causal) => + RecordCommandProcessorQwords(address, count, strideBytes, value, kind); + /// /// Writes copies of one eight-byte value, /// apart, in record order with deferred labels: the same bytes, in the same order, as diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalCommandStream.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalCommandStream.cs index 78b64f5c4..e832187db 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalCommandStream.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalCommandStream.cs @@ -1184,29 +1184,33 @@ private ulong EncodeOrderedCopies( // The hops below are their own methods so the worker's own calls build no closure: a lambda // over the parameters makes the compiler allocate its capture at entry of the method that holds it. - private void PostCommandProcessorWrite(ulong address, byte[] queued, string kind) + private void PostCommandProcessorWrite(ulong address, byte[] queued, string kind, bool causal) { if (QueueCommandProcessorWrites) { // Reads overlapping this queued write wait until the worker installed // its overlay. Unrelated packets can continue; prefetch's non-draw gate // still orders future resource reads after the write. - _commandThread!.PostWrite(() => RecordCommandProcessorWrite(address, queued, kind), address, queued, UngatedWrites); + _commandThread!.PostWrite(() => RecordCommandProcessorWrite(address, queued, kind, causal), address, queued, UngatedWrites); } else { - RunTagged(() => RecordCommandProcessorWrite(address, queued, kind), nameof(RecordCommandProcessorWrite)); + RunTagged(() => RecordCommandProcessorWrite(address, queued, kind, causal), nameof(RecordCommandProcessorWrite)); } } - public void RecordCommandProcessorWrite(ulong address, ReadOnlySpan source, string kind) + // A caller that cannot tell whether the write is causal (a DMA fill staged as a write, a test) gets the causal path. + public void RecordCommandProcessorWrite(ulong address, ReadOnlySpan source, string kind) => + RecordCommandProcessorWrite(address, source, kind, causal: true); + + public void RecordCommandProcessorWrite(ulong address, ReadOnlySpan source, string kind, bool causal) { if (OnCommandThread) { if (source.IsEmpty) return; if (address == 0 || (ulong)source.Length > ulong.MaxValue - address) throw Fatal($"A command-processor write has an invalid range: address=0x{address:X16} bytes={source.Length}."); - PostCommandProcessorWrite(address, source.ToArray(), kind); + PostCommandProcessorWrite(address, source.ToArray(), kind, causal); return; } @@ -1221,7 +1225,7 @@ public void RecordCommandProcessorWrite(ulong address, ReadOnlySpan source throw Fatal($"A command-processor write has an invalid range: address=0x{address:X16} bytes={source.Length}."); } - if (TryEncodeCommandProcessorWrite(address, source, kind)) + if (TryEncodeCommandProcessorWrite(address, source, kind, causal)) { Interlocked.Increment(ref _gpuTimedCommandProcessorWrites); return; @@ -1255,7 +1259,7 @@ public void RecordCommandProcessorWrite(ulong address, ReadOnlySpan source }, lazy ? (address, bytes.Length) : null); } - private bool TryEncodeCommandProcessorWrite(ulong address, ReadOnlySpan source, string kind) + private bool TryEncodeCommandProcessorWrite(ulong address, ReadOnlySpan source, string kind, bool causal) { using var phaseScope = SharpEmu.Libs.VideoOut.RenderPhaseProfile.MeasureDetail(SharpEmu.Libs.VideoOut.RenderPhaseProfile.Phase.CommandProcessorWrite); if (!GpuTimedLabels) @@ -1285,12 +1289,15 @@ private bool TryEncodeCommandProcessorWrite(ulong address, ReadOnlySpan so } source.CopyTo(payload); + var (cpuVisible, copyKind) = CommandProcessorWriteClass(causal); var copy = new DeferredLabelCopy( staging.Buffer, staging.Offset, destination.Buffer, destination.Offset, source.Length, address, - Kind: LabelCopyKind.CpWrite); + CpuVisible: cpuVisible, Kind: copyKind); var recordHistory = CommandProcessorWriteHistory.Enabled; + var held = _deferredLabelCopies.Count; var serial = EncodeOrderedCopy(in copy, address, recordHistory ? "landed:" + kind : null, recordHistory ? FirstValue(source) : 0, MetalGpuWriteOrigin.Copy, "cp write", kind, size); + NoteCommandProcessorWriteHeld(causal, held); // Parse-time readers see the bytes as written until they land (MetalPendingWriteOverlay). using var bookkeepingScope = SharpEmu.Libs.VideoOut.RenderPhaseProfile.MeasureDetail( @@ -1316,7 +1323,10 @@ private bool TryEncodeCommandProcessorWrite(ulong address, ReadOnlySpan so /// by a completion, the clobber diagnostic - records them one by one before anything has been /// recorded. SHARPEMU_GPU_CP_WRITE_BATCH=0 always does. /// - public void RecordCommandProcessorQwords(ulong address, int count, ulong strideBytes, ulong value, string kind) + public void RecordCommandProcessorQwords(ulong address, int count, ulong strideBytes, ulong value, string kind) => + RecordCommandProcessorQwords(address, count, strideBytes, value, kind, causal: true); + + public void RecordCommandProcessorQwords(ulong address, int count, ulong strideBytes, ulong value, string kind, bool causal) { if (count <= 0) return; if (OnCommandThread) @@ -1329,12 +1339,12 @@ public void RecordCommandProcessorQwords(ulong address, int count, ulong strideB (count == 1 || strideBytes <= (ulong.MaxValue - address - sizeof(ulong)) / (ulong)(count - 1))) { var size = (ulong)(count - 1) * strideBytes + sizeof(ulong); - _commandThread!.PostQwords(() => RecordCommandProcessorQwords(address, count, strideBytes, value, kind), address, size, value, + _commandThread!.PostQwords(() => RecordCommandProcessorQwords(address, count, strideBytes, value, kind, causal), address, size, value, count == 1 ? sizeof(ulong) : strideBytes, UngatedWrites); } else { - RunTagged(() => RecordCommandProcessorQwords(address, count, strideBytes, value, kind)); + RunTagged(() => RecordCommandProcessorQwords(address, count, strideBytes, value, kind, causal)); } return; } @@ -1344,7 +1354,7 @@ public void RecordCommandProcessorQwords(ulong address, int count, ulong strideB if (count > 1 && strideBytes >= sizeof(ulong) && address != 0 && CommandProcessorWriteBatching.Enabled && !GpuClobberDiagnostics.Enabled && strideBytes <= (ulong.MaxValue - address - sizeof(ulong)) / (ulong)(count - 1) && - TryEncodeCommandProcessorQwords(address, count, strideBytes, value, kind)) + TryEncodeCommandProcessorQwords(address, count, strideBytes, value, kind, causal)) { Interlocked.Add(ref _gpuTimedCommandProcessorWrites, count); _batchedCommandProcessorRuns++; @@ -1355,7 +1365,7 @@ public void RecordCommandProcessorQwords(ulong address, int count, ulong strideB System.Buffers.Binary.BinaryPrimitives.WriteUInt64LittleEndian(bytes, value); for (var index = 0; index < count; index++) { - RecordCommandProcessorWrite(address + (ulong)index * strideBytes, bytes, kind); + RecordCommandProcessorWrite(address + (ulong)index * strideBytes, bytes, kind, causal); } } @@ -1366,7 +1376,7 @@ public void RecordCommandProcessorQwords(ulong address, int count, ulong strideB /// Qword runs recorded as one write rather than store by store. internal long BatchedCommandProcessorRuns => _batchedCommandProcessorRuns; - private bool TryEncodeCommandProcessorQwords(ulong address, int count, ulong strideBytes, ulong value, string kind) + private bool TryEncodeCommandProcessorQwords(ulong address, int count, ulong strideBytes, ulong value, string kind, bool causal) { using var phaseScope = SharpEmu.Libs.VideoOut.RenderPhaseProfile.MeasureDetail(SharpEmu.Libs.VideoOut.RenderPhaseProfile.Phase.CommandProcessorWrite); // Declined, not counted: the one-by-one path that follows counts each store it forces. @@ -1381,6 +1391,7 @@ private bool TryEncodeCommandProcessorQwords(ulong address, int count, ulong str } var copies = _cpBatchCopies.AsSpan(0, count); + var (cpuVisible, copyKind) = CommandProcessorWriteClass(causal); for (var index = 0; index < count; index++) { var destination = _guestMemory.ResolveWritable(address + (ulong)index * strideBytes, sizeof(ulong)); @@ -1391,7 +1402,7 @@ private bool TryEncodeCommandProcessorQwords(ulong address, int count, ulong str copies[index] = new DeferredLabelCopy( 0, 0, destination.Buffer, destination.Offset, sizeof(ulong), address + (ulong)index * strideBytes, - Kind: LabelCopyKind.CpWrite); + CpuVisible: cpuVisible, Kind: copyKind); } var staging = _guestMemory.Allocate((ulong)count * sizeof(ulong), sizeof(ulong), out var payload); @@ -1410,8 +1421,10 @@ private bool TryEncodeCommandProcessorQwords(ulong address, int count, ulong str }; } + var held = _deferredLabelCopies.Count; var serial = EncodeOrderedCopies(copies, address, null, 0, MetalGpuWriteOrigin.Copy, "cp write", kind, (ulong)count * sizeof(ulong)); + NoteCommandProcessorWriteHeld(causal, held); // Parse-time readers see the bytes as written until they land (MetalPendingWriteOverlay). using (SharpEmu.Libs.VideoOut.RenderPhaseProfile.MeasureDetail(SharpEmu.Libs.VideoOut.RenderPhaseProfile.Phase.CommandCpBookkeeping)) @@ -1706,6 +1719,7 @@ private void HoldLabelCopies(ReadOnlySpan copies) private void ClearHeldLabelCopies() { _deferredLabelCopies.Clear(); + _causalCpWriteHeld = false; _labelScanEpoch++; if (DeferredLabelFilterEnabled) { @@ -1806,6 +1820,7 @@ private void EncodeLabelBarrier(nint commandBuffer, ReadOnlySpan copies, LabelLandC } } + // SHARPEMU_METAL_V2_CP_WRITE_DEVICE_ORDER (on; =0 off): a command-processor write its queue made with nothing causal + // before it (TakeCommandProcessorWriteCausal: no read of a value not yet landed, no flush, cache action or acquire + // since its previous write) is held device-ordered rather than CPU-visible. On the console such a WRITE_DATA waits + // for no earlier work and publishes nothing for the CPU, so it needs no shared event, and a batch of them lands + // inside the open compute encoder. Every Demon's Souls batch held one and paid the shared event for it. + // =verify keeps every write CPU-visible and counts (cp_write_order_suspects, logged once) the ones that would have + // been device-ordered while some queue had read a pending value since the last shared barrier: a causal read site + // the interpreter does not flag shows up there. + private static readonly string? CpWriteDeviceOrderMode = + Environment.GetEnvironmentVariable("SHARPEMU_METAL_V2_CP_WRITE_DEVICE_ORDER"); + + internal bool CpWritesDeviceOrdered { get; set; } = CpWriteDeviceOrderMode is not ("0" or "verify"); + + private static readonly bool CpWriteDeviceOrderVerify = CpWriteDeviceOrderMode == "verify"; + + // A causal command-processor write is held: every later one is held CPU-visible behind it until the held copies + // land, so none overtakes it and the order of the writes is kept across the landing. + private bool _causalCpWriteHeld; + private long _pendingReadsAtSharedBarrier; + private long _cpWriteOrderSuspects; + + private (bool CpuVisible, LabelCopyKind Kind) CommandProcessorWriteClass(bool causal) + { + var ordered = causal || _causalCpWriteHeld; + if (CpWriteDeviceOrderVerify && !ordered && + SharpEmu.Libs.Gpu.GpuCommands.GpuCommandInterpreter.PendingValueReads != _pendingReadsAtSharedBarrier) + { + _cpWriteOrderSuspects++; + MetalV2Diagnostics.WarnOnce("cp-write-order-suspect", + "A command-processor write its queue did not flag as causal followed a read of a pending value since the " + + "last shared label barrier (SHARPEMU_METAL_V2_CP_WRITE_DEVICE_ORDER=verify)."); + } + + return (!CpWritesDeviceOrdered || ordered, ordered ? LabelCopyKind.CpCausal : LabelCopyKind.CpWrite); + } + + // heldBefore: the held copies before the write was recorded; more now means it was held. + private void NoteCommandProcessorWriteHeld(bool causal, int heldBefore) + { + if (causal && _deferredLabelCopies.Count > heldBefore) + { + _causalCpWriteHeld = true; + } + } + private string TakeLabelLandingCounters() { var text = new System.Text.StringBuilder(256); + text.Append(" cp_write_order_suspects=").Append(Interlocked.Exchange(ref _cpWriteOrderSuspects, 0)); Append(text, "label_land", LabelLandNames, _labelLand); Append(text, "label_batch", LabelBatchNames, _labelBatch); Append(text, "label_barrier", LabelBarrierNames, _labelBarrierKinds); diff --git a/tests/SharpEmu.Gpu.Metal.Tests/MetalEndOfPipeOrderTests.LabelFold.cs b/tests/SharpEmu.Gpu.Metal.Tests/MetalEndOfPipeOrderTests.LabelFold.cs index 7a31e1f00..4f349047b 100644 --- a/tests/SharpEmu.Gpu.Metal.Tests/MetalEndOfPipeOrderTests.LabelFold.cs +++ b/tests/SharpEmu.Gpu.Metal.Tests/MetalEndOfPipeOrderTests.LabelFold.cs @@ -118,6 +118,74 @@ public void TheFoldIsRefusedWithoutTheFenceChainAndWhenSwitchedOff(bool noFence) Assert.Equal(5UL, rig.Backing.Read64(WindowedLabel)); } + // A command-processor write nothing causal came before (no read of a pending value, no flush or acquire on its + // queue) is device-ordered: the dispatch that reads it lands it inside the open compute encoder, with no barrier. + [Fact] + public void APlainCommandProcessorWriteADispatchReadsLandsInTheOpenComputeEncoder() + { + if (!RequireDevice()) return; + using var rig = new Rig(Device.Value); + var host = rig.Host; + Assert.True(host.CpWritesDeviceOrdered); + _ = host.TakeLabelBarriers(); + _ = host.TakeLabelBarrierKinds(); + + _ = host.EnsureComputeEncoder(); + host.RecordCommandProcessorWrite(LaterLabel, BitConverter.GetBytes(0x55UL), "WRITE_DATA", causal: false); + host.OrderAfterDeferredCopies(LaterLabel, 8, MetalRenderHost.LabelLandCause.BindRead); + Assert.True(host.ComputeEncoderOpen); + Assert.Equal(0, host.DeferredLabelCopyCount); + Assert.Equal(0L, host.TakeLabelBarriers()); + var kinds = host.TakeLabelBarrierKinds(); + Assert.Equal(0L, kinds[0]); + Assert.Equal(0L, kinds[1]); + + host.FlushCommandBuffer(); + WaitForGpu(host, host.LastWorkSerial); + WaitForCompletions(host); + Assert.Equal(0x55UL, rig.Backing.Read64(LaterLabel)); + } + + // A causal write (its queue's wait was met by a label not yet landed) stays CPU-visible: it is held, and every write + // after it is held behind it, CPU-visible too, until they land together behind the shared event with the label - + // in Demon's Souls' recycled command memory the store must not reach the guest before the label it waited on. + [Fact] + public void ACausalWriteAndTheWritesAfterItLandBehindTheSharedEventWithTheLabel() + { + if (!RequireDevice()) return; + using var rig = new Rig(Device.Value); + var host = rig.Host; + _ = host.TakeLabelBarriers(); + _ = host.TakeLabelBarrierKinds(); + + _ = host.EnsureComputeEncoder(); + host.RecordEndOfPipe(new EndOfPipeWrite(EndOfPipeWriteKind.WriteBack32, 1, WindowedLabel, 1)); + host.RecordCommandProcessorWrite(LaterLabel, BitConverter.GetBytes(0x55UL), "WRITE_DATA", causal: true); + host.RecordCommandProcessorWrite(LaterLabel + 8, BitConverter.GetBytes(0x66UL), "WRITE_DATA", causal: false); + Assert.Equal(3, host.DeferredLabelCopyCount); + + host.OrderAfterDeferredCopies(LaterLabel + 8, 8, MetalRenderHost.LabelLandCause.BindRead); + Assert.False(host.ComputeEncoderOpen); + Assert.Equal(0, host.DeferredLabelCopyCount); + Assert.Equal(1L, host.TakeLabelBarriers()); + Assert.Equal(new long[] { 1, 0, 0, 0 }, host.TakeLabelBarrierKinds()); + + // Landed, the next plain write is device-ordered again. + _ = host.EnsureComputeEncoder(); + host.RecordCommandProcessorWrite(LaterLabel + 16, BitConverter.GetBytes(0x77UL), "WRITE_DATA", causal: false); + host.OrderAfterDeferredCopies(LaterLabel + 16, 8, MetalRenderHost.LabelLandCause.BindRead); + Assert.True(host.ComputeEncoderOpen); + Assert.Equal(0L, host.TakeLabelBarriers()); + + host.FlushCommandBuffer(); + WaitForGpu(host, host.LastWorkSerial); + WaitForCompletions(host); + Assert.Equal(1u, rig.Backing.Read32(WindowedLabel)); + Assert.Equal(0x55UL, rig.Backing.Read64(LaterLabel)); + Assert.Equal(0x66UL, rig.Backing.Read64(LaterLabel + 8)); + Assert.Equal(0x77UL, rig.Backing.Read64(LaterLabel + 16)); + } + // A write-back label recorded after a GPU store is seen by the CPU only once the store is too: 500 times, the CPU // polls the label and reads the store's last word as soon as it sees it. [Fact] diff --git a/tests/SharpEmu.Libs.Tests/Gpu/GpuCommands/CommandStreamQueueTests.cs b/tests/SharpEmu.Libs.Tests/Gpu/GpuCommands/CommandStreamQueueTests.cs index f359a83a7..04b100d06 100644 --- a/tests/SharpEmu.Libs.Tests/Gpu/GpuCommands/CommandStreamQueueTests.cs +++ b/tests/SharpEmu.Libs.Tests/Gpu/GpuCommands/CommandStreamQueueTests.cs @@ -452,6 +452,40 @@ public void AWaitItsOwnRecordedLabelSatisfiesCommitsNothing() /// memory the guest had already reused. On a host that lands command-processor writes in /// order the store is recorded behind the label instead, and a wait on it is still met. /// + /// + /// A command-processor store is causal only when its queue, since its previous store, read a value not yet landed + /// (a wait met by a recorded label) or flushed, wrote back or acquired: only then does it say the work before it + /// is done, and the host keeps it CPU-visible behind the labels before it. + /// + [Fact] + public void AStoreIsCausalOnlyAfterAPendingReadOrABarrierOnItsQueue() + { + var (host, queue) = NewQueue(); + host.DefersEndOfPipeLabels = true; + host.DefersCommandProcessorWrites = true; + host.PendingLabelTick = 5; + var plain = Label + 0x10; + var afterWait = Label + 0x20; + var next = Label + 0x30; + var afterFlush = Label + 0x40; + var afterAcquire = Label + 0x50; + host.WriteDword(Label, 0); + Enqueue(host, queue, Graphics, 1, + WriteLabel(plain, 1), + ReleaseMemoryInterrupt(Label, 1), WaitEqual(Label, 1), WriteLabel(afterWait, 2), + WriteLabel(next, 3), + StreamRunner.Packet(PacketOpcode.EventWrite, 0x07u | (4u << 8)), WriteLabel(afterFlush, 4)); + Assert.Equal(SliceResult.Completed, queue.ProcessOne()); + + queue.GetInterpreter(0).AcquireMemory(1u << 23, 0); + Enqueue(host, queue, Graphics, 2, WriteLabel(afterAcquire, 5)); + Assert.Equal(SliceResult.Completed, queue.ProcessOne()); + + Assert.Equal( + [(plain, false), (afterWait, true), (next, false), (afterFlush, true), (afterAcquire, true)], + host.CommandProcessorWriteCausal); + } + [Fact] public void AStoreAfterAWaitOnARecordedLabelIsRecordedBehindTheLabel() { diff --git a/tests/SharpEmu.Libs.Tests/Gpu/GpuCommands/CommandStreamTestSupport.cs b/tests/SharpEmu.Libs.Tests/Gpu/GpuCommands/CommandStreamTestSupport.cs index 811804062..b3fe4fd2b 100644 --- a/tests/SharpEmu.Libs.Tests/Gpu/GpuCommands/CommandStreamTestSupport.cs +++ b/tests/SharpEmu.Libs.Tests/Gpu/GpuCommands/CommandStreamTestSupport.cs @@ -277,11 +277,26 @@ public void RecordCommandProcessorWrite(ulong address, ReadOnlySpan source Calls.Add($"cp_write {kind} {address:X} {source.Length}"); } + // Whether each command-processor write the interpreter recorded was causal, in record order. + public List<(ulong Address, bool Causal)> CommandProcessorWriteCausal { get; } = new(); + + public void RecordCommandProcessorWrite(ulong address, ReadOnlySpan source, string kind, bool causal) + { + CommandProcessorWriteCausal.Add((address, causal)); + RecordCommandProcessorWrite(address, source, kind); + } + // A host that takes a run of identical qword stores as one call, as the Metal host does. public bool RecordsQwordRuns { get; set; } public bool PublishesSyntheticOcclusionDumps { get; set; } + public void RecordCommandProcessorQwords(ulong address, int count, ulong strideBytes, ulong value, string kind, bool causal) + { + CommandProcessorWriteCausal.Add((address, causal)); + RecordCommandProcessorQwords(address, count, strideBytes, value, kind); + } + public void RecordCommandProcessorQwords(ulong address, int count, ulong strideBytes, ulong value, string kind) { if (!RecordsQwordRuns) From 4ca89a0f8c752d1e477f07278ae63654bb72aede Mon Sep 17 00:00:00 2001 From: kuba Date: Sun, 15 Nov 2026 06:20:10 +0000 Subject: [PATCH 028/178] [Metal] Record plain command-processor writes as a dispatch in the open compute encoder A command-processor write that is not causal, recorded while a compute encoder is open, is a scatter dispatch between two memory barriers in that encoder at once instead of a held copy: it lands where it was recorded, after all earlier work in device order, and the dispatch that reads it has nothing to land. Held as before when a held copy covers its bytes (by guest address or by destination buffer), when any command-processor write is held, when a staged store over its bytes is still to be written back, or when it is not whole aligned words. label_cp_in_encoder counts them. SHARPEMU_METAL_V2_CP_WRITES_IN_ENCODER=0 off. --- .../V2/MetalCommandStream.cs | 17 +++- .../V2/MetalRenderHost.LabelLanding.cs | 4 + .../V2/MetalRenderHost.LabelScatter.cs | 60 ++++++++++++ .../MetalEndOfPipeOrderTests.LabelFold.cs | 95 +++++++++++++++++++ 4 files changed, 175 insertions(+), 1 deletion(-) diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalCommandStream.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalCommandStream.cs index e832187db..8c62b8f3d 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalCommandStream.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalCommandStream.cs @@ -1015,7 +1015,16 @@ private ulong EncodeOrderedCopies( // what that later work left there. // A GPU-produced snapshot may wait for its producer encoder to end, but must // never be read on the CPU for label replay before that producer has executed. - if ((sourceIsFinal || deferStableGpuResult) && + if (sourceIsFinal && TryEncodeCommandProcessorWritesInEncoder(copies)) + { + // A plain command-processor write lands where it was recorded, as a dispatch in the open compute encoder. + serial = SubmissionSerial; + if (DsTrace.Gpu) + { + _dsLabelDeferred = 0; + } + } + else if ((sourceIsFinal || deferStableGpuResult) && (LabelsAtCommit || (MetalV2Diagnostics.DeferLabelWrites && _renderEncoder != 0) || (DefersCopiesInCompute && _computeEncoder != 0))) @@ -1706,6 +1715,11 @@ private void HoldLabelCopies(ReadOnlySpan copies) _deferredLabelDestinationLow = Math.Min(_deferredLabelDestinationLow, copy.DestinationOffset); _deferredLabelDestinationHigh = Math.Max(_deferredLabelDestinationHigh, copy.DestinationOffset + (ulong)copy.Bytes); _deferredLabelCopies.Add(copy); + if (copy.Kind is LabelCopyKind.CpWrite or LabelCopyKind.CpCausal) + { + _heldCpWrites++; + } + if (DeferredLabelFilterEnabled) { _deferredGuestPages.Add(copy.GuestAddress, (ulong)copy.Bytes); @@ -1720,6 +1734,7 @@ private void ClearHeldLabelCopies() { _deferredLabelCopies.Clear(); _causalCpWriteHeld = false; + _heldCpWrites = 0; _labelScanEpoch++; if (DeferredLabelFilterEnabled) { diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.LabelLanding.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.LabelLanding.cs index 5b3e8dc22..0b702a181 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.LabelLanding.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.LabelLanding.cs @@ -156,6 +156,9 @@ private void NoteLabelLanding(ReadOnlySpan copies, LabelLandC private long _pendingReadsAtSharedBarrier; private long _cpWriteOrderSuspects; + // Command-processor writes recorded as a dispatch in the open compute encoder rather than held (label_cp_in_encoder). + private long _labelCpInEncoder; + private (bool CpuVisible, LabelCopyKind Kind) CommandProcessorWriteClass(bool causal) { var ordered = causal || _causalCpWriteHeld; @@ -184,6 +187,7 @@ private string TakeLabelLandingCounters() { var text = new System.Text.StringBuilder(256); text.Append(" cp_write_order_suspects=").Append(Interlocked.Exchange(ref _cpWriteOrderSuspects, 0)); + text.Append(" label_cp_in_encoder=").Append(Interlocked.Exchange(ref _labelCpInEncoder, 0)); Append(text, "label_land", LabelLandNames, _labelLand); Append(text, "label_batch", LabelBatchNames, _labelBatch); Append(text, "label_barrier", LabelBarrierNames, _labelBarrierKinds); diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.LabelScatter.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.LabelScatter.cs index d52502ca6..a43f6b8c9 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.LabelScatter.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.LabelScatter.cs @@ -298,6 +298,66 @@ private bool TryLandHeldCopiesInComputeEncoder() return true; } + // SHARPEMU_METAL_V2_CP_WRITES_IN_ENCODER (on; =0 off): a command-processor write that is not causal, recorded while a + // compute encoder is open, is a scatter dispatch in that encoder at once instead of a held copy: it lands exactly where + // it was recorded, after all the work before it in device order (the encoder's fence wait and a memory barrier), and a + // dispatch that reads it then has nothing to land. It may land before an earlier held end-of-pipe label at other bytes, + // which the console allows (the command processor does not wait for end-of-pipe). It is held as before when a held + // copy covers its bytes (it must land after that copy: a label still owed into reused command memory), when any + // command-processor write is held (it must not overtake it), when a staged store recorded over its bytes is still to + // be written back at the encoder end, or when it is not whole aligned words. + internal bool CpWritesInEncoder { get; set; } = + Environment.GetEnvironmentVariable("SHARPEMU_METAL_V2_CP_WRITES_IN_ENCODER") != "0"; + + // Command-processor writes held now; a later one is held behind them. + private int _heldCpWrites; + private long _cpWritesEncodedInEncoder; + + /// Command-processor writes recorded as a dispatch in the open compute encoder. + internal long CpWritesEncodedInEncoder => Interlocked.Read(ref _cpWritesEncodedInEncoder); + + private bool TryEncodeCommandProcessorWritesInEncoder(ReadOnlySpan copies) + { + if (!CpWritesInEncoder || _computeEncoder == 0 || _renderEncoder != 0 || _encodingDeferredLabels || + _heldCpWrites != 0 || EncoderOrdering != EncoderOrderingMode.Fence) + { + return false; + } + + foreach (ref readonly var copy in copies) + { + if (copy.Kind != LabelCopyKind.CpWrite || copy.CpuVisible || (copy.Bytes & 3) != 0 || + ((copy.StagingOffset | copy.DestinationOffset) & 3) != 0 || + DeferredLabelCopiesTouch(copy.GuestAddress, (ulong)copy.Bytes) || + // The same bytes through another guest address (an alias of the window) are the same bytes. + DeferredLabelCopiesTouch(new MetalGuestRange(copy.DestinationBuffer, copy.DestinationOffset, (ulong)copy.Bytes, 0)) || + (_stagedStorageCopies is { Count: > 0 } staged && staged.HasRecordedStoresOver(copy.GuestAddress, (ulong)copy.Bytes))) + { + return false; + } + } + + if (!TryBuildLabelScatter(copies, out var list, out var sources, out var buffers, out var count)) + { + return false; + } + + var encoder = _computeEncoder; + NoteRecordedWork(); + MetalV2Native.SendMemoryBarrierScope(encoder, SelComputeMemoryBarrier, Mtl.BarrierScopeBuffers | Mtl.BarrierScopeTextures); + EncodeLabelScatterDispatch(encoder, in list, sources, buffers, count); + MetalV2Native.SendMemoryBarrierScope(encoder, SelComputeMemoryBarrier, Mtl.BarrierScopeBuffers | Mtl.BarrierScopeTextures); + _boundComputePipeline = 0; + _cpWritesEncodedInEncoder += copies.Length; + _labelCpInEncoder += copies.Length; + if (PassProfileEnabled) + { + PassProfileNoteWork("cp-write", "transfer"); + } + + return true; + } + // =verify: what each folded word holds once the submission completes, the last copy into a word winning. private unsafe void VerifyFoldedCopies(ReadOnlySpan copies) { diff --git a/tests/SharpEmu.Gpu.Metal.Tests/MetalEndOfPipeOrderTests.LabelFold.cs b/tests/SharpEmu.Gpu.Metal.Tests/MetalEndOfPipeOrderTests.LabelFold.cs index 4f349047b..a3521942f 100644 --- a/tests/SharpEmu.Gpu.Metal.Tests/MetalEndOfPipeOrderTests.LabelFold.cs +++ b/tests/SharpEmu.Gpu.Metal.Tests/MetalEndOfPipeOrderTests.LabelFold.cs @@ -186,6 +186,101 @@ public void ACausalWriteAndTheWritesAfterItLandBehindTheSharedEventWithTheLabel( Assert.Equal(0x77UL, rig.Backing.Read64(LaterLabel + 16)); } + // A plain command-processor write recorded while a compute encoder is open is a dispatch in that encoder at once + // (SHARPEMU_METAL_V2_CP_WRITES_IN_ENCODER), unless a held copy covers its bytes: Demon's Souls' recycled command + // memory, where a label from an earlier frame is still owed over the bytes the write reuses. That one is held behind + // the label and lands after it. + [Fact] + public void APlainWriteOverAHeldLabelIsHeldBehindItAndLandsAfterIt() + { + if (!RequireDevice()) return; + using var rig = new Rig(Device.Value); + var host = rig.Host; + Assert.True(host.CpWritesInEncoder); + + _ = host.EnsureComputeEncoder(); + host.RecordEndOfPipe(new EndOfPipeWrite(EndOfPipeWriteKind.Write32, 1, WindowedLabel, 0x0BAD)); + var inEncoder = host.CpWritesEncodedInEncoder; + + // Elsewhere, a plain write is a dispatch in the encoder: nothing is held for it. + host.RecordCommandProcessorWrite(LaterLabel + 0x100, BitConverter.GetBytes(0x99UL), "WRITE_DATA", causal: false); + Assert.Equal(1, host.DeferredLabelCopyCount); + Assert.Equal(inEncoder + 1, host.CpWritesEncodedInEncoder); + + host.RecordCommandProcessorWrite(WindowedLabel, BitConverter.GetBytes(0xC0DEu), "WRITE_DATA", causal: false); + Assert.Equal(2, host.DeferredLabelCopyCount); + Assert.Equal(inEncoder + 1, host.CpWritesEncodedInEncoder); + + host.FlushCommandBuffer(); + WaitForGpu(host, host.LastWorkSerial); + WaitForCompletions(host); + Assert.Equal(0xC0DEu, rig.Backing.Read32(WindowedLabel)); + Assert.Equal(0x99UL, rig.Backing.Read64(LaterLabel + 0x100)); + } + + // A held command-processor write keeps every later one held behind it, so none overtakes it: a causal write, then a + // plain one elsewhere and a plain one over the first write's bytes, land in that order. + [Fact] + public void APlainWriteAfterAHeldWriteIsHeldAndTheyLandInOrder() + { + if (!RequireDevice()) return; + using var rig = new Rig(Device.Value); + var host = rig.Host; + + _ = host.EnsureComputeEncoder(); + var inEncoder = host.CpWritesEncodedInEncoder; + host.RecordCommandProcessorWrite(LaterLabel, BitConverter.GetBytes(1UL), "WRITE_DATA", causal: true); + host.RecordCommandProcessorWrite(LaterLabel + 0x40, BitConverter.GetBytes(2UL), "WRITE_DATA", causal: false); + host.RecordCommandProcessorWrite(LaterLabel, BitConverter.GetBytes(3UL), "WRITE_DATA", causal: false); + Assert.Equal(3, host.DeferredLabelCopyCount); + Assert.Equal(inEncoder, host.CpWritesEncodedInEncoder); + + host.FlushCommandBuffer(); + WaitForGpu(host, host.LastWorkSerial); + WaitForCompletions(host); + Assert.Equal(3UL, rig.Backing.Read64(LaterLabel)); + Assert.Equal(2UL, rig.Backing.Read64(LaterLabel + 0x40)); + } + + // A dispatch reading a plain write needs no landing at all, and a device-only label inside a 1 GiB binding the + // dispatch reads lands in the encoder: the encoder stays open. A CPU-visible label in that binding still ends it, + // counted as a read binding forced by a CPU-visible label in a range of 1 GiB or more. + [Fact] + public void ABigReadBindingOverHeldLabelsEndsTheEncoderOnlyForACpuVisibleOne() + { + if (!RequireDevice()) return; + using var rig = new Rig(Device.Value); + var host = rig.Host; + const ulong gib = 1UL << 30; + _ = host.TakeLabelLandCounts(); + _ = host.TakeLabelBarrierKinds(); + + _ = host.EnsureComputeEncoder(); + host.RecordCommandProcessorWrite(LaterLabel, BitConverter.GetBytes(0x55UL), "WRITE_DATA", causal: false); + host.OrderAfterDeferredCopies(LaterLabel, 8, MetalRenderHost.LabelLandCause.BindRead); + Assert.Equal(0, host.DeferredLabelCopyCount); + Assert.All(host.TakeLabelLandCounts(), count => Assert.Equal(0L, count)); + + host.RecordEndOfPipe(new EndOfPipeWrite(EndOfPipeWriteKind.Write64, 1, WindowedLabel, 7)); + host.OrderAfterDeferredCopies(GuestBase, gib, MetalRenderHost.LabelLandCause.BindRead); + Assert.True(host.ComputeEncoderOpen); + Assert.Equal(0, host.DeferredLabelCopyCount); + + host.RecordEndOfPipe(new EndOfPipeWrite(EndOfPipeWriteKind.WriteBack64, 1, WindowedLabel + 8, 8)); + host.OrderAfterDeferredCopies(GuestBase, gib, MetalRenderHost.LabelLandCause.BindRead); + Assert.False(host.ComputeEncoderOpen); + var lands = host.TakeLabelLandCounts(); + Assert.Equal(2L, lands[(int)MetalRenderHost.LabelLandCause.BindRead - 1]); + Assert.Equal(new long[] { 1, 0, 0, 1 }, host.TakeLabelBarrierKinds()); + + host.FlushCommandBuffer(); + WaitForGpu(host, host.LastWorkSerial); + WaitForCompletions(host); + Assert.Equal(0x55UL, rig.Backing.Read64(LaterLabel)); + Assert.Equal(7UL, rig.Backing.Read64(WindowedLabel)); + Assert.Equal(8UL, rig.Backing.Read64(WindowedLabel + 8)); + } + // A write-back label recorded after a GPU store is seen by the CPU only once the store is too: 500 times, the CPU // polls the label and reads the store's last word as soon as it sees it. [Fact] From 76d34bc9c18f200b9186de7e7d9e22275d7a6c70 Mon Sep 17 00:00:00 2001 From: kuba Date: Sun, 15 Nov 2026 06:26:44 +0000 Subject: [PATCH 029/178] [Metal] Copy layer subsets of aliased arrays on the device; count alias outcomes Two cached arrays over the same guest bytes that lay their layers out identically (a 64- and a 72-layer array on one base, a surface placed on a layer of an array) now hand the shared layers over with a slice copy between their textures instead of a writeback of one and an upload of the other. MetalImageTransfer.TryMatchLayerSubset proves the match layer by layer, including the slice term of the 64 KiB render-target swizzle. SHARPEMU_METAL_V2_ALIAS_SUBSET_DEVICE=0 restores the round trip; =verify (or SHARPEMU_PERF_VERIFY=1) retiles both sides of each copy and compares them. Counter truth: round-trip now counts only pairs that went through guest memory, split into published-run and published-whole; layout skips, moved writeback and blit bytes, and device-subset copies are counted on their own. Alias trace lines name the use (role) and the bytes it wrote back. The stale keep in RefreshFromGuestCore is now a warning with a counter (alias_run_refresh_refused); its behaviour is unchanged. --- .../V2/MetalImageCache.AliasSubset.cs | 244 ++++++++++++++++ .../V2/MetalImageCache.AliasTrace.cs | 11 +- .../V2/MetalImageCache.AliasTransitions.cs | 35 ++- .../V2/MetalImageCache.DeferredRefresh.cs | 2 +- .../SharpEmu.Gpu.Metal/V2/MetalImageCache.cs | 39 ++- .../V2/MetalImageTransfer.LayerSubset.cs | 207 ++++++++++++++ .../SharpEmu.Gpu.Metal/V2/MetalV2Contracts.cs | 13 + .../MetalImageAliasTests.Subset.cs | 262 ++++++++++++++++++ 8 files changed, 800 insertions(+), 13 deletions(-) create mode 100644 src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.AliasSubset.cs create mode 100644 src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageTransfer.LayerSubset.cs create mode 100644 tests/SharpEmu.Gpu.Metal.Tests/MetalImageAliasTests.Subset.cs diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.AliasSubset.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.AliasSubset.cs new file mode 100644 index 000000000..a5c3d51ed --- /dev/null +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.AliasSubset.cs @@ -0,0 +1,244 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using System.Globalization; +using System.Runtime.InteropServices; +using SharpEmu.Libs.Gpu.Images; + +namespace SharpEmu.Gpu.Metal.V2; + +/// +/// An alias that shares whole layers with a GPU-written image, laid out the same way (MetalImageTransfer.LayerSubset), +/// takes those layers by a slice copy between the two textures instead of a writeback of the one and an upload of the +/// other. Demon's Souls keeps a 64-layer and a 72-layer 160x90 array on one base: each use of either moved 16-18 MiB +/// out through guest memory and back, every frame. The copy leaves the target holding exactly the texels the round +/// trip would have; guest memory is not written, and does not need to be: the source stays GPU-modified (a read) or +/// the target becomes the owner (a write), so the lazy writeback rules publish the bytes when anything asks for them. +/// +internal sealed partial class MetalImageCache +{ + // SHARPEMU_METAL_V2_ALIAS_SUBSET_DEVICE (on; =0 sends such aliases through guest memory again; =verify, or + // SHARPEMU_PERF_VERIFY=1, also retiles both sides of every copy into scratch and compares them once the command + // buffer completed, logging [METAL-V2][ALIAS-VERIFY] and counting a mismatch). + private static readonly string? AliasSubsetSetting = + Environment.GetEnvironmentVariable("SHARPEMU_METAL_V2_ALIAS_SUBSET_DEVICE"); + + internal bool AliasSubsetDeviceEnabled { get; set; } = AliasSubsetSetting != "0"; + + internal bool AliasSubsetVerify { get; set; } = + AliasSubsetSetting == "verify" || Environment.GetEnvironmentVariable("SHARPEMU_PERF_VERIFY") == "1"; + + private long _aliasSubsetCopies, _aliasSubsetBytes; + private long _aliasSubsetVerified, _aliasSubsetMismatches, _aliasSubsetUnverified; + + private sealed record AliasSubsetCheck(ulong Serial, nint Copied, nint RoundTripped, ulong Size, string Pair); + + private readonly List _aliasSubsetChecks = []; + + private static readonly nint SelSubsetNewBuffer = MetalNative.Selector("newBufferWithLength:options:"); + private static readonly nint SelSubsetContents = MetalNative.Selector("contents"); + private static readonly nint SelSubsetRelease = MetalNative.Selector("release"); + + /// Copies, bytes, verified copies, verify mismatches and copies the verify could not retile. + internal (long Copies, long Bytes, long Verified, long Mismatches, long Unverified) AliasSubsetCounters => + (Interlocked.Read(ref _aliasSubsetCopies), Interlocked.Read(ref _aliasSubsetBytes), + Interlocked.Read(ref _aliasSubsetVerified), Interlocked.Read(ref _aliasSubsetMismatches), + Interlocked.Read(ref _aliasSubsetUnverified)); + + // The other image is GPU-modified and not stale over the run the two share (the loop checked both). Caller holds + // the lock. False, with nothing encoded and neither image changed, unless the pair is one MetalImageTransfer + // matches layer for layer and the copy leaves the target current over the whole run. + private bool TryPublishAliasLayerSubset( + MetalCachedImage image, MetalCachedImage other, bool takesGpuOwnership, ulong otherStart, ulong otherEnd) + { + if (!AliasSubsetDeviceEnabled || image.Texture == 0 || other.Texture == 0 || image.Texture == other.Texture || + image.IsWindowLinearView || other.IsWindowLinearView || image.FirstLevel != 0 || other.FirstLevel != 0 || + SparseOf(image) is not null || SparseOf(other) is not null || + image.Shape.PixelFormat != other.Shape.PixelFormat || image.Shape.SampleCount != other.Shape.SampleCount || + image.Shape.Width != other.Shape.Width || image.Shape.Height != other.Shape.Height || + image.Shape.MipLevels != 1 || other.Shape.MipLevels != 1 || + !_transfer.TryMatchLayerSubset( + in other.Description, in image.Description, out var sourceFirst, out var targetFirst, out var layers)) + { + return false; + } + + // The matched layers are the whole of what the two share: both sizes are whole numbers of layers. + var stride = image.Description.Data.Size / image.Description.Resources.Layers; + var sourceStart = sourceFirst * stride; + var sourceEnd = sourceStart + layers * stride; + var targetStart = targetFirst * stride; + var targetEnd = targetStart + layers * stride; + var otherInside = sourceStart == 0 && sourceEnd == other.Description.Data.Size; + if (sourceStart != otherStart || sourceEnd != otherEnd || + (other.IsCpuDirty && (other.DirtyEnd <= other.DirtyStart || (other.DirtyStart < sourceEnd && other.DirtyEnd > sourceStart))) || + !CopyLeavesRunCurrent(image, targetStart, targetEnd) || + // A write leaves the other image stale over the run and GPU-modified for the rest; one stale interval + // cannot hold the run apart from one it already has, and widening it would cover bytes only its texture holds. + (takesGpuOwnership && !otherInside && other.IsCpuDirty && + (other.DirtyEnd < sourceStart || other.DirtyStart > sourceEnd))) + { + return false; + } + + EnsureSparseBacked(image); + var context = _owner.BeginTransfer(MetalTransferCause.Writeback, other.Texture, image.Texture); + if (!_transfer.TryEncodeLayerSubsetCopy( + context, other.Texture, sourceFirst, image.Texture, targetFirst, layers, image.Shape.Width, image.Shape.Height)) + { + return false; + } + + if (context.WantsEncodedLabels) + { + context.ProfileEncoded(ProfileLabel("alias-subset", in image.Description)); + } + + if (AliasSubsetVerify) + { + EncodeAliasSubsetCheck(context, image, other, targetStart, sourceStart, sourceEnd - sourceStart); + } + + // The texture changed whether or not it was stale there; then it is current over the run. A new image is + // stale over an empty interval, which means all of it: that is named first, or the cut would clear it all. + if (image.IsCpuDirty && image.DirtyEnd <= image.DirtyStart) + { + image.MarkCpuDirty(image.DirtyCause, 0, image.Description.Data.Size); + } + + image.NoteContentChanged(); + image.RefreshComplete(targetStart, targetEnd); + if (takesGpuOwnership) + { + if (otherInside) + { + other.ClearGpuModified(); + other.MarkCpuDirty(MetalImageDirtyCause.AliasWrite); + } + else + { + // As a narrow hand-over leaves it, without the publication: the bytes went to this image's texture, + // which owns them from this write on. + other.MarkCpuDirty(MetalImageDirtyCause.AliasWrite, sourceStart, sourceEnd); + } + } + + _aliasSubsetCopies++; + _aliasSubsetBytes += (long)(sourceEnd - sourceStart); + _aliasMovedBlitBytes += (long)(sourceEnd - sourceStart); + return true; + } + + // Whether marking [start, end) refreshed leaves none of it stale: one stale interval cannot lose its middle + // (MetalCachedImage.RefreshComplete), and a refresh of what stays stale would put the guest's older bytes back + // over the copy. + // An empty stale interval on a dirty image is a new one, stale over all of it. + private static bool CopyLeavesRunCurrent(MetalCachedImage image, ulong start, ulong end) + { + if (!image.IsCpuDirty) + { + return true; + } + + var (dirtyStart, dirtyEnd) = image.DirtyEnd > image.DirtyStart + ? (image.DirtyStart, image.DirtyEnd) + : (0UL, image.Description.Data.Size); + return dirtyEnd <= start || dirtyStart >= end || start <= dirtyStart || end >= dirtyEnd; + } + + // Verify mode: what the round trip would have published (the source's run, retiled) and what the copy put in the + // target (the target's run, retiled the same way) go to two scratch buffers, compared once the command buffer + // completed. Identical layouts retile identical texels to identical bytes. Caller holds the lock. + private void EncodeAliasSubsetCheck( + IMetalSubmissionContext context, MetalCachedImage image, MetalCachedImage other, + ulong targetStart, ulong sourceStart, ulong size) + { + var copied = NewSubsetScratch(size); + var roundTripped = NewSubsetScratch(size); + if (copied == 0 || roundTripped == 0 || + !_transfer.EncodeTextureToGuest( + context, in other.Description, + new SubresourceRange(0, other.Description.Resources.Levels, 0, other.Description.TransferLayers), + other.Texture, new MetalGuestRange(roundTripped, 0, size, 0), default, sourceStart, size) || + !_transfer.EncodeTextureToGuest( + context, in image.Description, + new SubresourceRange(0, image.Description.Resources.Levels, 0, image.Description.TransferLayers), + image.Texture, new MetalGuestRange(copied, 0, size, 0), default, targetStart, size)) + { + ReleaseSubsetScratch(copied); + ReleaseSubsetScratch(roundTripped); + _aliasSubsetUnverified++; + return; + } + + _aliasSubsetChecks.Add(new AliasSubsetCheck( + context.SubmissionSerial, copied, roundTripped, size, + $"target=<{AliasImageText(in image.Description)}> source=<{AliasImageText(in other.Description)}> " + + $"target_run=0x{targetStart:X} source_run=0x{sourceStart:X}+0x{size:X}")); + } + + private unsafe nint NewSubsetScratch(ulong size) + { + var buffer = MetalNative.SendNewBuffer(_owner.Device, SelSubsetNewBuffer, (nuint)size, 0); + if (buffer != 0) + { + NativeMemory.Clear((void*)MetalNative.Send(buffer, SelSubsetContents), (nuint)size); + } + + return buffer; + } + + private static void ReleaseSubsetScratch(nint buffer) + { + if (buffer != 0) + { + MetalNative.SendVoid(buffer, SelSubsetRelease); + } + } + + /// Compares every verify-mode copy whose command buffer completed. Caller holds the lock. + internal unsafe void DrainAliasSubsetChecksLocked() + { + if (_aliasSubsetChecks.Count == 0) + { + return; + } + + var completed = _owner.CompletedSerial; + for (var index = 0; index < _aliasSubsetChecks.Count;) + { + var check = _aliasSubsetChecks[index]; + if (check.Serial > completed) + { + index++; + continue; + } + + _aliasSubsetChecks.RemoveAt(index); + var copied = new ReadOnlySpan((void*)MetalNative.Send(check.Copied, SelSubsetContents), (int)check.Size); + var roundTripped = new ReadOnlySpan( + (void*)MetalNative.Send(check.RoundTripped, SelSubsetContents), (int)check.Size); + var first = copied.CommonPrefixLength(roundTripped); + Interlocked.Increment(ref _aliasSubsetVerified); + if (first != copied.Length) + { + if (Interlocked.Increment(ref _aliasSubsetMismatches) <= 16) + { + Console.Error.WriteLine( + $"[METAL-V2][ALIAS-VERIFY] a layer-subset copy differs from the round trip at run byte " + + $"0x{first.ToString("X", CultureInfo.InvariantCulture)}: {check.Pair}"); + } + } + + ReleaseSubsetScratch(check.Copied); + ReleaseSubsetScratch(check.RoundTripped); + } + } + + /// Test hook: compares the completed verify-mode copies. + internal void DrainAliasSubsetChecks() + { + using var held = _lock.Hold(); + DrainAliasSubsetChecksLocked(); + } +} diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.AliasTrace.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.AliasTrace.cs index 36b12b9db..9e1a102cb 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.AliasTrace.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.AliasTrace.cs @@ -89,7 +89,7 @@ private void NoteAliasFallback( var because = write ? $"reason={reason}" : $"reason=ReadUse detail={reason}"; Console.Error.WriteLine( $"[METAL-V2][ALIAS-TRACE] decline use={(write ? "write" : "read")} {because} " + - AliasPairText(image, other, otherGpuModified, runStart, runEnd)); + AliasPairText(image, other, otherGpuModified, runStart, runEnd) + AliasUseText()); } // Logs an alias publication with the trace on. Caller holds the lock. @@ -105,9 +105,16 @@ private void NoteAliasPublication( Console.Error.WriteLine( $"[METAL-V2][ALIAS-TRACE] publish kind={kind} " + - AliasPairText(image, other, otherGpuModified, runStart, runEnd)); + AliasPairText(image, other, otherGpuModified, runStart, runEnd) + AliasUseText()); } + // The requester's use (rt-overwrite is a colour target whose pass is proven to overwrite it; rt-load one whose + // pass loads or is not proven), and the guest bytes written back for this pair so far in this sync step. + private string _aliasSyncRole = "other"; + private long _aliasTraceMark; + + private string AliasUseText() => $" role={_aliasSyncRole} moved_wb=0x{_writebackBytes - _aliasTraceMark:X}"; + // gpu_mod is the requester's and the other image's state when the alias was found, // before any writeback cleared it. private static string AliasPairText( diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.AliasTransitions.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.AliasTransitions.cs index cb7902b08..00e70a5a4 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.AliasTransitions.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.AliasTransitions.cs @@ -17,7 +17,26 @@ internal sealed partial class MetalImageCache internal bool AliasTransitionsEnabled { get; set; } = AliasTransitionsDefault; private long _aliasFused, _aliasFusedBytes, _aliasDiscarded, _aliasDiscardedBytes; + // round-trip counts only pairs whose bytes went through guest memory: a run or the whole other image + // published (and this one reloaded). A layout skip moves nothing and is counted on its own. private long _aliasRoundTrip, _aliasRoundTripBytes; + private long _aliasPublishedRuns, _aliasPublishedWholes, _aliasLayoutSkips; + private long _aliasMovedWritebackBytes, _aliasMovedBlitBytes; + private long _aliasRunRefreshRefused; + + private void NoteAliasRoundTrip(bool whole, ulong sharedSize) + { + _aliasRoundTrip++; + _aliasRoundTripBytes += (long)sharedSize; + if (whole) + { + _aliasPublishedWholes++; + } + else + { + _aliasPublishedRuns++; + } + } private long _aliasCpuReadRuns, _aliasCpuReadBytes; private readonly Dictionary _aliasTransitionRefusals = new(StringComparer.Ordinal); @@ -40,8 +59,20 @@ internal string TakeAliasTransitionText() var readRuns = Interlocked.Exchange(ref _aliasCpuReadRuns, 0); var readBytes = Interlocked.Exchange(ref _aliasCpuReadBytes, 0); var consumers = TakeConsumerRuns(); - return $"alias_transitions=[fused:{counts.Fused},discarded:{counts.Discarded},round-trip:{counts.RoundTrip}] " + - $"alias_mib=[fused:{Mb(counts.FusedBytes)},discarded:{Mb(counts.DiscardedBytes)},round-trip:{Mb(counts.RoundTripBytes)}] " + + DrainAliasSubsetChecksLocked(); + var subsetCopies = Interlocked.Exchange(ref _aliasSubsetCopies, 0); + var subsetBytes = Interlocked.Exchange(ref _aliasSubsetBytes, 0); + return $"alias_transitions=[fused:{counts.Fused},discarded:{counts.Discarded},device-subset:{subsetCopies}," + + $"round-trip:{counts.RoundTrip},published-run:{Interlocked.Exchange(ref _aliasPublishedRuns, 0)}," + + $"published-whole:{Interlocked.Exchange(ref _aliasPublishedWholes, 0)}," + + $"layout-skip:{Interlocked.Exchange(ref _aliasLayoutSkips, 0)}] " + + $"alias_mib=[fused:{Mb(counts.FusedBytes)},discarded:{Mb(counts.DiscardedBytes)},device-subset:{Mb(subsetBytes)}," + + $"round-trip:{Mb(counts.RoundTripBytes)}] " + + $"alias_moved_mib=[wb:{Mb(Interlocked.Exchange(ref _aliasMovedWritebackBytes, 0))}," + + $"blit:{Mb(Interlocked.Exchange(ref _aliasMovedBlitBytes, 0))}] " + + $"alias_run_refresh_refused={Interlocked.Exchange(ref _aliasRunRefreshRefused, 0)} " + + $"alias_subset_verify=[checked:{Interlocked.Exchange(ref _aliasSubsetVerified, 0)}," + + $"mismatch:{Interlocked.Read(ref _aliasSubsetMismatches)},unverified:{Interlocked.Exchange(ref _aliasSubsetUnverified, 0)}] " + $"alias_transition_refused=[{refusals}] alias_cpu_read_runs={readRuns} " + $"alias_cpu_read_requested_mib={Mb(readBytes)} " + $"consumer_runs=[published:{consumers.Runs},skipped:{consumers.AlreadyPublished},gpu_writes_kept:{consumers.GpuWritesKept}] " + diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.DeferredRefresh.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.DeferredRefresh.cs index 79501784d..7c91b2dcc 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.DeferredRefresh.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.DeferredRefresh.cs @@ -248,7 +248,7 @@ private void CompleteDeferredLocked(in DeferredRefresh entry, bool overwritten) var image = entry.Image; if (entry.AliasesPending && (!overwritten || !TryDiscardOverwrittenAliases(entry.Identifier))) { - SynchronizeAliases(entry.Identifier, takesGpuOwnership: true); + SynchronizeAliases(entry.Identifier, takesGpuOwnership: true, role: overwritten ? "rt-overwrite" : "rt-load"); } if (overwritten && image.IsCpuDirty) { diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.cs index ef5c7bf73..2eac63103 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.cs @@ -526,10 +526,13 @@ private static bool IsOneLevelOf(in ImageDescription level, in ImageDescription /// Alias syncs that kept this image's newer contents instead of publishing an older alias. public long TakeAliasNewerKept() => Interlocked.Exchange(ref _aliasNewerKept, 0); + // role names the use for the alias trace: rt, rt-overwrite, rt-load, depth, depth-read, storage, texture, other. private void SynchronizeAliases( - ResourceSlotIdentifier imageIdentifier, bool takesGpuOwnership, bool keepsDepthPlane = false) + ResourceSlotIdentifier imageIdentifier, bool takesGpuOwnership, bool keepsDepthPlane = false, + string role = "other") { var image = _slots[imageIdentifier]; + _aliasSyncRole = role; var address = image.Description.Data.Address; var size = image.Description.Data.Size; if (takesGpuOwnership) @@ -562,6 +565,7 @@ private void SynchronizeAliases( var alone = true; _syncedScratch.Clear(); + var writtenBefore = _writebackBytes; foreach (var otherIdentifier in FindImagesInRange(address, size, pageOverlap: false)) { if (otherIdentifier == imageIdentifier || @@ -589,6 +593,7 @@ private void SynchronizeAliases( // 19 MiB target used to cost a full retile of one and a full detile of // the other, every time the pair was used. ReportAliasPair(image, other); + _aliasTraceMark = _writebackBytes; var sharedStart = Math.Max(image.Description.Data.Address, other.Description.Data.Address); var sharedEnd = Math.Min( image.Description.Data.Address + image.Description.Data.Size, @@ -628,6 +633,17 @@ private void SynchronizeAliases( continue; } + if ((image.Description.Data.Address != other.Description.Data.Address || + image.Description.Data.Size != other.Description.Data.Size) && + TryPublishAliasLayerSubset(image, other, takesGpuOwnership, otherStart, otherEnd)) + { + // Whole layers laid out alike: a slice copy is what the round trip would leave in this + // texture (MetalImageCache.AliasSubset), and it settled the other image's ownership by use. + _aliasPublishes++; + NoteAliasPublication("device-subset", image, other, otherOwedGuestMemory, otherStart, otherEnd); + continue; + } + var reusesBefore = _deviceAliasReuses; if (TryPublishAliasOnDevice(image, other)) { @@ -661,8 +677,6 @@ private void SynchronizeAliases( continue; } - _aliasRoundTrip++; - _aliasRoundTripBytes += (long)sharedSize; var (dirtyStart, dirtyEnd) = image.OverlapWithin(sharedStart, sharedSize); var declined = MetalAliasFallbackReason.None; if (takesGpuOwnership && TryHandOverAliasRun(other, otherStart, otherEnd, out declined)) @@ -674,6 +688,7 @@ private void SynchronizeAliases( MarkAliasRunDirty(image, dirtyStart, dirtyEnd); _aliasPublishes++; _aliasNarrowWrites++; + NoteAliasRoundTrip(whole: false, sharedSize); NoteAliasPublication("narrow-write", image, other, otherOwedGuestMemory, otherStart, otherEnd); continue; } @@ -687,6 +702,7 @@ private void SynchronizeAliases( // image does not reload it. Guest memory there is stale until this image's own write is published. other.MarkCpuDirty(MetalImageDirtyCause.AliasWrite, otherStart, otherEnd); _aliasWritesDiscarded++; + _aliasLayoutSkips++; continue; } @@ -700,6 +716,7 @@ private void SynchronizeAliases( // going out through guest memory and back in. The trailing ownership step below still // runs for it. _aliasWritesDiscarded++; + _aliasLayoutSkips++; } else if (takesGpuOwnership) { @@ -709,11 +726,13 @@ private void SynchronizeAliases( // follows to replace with the stale guest bytes. NoteAliasFallback(write: true, declined, image, other, otherOwedGuestMemory, otherStart, otherEnd); WriteBackToGuest(other, MetalWritebackCause.ImageOverlap); + NoteAliasRoundTrip(whole: true, sharedSize); NoteAliasPublication("whole-write", image, other, otherOwedGuestMemory, otherStart, otherEnd); } else { var whole = PublishAliasRange(other, sharedStart, sharedSize); + NoteAliasRoundTrip(whole != MetalAliasFallbackReason.None, sharedSize); if (whole != MetalAliasFallbackReason.None) { NoteAliasFallback(write: false, whole, image, other, otherOwedGuestMemory, otherStart, otherEnd); @@ -765,6 +784,7 @@ private void SynchronizeAliases( } } + _aliasMovedWritebackBytes += _writebackBytes - writtenBefore; image.AlonePageVersions = alone ? pageVersions : -1; RecordSync(image, alone, pageVersions, kind); } @@ -1422,7 +1442,7 @@ private nint AcquireTextureViewLocked(ResourceSlotIdentifier imageIdentifier, in EnsureStorageUsageLocked(image); EnsureSparseBacked(image); WatchImage(imageIdentifier); - SynchronizeAliases(imageIdentifier, takesGpuOwnership: true); + SynchronizeAliases(imageIdentifier, takesGpuOwnership: true, role: "storage"); RefreshFromGuest(image); image.Uses.Storage = true; image.MarkGpuModified(); @@ -1452,7 +1472,7 @@ private nint AcquireTextureViewLocked(ResourceSlotIdentifier imageIdentifier, in } WatchImage(imageIdentifier); - SynchronizeAliases(imageIdentifier, takesGpuOwnership: false); + SynchronizeAliases(imageIdentifier, takesGpuOwnership: false, role: "texture"); RefreshFromGuest(image); image.Uses.Texture = true; image.NoteUse(_owner.CurrentSerial); @@ -1750,7 +1770,8 @@ public nint AcquireDepthTargetView( var stencil = request.Description.HasStencil ? ImageStencilPlane(in image.Description, in request.Description) : default; - SynchronizeAliases(imageIdentifier, takesGpuOwnership: writes, keepsDepthPlane: stencilOnly); + SynchronizeAliases( + imageIdentifier, takesGpuOwnership: writes, keepsDepthPlane: stencilOnly, role: writes ? "depth" : "depth-read"); // Only a target the pass writes can be one it clears. The refresh reads the // stencil plane from where the image has it, so a request that moves the plane // refreshes now, before the description changes. @@ -2777,8 +2798,10 @@ private void RefreshFromGuestCore(MetalCachedImage image) { // Stale over a run an alias took while the texture still owns the rest: a // whole upload would replace bytes guest memory was never given. The run - // stays stale rather than costing them. - MetalV2Diagnostics.InfoOnce( + // stays stale rather than costing them - which serves the texture's older + // bytes there, so it is counted (alias_run_refresh_refused) and warned about. + Interlocked.Increment(ref _aliasRunRefreshRefused); + MetalV2Diagnostics.WarnOnce( $"alias-run-refresh:{description.PixelFormat}:{description.Extent.Width}x{description.Extent.Height}", "A GPU-written image stale over an alias run could not reload just that run, so it keeps " + $"its texture there: {description.PixelFormat} {description.Extent.Width}x{description.Extent.Height} " + diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageTransfer.LayerSubset.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageTransfer.LayerSubset.cs new file mode 100644 index 000000000..67ee5c7f2 --- /dev/null +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageTransfer.LayerSubset.cs @@ -0,0 +1,207 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using SharpEmu.Libs.Gpu.Images; + +namespace SharpEmu.Gpu.Metal.V2; + +// Two cached images over the same guest bytes that lay their layers out identically - a 64-layer and a 72-layer +// array from one base, or a one-layer surface placed on a layer of an array - map every shared guest byte to the +// same texel of the same format. A copy of those slices between their textures is then exactly what a writeback of +// one and an upload of the other through guest memory would leave in the target. +internal sealed partial class MetalImageTransfer +{ + private static readonly nint SelCopyTextureSlice = MetalNative.Selector( + "copyFromTexture:sourceSlice:sourceLevel:sourceOrigin:sourceSize:" + + "toTexture:destinationSlice:destinationLevel:destinationOrigin:"); + + /// + /// Whether target layers [, + ) lie on exactly the + /// guest bytes of source layers [, + ), byte for byte + /// the same texels, and no other target layer touches a source byte. False for anything else: a depth or stencil + /// plane, a volume, a mip chain, multisampling, a different format, extent, pitch or tile mode, a layer stride that + /// differs or is not a whole multiple of the address difference, a guest size that is not a whole number of + /// layers, and a tile mode that swizzles by slice index (RenderTarget and Depth 64 KiB blocks) at a layer offset + /// other than zero, since the same bytes then hold different texels in each. + /// + public bool TryMatchLayerSubset( + in ImageDescription source, in ImageDescription target, + out uint sourceFirstLayer, out uint targetFirstLayer, out uint layers) + { + sourceFirstLayer = 0; + targetFirstLayer = 0; + layers = 0; + if (_disposed || !SameLayerShape(in source, in target)) + { + return false; + } + + var sourcePlan = PlanFor(source); + var targetPlan = PlanFor(target); + if (sourcePlan.DepthStencil || targetPlan.DepthStencil || sourcePlan.Volume || targetPlan.Volume || + sourcePlan.Tiled != targetPlan.Tiled || sourcePlan.Swap != targetPlan.Swap || + sourcePlan.Format != targetPlan.Format || + !TryLayerStride(sourcePlan, source.Resources.Layers, out var stride) || + !TryLayerStride(targetPlan, target.Resources.Layers, out var targetStride) || stride != targetStride || + source.Data.Size != stride * source.Resources.Layers || target.Data.Size != stride * target.Resources.Layers) + { + return false; + } + + // Target layer t sits on source layer t + shift. + long shift; + if (target.Data.Address >= source.Data.Address) + { + var delta = target.Data.Address - source.Data.Address; + if (delta % stride != 0 || delta / stride >= source.Resources.Layers) + { + return false; + } + + shift = (long)(delta / stride); + } + else + { + var delta = source.Data.Address - target.Data.Address; + if (delta % stride != 0 || delta / stride >= target.Resources.Layers) + { + return false; + } + + shift = -(long)(delta / stride); + } + + var first = shift < 0 ? -shift : 0; + var end = Math.Min((long)target.Resources.Layers, source.Resources.Layers - shift); + if (end <= first) + { + return false; + } + + for (var layer = first; layer < end; layer++) + { + if (!SameLayerLayout(sourcePlan, (int)(layer + shift), targetPlan, (int)layer)) + { + return false; + } + } + + sourceFirstLayer = (uint)(first + shift); + targetFirstLayer = (uint)first; + layers = (uint)(end - first); + return true; + } + + private static bool SameLayerShape(in ImageDescription source, in ImageDescription target) => + source.Type is GuestImageType.Color2D or GuestImageType.Color2DArray && + target.Type is GuestImageType.Color2D or GuestImageType.Color2DArray && + !source.IsDepth && !target.IsDepth && !source.HasStencil && !target.HasStencil && + source.Stencil.Size == 0 && target.Stencil.Size == 0 && + source.Samples == 1 && target.Samples == 1 && + source.Resources.Levels == 1 && target.Resources.Levels == 1 && + source.Resources.Layers != 0 && target.Resources.Layers != 0 && + source.GuestFormat == target.GuestFormat && source.PixelFormat == target.PixelFormat && + source.TileMode == target.TileMode && source.Bgra16 == target.Bgra16 && + source.Extent.Width == target.Extent.Width && source.Extent.Height == target.Extent.Height && + source.Extent.Depth <= 1 && target.Extent.Depth <= 1 && + source.Pitch == target.Pitch && source.BytesPerBlock == target.BytesPerBlock && + !ImageDescription.IsEmptyRange(source.Data) && !ImageDescription.IsEmptyRange(target.Data); + + // The guest distance between consecutive layers, confirmed against every layer's transfer: one tile transfer or + // one copy per layer (one level), each at a whole number of strides from the first. + private static bool TryLayerStride(TransferPlan plan, uint layers, out ulong stride) + { + stride = 0; + if (plan.Tiled) + { + stride = plan.Layout.SourceSliceStride != 0 ? plan.Layout.SourceSliceStride : plan.Layout.Surface.BlockSliceSize; + if (stride == 0 || plan.Tiles.Count != layers) + { + return false; + } + + for (var layer = 0; layer < plan.Tiles.Count; layer++) + { + if (plan.Tiles[layer].Slice != (uint)layer || plan.Tiles[layer].Level != 0 || + plan.Tiles[layer].TiledOffset != plan.Tiles[0].TiledOffset + (ulong)layer * stride || + plan.Tiles[layer].TiledOffset + plan.Tiles[layer].TiledSize > ((ulong)layer + 1) * stride) + { + return false; + } + } + + return true; + } + + stride = plan.Layout.SliceStride; + if (stride == 0 || plan.Copies.Count != layers) + { + return false; + } + + for (var layer = 0; layer < plan.Copies.Count; layer++) + { + if (plan.Copies[layer].Slice != (uint)layer || plan.Copies[layer].Level != 0 || + plan.Copies[layer].BufferOffset != plan.Copies[0].BufferOffset + (ulong)layer * stride || + CopyEnd(plan, plan.Copies[layer]) > ((ulong)layer + 1) * stride) + { + return false; + } + } + + return true; + } + + // One layer of each plan, compared field by field except where in the image it sits (its offsets and slice): the + // swizzle's slice term (SurfaceZ) is compared, so a slice-swizzled mode matches only at the same layer index. + private static bool SameLayerLayout(TransferPlan sourcePlan, int sourceLayer, TransferPlan targetPlan, int targetLayer) + { + if (sourcePlan.Tiled) + { + var a = sourcePlan.Tiles[sourceLayer]; + var b = targetPlan.Tiles[targetLayer]; + return a.Kind == b.Kind && a.BytesPerElement == b.BytesPerElement && a.TiledSize == b.TiledSize && + a.LinearSize == b.LinearSize && a.LinearSliceStride == b.LinearSliceStride && + a.Width == b.Width && a.Height == b.Height && a.Depth == b.Depth && a.Pitch == b.Pitch && + a.TailX == b.TailX && a.TailY == b.TailY && a.Tail == b.Tail && + a.TiledWidth == b.TiledWidth && a.TiledHeight == b.TiledHeight && + a.SurfaceZ == b.SurfaceZ && a.BaseY == b.BaseY && + // TryLayerStride put every layer at its first layer's offset plus whole strides. + sourcePlan.Tiles[0].TiledOffset == targetPlan.Tiles[0].TiledOffset; + } + + var c = sourcePlan.Copies[sourceLayer]; + var d = targetPlan.Copies[targetLayer]; + return c.BufferRowLength == d.BufferRowLength && c.BufferImageHeight == d.BufferImageHeight && + c.OriginZ == d.OriginZ && c.OriginY == d.OriginY && c.Width == d.Width && c.Height == d.Height && + c.Depth == d.Depth && sourcePlan.Copies[0].BufferOffset == targetPlan.Copies[0].BufferOffset; + } + + /// + /// Copies source slices [, + ) into target slices + /// from , level 0, whole slices, in one blit pass. False, with nothing + /// encoded, when the textures cannot be blitted between (different formats, extents or sample counts). + /// + public bool TryEncodeLayerSubsetCopy( + IMetalSubmissionContext context, nint sourceTexture, uint sourceFirstLayer, + nint targetTexture, uint targetFirstLayer, uint layers, uint width, uint height) + { + if (_disposed || context.CommandBuffer == 0 || sourceTexture == 0 || targetTexture == 0 || + sourceTexture == targetTexture || layers == 0 || width == 0 || height == 0) + { + return false; + } + + var blit = _tiler.BeginBlit(context); + var size = new MtlSize { Width = width, Height = height, Depth = 1 }; + for (var layer = 0u; layer < layers; layer++) + { + MetalNative.SendCopyTextureSlice( + blit, SelCopyTextureSlice, sourceTexture, sourceFirstLayer + layer, 0, default, size, + targetTexture, targetFirstLayer + layer, 0, default); + } + + MetalTiler.EndEncoding(context, blit); + return true; + } +} diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalV2Contracts.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalV2Contracts.cs index 37aee9fb0..4ad69493a 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalV2Contracts.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalV2Contracts.cs @@ -155,6 +155,19 @@ bool TryEncodeTextureToTexture(IMetalSubmissionContext context, in ImageDescription sourceDescription, nint sourceTexture, in ImageDescription targetDescription, nint targetTexture); + // Whether target layers [targetFirstLayer, + layers) lie on exactly the guest bytes, and texels, of source layers + // [sourceFirstLayer, + layers) (MetalImageTransfer.LayerSubset). False keeps the round trip through guest memory. + bool TryMatchLayerSubset(in ImageDescription source, in ImageDescription target, + out uint sourceFirstLayer, out uint targetFirstLayer, out uint layers) + { + sourceFirstLayer = targetFirstLayer = layers = 0; + return false; + } + + // Copies whole level-0 slices between two textures of one format and extent; false with nothing encoded otherwise. + bool TryEncodeLayerSubsetCopy(IMetalSubmissionContext context, nint sourceTexture, uint sourceFirstLayer, + nint targetTexture, uint targetFirstLayer, uint layers, uint width, uint height) => false; + bool HasDenseAliasCoverage(in ImageDescription description) => false; bool CanDiscardAliasForOverwrite(in ImageDescription target, in ImageDescription source) => false; diff --git a/tests/SharpEmu.Gpu.Metal.Tests/MetalImageAliasTests.Subset.cs b/tests/SharpEmu.Gpu.Metal.Tests/MetalImageAliasTests.Subset.cs new file mode 100644 index 000000000..bf7e09361 --- /dev/null +++ b/tests/SharpEmu.Gpu.Metal.Tests/MetalImageAliasTests.Subset.cs @@ -0,0 +1,262 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using SharpEmu.Gpu.Metal.V2; +using SharpEmu.HLE.GpuMemory; +using SharpEmu.Libs.Gpu.Buffers; +using SharpEmu.Libs.Gpu.Abstractions; +using SharpEmu.Libs.Gpu.Images; +using Xunit; + +namespace SharpEmu.Gpu.Metal.Tests; + +// Two arrays over the same guest bytes that lay their layers out the same way (Demon's Souls' 64- and 72-layer +// 160x90 arrays on one base) hand the layers they share over by a slice copy between their textures +// (SHARPEMU_METAL_V2_ALIAS_SUBSET_DEVICE). Every case runs with the copy on and off and must end bit-identical: +// both textures read back, and guest memory after every GPU write is flushed. +public sealed unsafe partial class MetalImageAliasTests +{ + private const uint SubsetSide = 128; + + // A 128x128 RGBA8 array of the given tile mode: one 64 KiB block (or 64 KiB of linear rows) per layer. + // A width under 128 leaves pitch padding in every row, as Demon's Souls' 160-wide arrays have (pitch 256). + private static ImageRequest SubsetArray( + ulong address, uint layers, GuestTileMode tile, ImageRole role, uint levels = 1, uint width = SubsetSide) + { + var request = Rig.ArrayRequest(address, SubsetSide, layers, role); + var description = request.Description; + var size = TileGeometry.TextureTotalSize( + GuestPixelFormat.Bits8_8_8_8UNorm, width, SubsetSide, layers, levels, tile, volume: false).Size; + description.Data = new GuestSpan(address, size); + description.Extent = new GpuExtent3D(width, SubsetSide, 1); + description.Pitch = TileGeometry.TexturePitch(GuestPixelFormat.Bits8_8_8_8UNorm, width, tile); + description.TileMode = tile; + description.Resources = new SubresourceCount(levels, layers); + // One layer's bytes, as a colour target's description carries them: the cache then keeps two such arrays + // over one base as two images (FindMatchingArraySlice does not match them), as it does Demon's Souls'. + description.MipLayout[0] = new MipLevelLayout + { + Offset = 0, Size = size / layers, Pitch = description.Pitch, Height = SubsetSide, + }; + return new ImageRequest(description, request.View with { LevelCount = levels }, role); + } + + private static ulong LayerBytes(GuestTileMode tile) => + TileGeometry.TextureTotalSize(GuestPixelFormat.Bits8_8_8_8UNorm, SubsetSide, SubsetSide, 1, 1, tile, volume: false).Size; + + // Every layer of the image's texture, retiled to its guest layout. + private static byte[] ReadLayers(Rig rig, MetalCachedImage image) + { + var description = image.Description; + var size = description.Data.Size; + var buffer = rig.Harness.Buffer(size); + Assert.True(rig.Harness.Transfer.EncodeTextureToGuest( + rig.Harness, in description, new SubresourceRange(0, description.Resources.Levels, 0, description.TransferLayers), + image.Texture, new MetalGuestRange(buffer, 0, size, 0), default, 0, size, 0)); + rig.Harness.Submit(); + rig.Harness.Begin(); + return rig.Harness.Read(buffer, 0, size); + } + + private sealed record SubsetOutcome(byte[] First, byte[] Second, byte[] Guest, long Copies, long Writebacks, string Text); + + // The first array is written by the GPU (its texture holds `written`, guest memory something else), then the + // second is acquired with the given role. Then both are read back and every GPU write is flushed. + private static SubsetOutcome RunSubset( + bool subset, ImageRequest first, ImageRequest second, ImageRole secondRole, bool verify = false) + { + using var rig = new Rig(Device.Value); + rig.Cache.AliasSubsetDeviceEnabled = subset; + rig.Cache.AliasSubsetVerify = verify; + var start = Math.Min(first.Description.Data.Address, second.Description.Data.Address); + var end = Math.Max(first.Description.Data.End, second.Description.Data.End); + var span = end - start; + rig.WriteGuest(start, MetalTileOracle.Pattern((int)span, 0x5A)); + var firstImage = rig.Cache.GetImage(rig.Acquire(first with { Role = ImageRole.StorageImage })); + Assert.True(firstImage.IsGpuModified); + rig.Harness.Submit(); + rig.Harness.Begin(); + rig.WriteGuest(start, MetalTileOracle.Pattern((int)span, 0xC3)); + _ = rig.Cache.TakeAliasTransitionText(); + var writebacks = rig.Cache.Counters.Writebacks; + var secondImage = rig.Cache.GetImage(rig.Acquire(second with { Role = secondRole })); + rig.Harness.Submit(); + rig.Harness.Begin(); + var copies = rig.Cache.AliasSubsetCounters.Copies; + writebacks = rig.Cache.Counters.Writebacks - writebacks; + if (verify) + { + rig.Cache.DrainAliasSubsetChecks(); + var counters = rig.Cache.AliasSubsetCounters; + Assert.Equal((copies, 0L), (counters.Verified, counters.Unverified)); + Assert.Equal(0, counters.Mismatches); + } + + Assert.NotSame(firstImage, secondImage); + var text = $"first_dirty={firstImage.IsCpuDirty}:0x{firstImage.DirtyStart:X}-0x{firstImage.DirtyEnd:X} " + + $"first_gpu={firstImage.IsGpuModified} " + rig.Cache.TakeAliasTransitionText(); + + // The first image read again: a write through the second left it stale over the shared layers. + rig.Acquire(first with { Role = ImageRole.Texture }); + rig.Harness.Submit(); + rig.Harness.Begin(); + var firstBytes = ReadLayers(rig, firstImage); + var secondBytes = ReadLayers(rig, secondImage); + rig.Cache.FlushGpuWrites(start, span, MetalWritebackCause.HostRead); + rig.Harness.Submit(); + rig.Harness.Begin(); + return new SubsetOutcome(firstBytes, secondBytes, rig.ReadGuest(start, span), copies, writebacks, text); + } + + private static void AssertSameOutcome(SubsetOutcome on, SubsetOutcome off) + { + Assert.Equal(off.First, on.First); + Assert.Equal(off.Second, on.Second); + Assert.Equal(off.Guest, on.Guest); + } + + // 8 layers written, then 9 sampled from the same base, and the reverse; in the slice-swizzled RenderTarget mode + // (Demon's Souls' arrays), the 64 KiB standard mode and linear rows. + [Theory] + [InlineData(GuestTileMode.RenderTarget, 8u, 9u, ImageRole.Texture, 128u)] + [InlineData(GuestTileMode.RenderTarget, 9u, 8u, ImageRole.StorageImage, 128u)] + [InlineData(GuestTileMode.RenderTarget, 9u, 8u, ImageRole.Texture, 128u)] + [InlineData(GuestTileMode.RenderTarget, 8u, 9u, ImageRole.StorageImage, 128u)] + [InlineData(GuestTileMode.RenderTarget, 8u, 9u, ImageRole.Texture, 120u)] + [InlineData(GuestTileMode.RenderTarget, 9u, 8u, ImageRole.StorageImage, 120u)] + [InlineData(GuestTileMode.Standard64KB, 8u, 9u, ImageRole.Texture, 128u)] + [InlineData(GuestTileMode.Standard64KB, 9u, 8u, ImageRole.StorageImage, 120u)] + [InlineData(GuestTileMode.Linear, 8u, 9u, ImageRole.Texture, 128u)] + [InlineData(GuestTileMode.Linear, 9u, 8u, ImageRole.StorageImage, 128u)] + public void ALayerSubsetOnTheSameBaseIsCopiedOnTheDeviceAndMatchesTheRoundTrip( + GuestTileMode tile, uint firstLayers, uint secondLayers, ImageRole role, uint width) + { + if (!RequireDevice()) return; + var first = SubsetArray(ImageAddress, firstLayers, tile, ImageRole.StorageImage, width: width); + var second = SubsetArray(ImageAddress, secondLayers, tile, role, width: width); + var on = RunSubset(subset: true, first, second, role, verify: true); + var off = RunSubset(subset: false, first, second, role); + output.WriteLine($"{tile} {firstLayers}->{secondLayers} {role}: on copies={on.Copies} wb={on.Writebacks}, " + + $"off copies={off.Copies} wb={off.Writebacks}\n on: {on.Text}\n off: {off.Text}"); + Assert.Equal(1, on.Copies); + Assert.Equal(0, on.Writebacks); + Assert.Equal(0, off.Copies); + Assert.NotEqual(0, off.Writebacks); + AssertSameOutcome(on, off); + } + + // A two-layer image placed on layers 3 and 4 of a nine-layer array: a whole number of layers in, in a mode whose + // swizzle does not depend on the slice index. + [Theory] + [InlineData(GuestTileMode.Standard64KB, ImageRole.Texture)] + [InlineData(GuestTileMode.Standard64KB, ImageRole.StorageImage)] + [InlineData(GuestTileMode.Linear, ImageRole.Texture)] + [InlineData(GuestTileMode.Linear, ImageRole.StorageImage)] + public void ASubsetAtANonZeroBaseLayerIsCopiedOnTheDeviceAndMatchesTheRoundTrip(GuestTileMode tile, ImageRole role) + { + if (!RequireDevice()) return; + var first = SubsetArray(ImageAddress, 9, tile, ImageRole.StorageImage); + var second = SubsetArray(ImageAddress + 3 * LayerBytes(tile), 2, tile, role); + var on = RunSubset(subset: true, first, second, role, verify: true); + var off = RunSubset(subset: false, first, second, role); + output.WriteLine($"on: {on.Text}"); + output.WriteLine($"off: {off.Text}"); + Assert.Equal(1, on.Copies); + Assert.Equal(0, on.Writebacks); + Assert.Equal(0, off.Copies); + AssertSameOutcome(on, off); + } + + // Refused, and the round trip taken as before: a RenderTarget array a layer in (its swizzle takes the slice index, + // so the same bytes are different texels in each), a layer offset that is not whole, and a mip chain. + public static TheoryData SubsetRefusals => ["rt-shifted", "half-layer", "mips"]; + + [Theory] + [MemberData(nameof(SubsetRefusals))] + public void ALayerSubsetTheLayoutsDoNotShareIsRefused(string name) + { + if (!RequireDevice()) return; + var (first, second) = name switch + { + "rt-shifted" => (SubsetArray(ImageAddress, 9, GuestTileMode.RenderTarget, ImageRole.StorageImage), + SubsetArray(ImageAddress + LayerBytes(GuestTileMode.RenderTarget), 2, GuestTileMode.RenderTarget, ImageRole.Texture)), + "half-layer" => (SubsetArray(ImageAddress, 9, GuestTileMode.Linear, ImageRole.StorageImage), + SubsetArray(ImageAddress + LayerBytes(GuestTileMode.Linear) / 2, 2, GuestTileMode.Linear, ImageRole.Texture)), + _ => (SubsetArray(ImageAddress, 4, GuestTileMode.Standard64KB, ImageRole.StorageImage, levels: 2), + SubsetArray(ImageAddress, 2, GuestTileMode.Standard64KB, ImageRole.Texture)), + }; + var on = RunSubset(subset: true, first, second, ImageRole.Texture); + var off = RunSubset(subset: false, first, second, ImageRole.Texture); + Assert.Equal(0, on.Copies); + AssertSameOutcome(on, off); + } + + // The planning side of the refusals, without a cache: the slice-swizzled mode matches only at the same layer index. + [Fact] + public void TheLayerMatchFollowsTheSliceSwizzle() + { + if (!RequireDevice()) return; + using var transfer = new MetalImageTransfer(Device.Value); + foreach (var tile in new[] { GuestTileMode.RenderTarget, GuestTileMode.Standard64KB, GuestTileMode.Linear }) + { + var array = SubsetArray(ImageAddress, 9, tile, ImageRole.Texture).Description; + var same = SubsetArray(ImageAddress, 8, tile, ImageRole.Texture).Description; + var shifted = SubsetArray(ImageAddress + 3 * LayerBytes(tile), 2, tile, ImageRole.Texture).Description; + Assert.True(transfer.TryMatchLayerSubset(in array, in same, out var sourceFirst, out var targetFirst, out var layers)); + Assert.Equal((0u, 0u, 8u), (sourceFirst, targetFirst, layers)); + Assert.True(transfer.TryMatchLayerSubset(in same, in array, out sourceFirst, out targetFirst, out layers)); + Assert.Equal((0u, 0u, 8u), (sourceFirst, targetFirst, layers)); + var matched = transfer.TryMatchLayerSubset(in array, in shifted, out sourceFirst, out targetFirst, out layers); + Assert.Equal(tile != GuestTileMode.RenderTarget, matched); + if (matched) + { + Assert.Equal((3u, 0u, 2u), (sourceFirst, targetFirst, layers)); + } + } + } + + // The source already stale inside the run (a one-layer alias took its layer 2): copying it would carry its old + // bytes there, so the array is refused (the alias, a subset itself, may still be copied). Same bytes either way. + [Fact] + public void ASourceStaleInsideTheSubsetIsRefused() + { + if (!RequireDevice()) return; + var outcomes = new List<(byte[] Second, byte[] Guest, long Copies)>(); + foreach (var subset in new[] { true, false }) + { + using var rig = new Rig(Device.Value); + rig.Cache.AliasSubsetDeviceEnabled = subset; + var first = SubsetArray(ImageAddress, 9, GuestTileMode.Standard64KB, ImageRole.StorageImage); + var size = first.Description.Data.Size; + var layer = LayerBytes(GuestTileMode.Standard64KB); + rig.WriteGuest(ImageAddress, MetalTileOracle.Pattern((int)size, 0x5A)); + var firstImage = rig.Cache.GetImage(rig.Acquire(first)); + rig.Harness.Submit(); + rig.Harness.Begin(); + rig.WriteGuest(ImageAddress, MetalTileOracle.Pattern((int)size, 0xC3)); + rig.Acquire(SubsetArray(ImageAddress + 2 * layer, 1, GuestTileMode.Standard64KB, ImageRole.StorageImage)); + rig.Harness.Submit(); + rig.Harness.Begin(); + Assert.True(firstImage.IsGpuModified); + Assert.True(firstImage.IsCpuDirty); + Assert.Equal((2 * layer, 3 * layer), (firstImage.DirtyStart, firstImage.DirtyEnd)); + var copies = rig.Cache.AliasSubsetCounters.Copies; + var second = rig.Cache.GetImage(rig.Acquire( + SubsetArray(ImageAddress, 8, GuestTileMode.Standard64KB, ImageRole.Texture))); + rig.Harness.Submit(); + rig.Harness.Begin(); + copies = rig.Cache.AliasSubsetCounters.Copies - copies; + var secondBytes = ReadLayers(rig, second); + rig.Cache.FlushGpuWrites(ImageAddress, size, MetalWritebackCause.HostRead); + rig.Harness.Submit(); + rig.Harness.Begin(); + outcomes.Add((secondBytes, rig.ReadGuest(ImageAddress, size), copies)); + } + + // On: one copy at most, the alias's own layer; never the array. + Assert.True(outcomes[0].Copies <= 1); + Assert.Equal(0, outcomes[1].Copies); + Assert.Equal(outcomes[1].Second, outcomes[0].Second); + Assert.Equal(outcomes[1].Guest, outcomes[0].Guest); + } +} From 727d8cfcb202c34dad27449ae4729d274f393962 Mon Sep 17 00:00:00 2001 From: kuba Date: Sun, 15 Nov 2026 06:27:55 +0000 Subject: [PATCH 030/178] [Tests] Separator bench: an encoder split without the fence, tracked and untracked --- .../MetalEndOfPipeOrderTests.NonDrawBench.cs | 20 +++++++++++++------ 1 file changed, 14 insertions(+), 6 deletions(-) diff --git a/tests/SharpEmu.Gpu.Metal.Tests/MetalEndOfPipeOrderTests.NonDrawBench.cs b/tests/SharpEmu.Gpu.Metal.Tests/MetalEndOfPipeOrderTests.NonDrawBench.cs index a524121d6..65a27942f 100644 --- a/tests/SharpEmu.Gpu.Metal.Tests/MetalEndOfPipeOrderTests.NonDrawBench.cs +++ b/tests/SharpEmu.Gpu.Metal.Tests/MetalEndOfPipeOrderTests.NonDrawBench.cs @@ -162,21 +162,27 @@ public void MeasureLabelSeparatorsWhenRequested() var selRelease = MetalNative.Selector("release"); var group = new MtlSize { Width = 1, Height = 1, Depth = 1 }; var threads = new MtlSize { Width = 64, Height = 1, Depth = 1 }; - string[] cases = ["none", "split", "split_blit", "device_event", "shared_event", "in_encoder"]; + // split_nofence leaves the fence out (Metal's own hazard tracking still orders the two encoders over the + // tracked buffer); split_untracked also takes an untracked buffer, so nothing orders them: what a split + // costs once the fence chain is taken away. + var untracked = MetalNative.SendNewBuffer(device, selNewBuffer, 4096, 1 << 8); + string[] cases = ["none", "split", "split_nofence", "split_untracked", "split_blit", "device_event", "shared_event", "in_encoder"]; + var fenced = true; + var target = words; var samples = cases.ToDictionary(name => name, _ => new List()); nint OpenCompute(nint commandBuffer) { var encoder = MetalNative.Send(commandBuffer, selCompute); - MetalNative.SendVoid(encoder, selWaitFence, fence); + if (fenced) MetalNative.SendVoid(encoder, selWaitFence, fence); MetalNative.SendVoid(encoder, selPipeline, tick); - MetalNative.SendSetBuffer(encoder, selSetBuffer, words, 0, 0); + MetalNative.SendSetBuffer(encoder, selSetBuffer, target, 0, 0); return encoder; } void EndCompute(nint encoder) { - MetalNative.SendVoid(encoder, selUpdateFence, fence); + if (fenced) MetalNative.SendVoid(encoder, selUpdateFence, fence); MetalNative.SendVoid(encoder, selEnd); } @@ -202,6 +208,8 @@ void Blit(nint commandBuffer) _ => 0, }; var value = 0UL; + fenced = name is not ("split_nofence" or "split_untracked"); + target = name == "split_untracked" ? untracked : words; var encoder = OpenCompute(commandBuffer); for (var pair = 0; pair < pairs; pair++) { @@ -229,7 +237,7 @@ void Blit(nint commandBuffer) SharpEmu.Gpu.Metal.V2.MetalV2Native.SendEventValue(commandBuffer, selWait, @event, value); } - if (name != "split") + if (name is not ("split" or "split_nofence" or "split_untracked")) { Blit(commandBuffer); } @@ -269,7 +277,7 @@ void Blit(nint commandBuffer) File.WriteAllText(path, JsonSerializer.Serialize(new { architecture = System.Runtime.InteropServices.RuntimeInformation.ProcessArchitecture.ToString(), pairs, rounds = rounds - warmup, results }, new JsonSerializerOptions { WriteIndented = true })); - foreach (var handle in new[] { words, staging, labels, fence, tick, copy, queue }) MetalNative.SendVoid(handle, selRelease); + foreach (var handle in new[] { words, untracked, staging, labels, fence, tick, copy, queue }) MetalNative.SendVoid(handle, selRelease); } finally { From 12af424f8e57e614c1483f7b7beb3b9efd0ed122 Mon Sep 17 00:00:00 2001 From: kuba Date: Sun, 15 Nov 2026 06:36:06 +0000 Subject: [PATCH 031/178] [Metal] Defer array target uploads to their pass, drop the layers a pass clears An array target stale over some of its layers - a new one, or a GPU-written one the guest rewrote - now leaves its upload to the pass as a single-layer target does. A pass proven to overwrite the one layer its view names (a clear, an elided load) drops that layer's stale bytes; the layers it does not touch stay stale and are refreshed as a run on their next use. A cut that would split the stale interval, a pass that loads a stale layer, a stencil plane, or a remainder that is not an exact run readable in place uploads as before. Demon's Souls clears each of its four 1024x1024 shadow cascades in its own pass and uploaded the 16 MiB array before the first, every frame. Depth runs may begin at a layer past the first: the depth kernels move a layer at a time, and the new device tests move runs from layers 1-3 of D32 and D32S8 bit for bit. The run refresh no longer applies its past-half rule to a GPU-written array (the whole refresh is no option there). SHARPEMU_METAL_V2_LAYER_DEFER=0 and SHARPEMU_METAL_V2_DEPTH_LAYER_RUNS=0 turn each off; layer_refresh_skipped=[layers,mib] counts the dropped layers. --- .../V2/MetalImageCache.AliasTransitions.cs | 2 + .../V2/MetalImageCache.DeferredRefresh.cs | 149 ++++++++++- .../SharpEmu.Gpu.Metal/V2/MetalImageCache.cs | 37 ++- .../V2/MetalImageTransfer.LayerSubset.cs | 41 +++ .../SharpEmu.Gpu.Metal/V2/MetalV2Contracts.cs | 8 + .../MetalDeferredRefreshTests.cs | 235 +++++++++++++++++- .../MetalImageTransferTests.CoveringRuns.cs | 158 ++++++++++++ 7 files changed, 605 insertions(+), 25 deletions(-) diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.AliasTransitions.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.AliasTransitions.cs index 00e70a5a4..e0bd50077 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.AliasTransitions.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.AliasTransitions.cs @@ -62,6 +62,7 @@ internal string TakeAliasTransitionText() DrainAliasSubsetChecksLocked(); var subsetCopies = Interlocked.Exchange(ref _aliasSubsetCopies, 0); var subsetBytes = Interlocked.Exchange(ref _aliasSubsetBytes, 0); + var layerSkips = TakeLayerRefreshSkipped(); return $"alias_transitions=[fused:{counts.Fused},discarded:{counts.Discarded},device-subset:{subsetCopies}," + $"round-trip:{counts.RoundTrip},published-run:{Interlocked.Exchange(ref _aliasPublishedRuns, 0)}," + $"published-whole:{Interlocked.Exchange(ref _aliasPublishedWholes, 0)}," + @@ -71,6 +72,7 @@ internal string TakeAliasTransitionText() $"alias_moved_mib=[wb:{Mb(Interlocked.Exchange(ref _aliasMovedWritebackBytes, 0))}," + $"blit:{Mb(Interlocked.Exchange(ref _aliasMovedBlitBytes, 0))}] " + $"alias_run_refresh_refused={Interlocked.Exchange(ref _aliasRunRefreshRefused, 0)} " + + $"layer_refresh_skipped=[{layerSkips.Layers},{Mb(layerSkips.Bytes)}] " + $"alias_subset_verify=[checked:{Interlocked.Exchange(ref _aliasSubsetVerified, 0)}," + $"mismatch:{Interlocked.Read(ref _aliasSubsetMismatches)},unverified:{Interlocked.Exchange(ref _aliasSubsetUnverified, 0)}] " + $"alias_transition_refused=[{refusals}] alias_cpu_read_runs={readRuns} " + diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.DeferredRefresh.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.DeferredRefresh.cs index 7c91b2dcc..2296fa4d7 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.DeferredRefresh.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.DeferredRefresh.cs @@ -29,8 +29,9 @@ internal sealed partial class MetalImageCache // The view a pass will name the attachment by, the image, and the GPU-write marking // the acquire left for later: a colour target, or a depth target and whether it // writes only the stencil plane. + // BaseLayer and LayerCount are the layers the view names, for layered deferral. private readonly record struct DeferredRefresh(nint View, ResourceSlotIdentifier Identifier, - MetalCachedImage Image, bool Depth, bool StencilOnly, bool AliasesPending); + MetalCachedImage Image, bool Depth, bool StencilOnly, bool AliasesPending, uint BaseLayer, uint LayerCount); private readonly List _deferredRefreshes = []; @@ -59,9 +60,10 @@ private static bool CanDeferRefresh(MetalCachedImage image) => // Caller holds the lock. private void DeferRefreshLocked(nint view, ResourceSlotIdentifier identifier, MetalCachedImage image, - bool depth, bool stencilOnly, bool aliasesPending) + bool depth, bool stencilOnly, bool aliasesPending, uint baseLayer, uint layerCount) { - _deferredRefreshes.Add(new DeferredRefresh(view, identifier, image, depth, stencilOnly, aliasesPending)); + _deferredRefreshes.Add(new DeferredRefresh( + view, identifier, image, depth, stencilOnly, aliasesPending, baseLayer, layerCount)); Volatile.Write(ref _deferredRefreshCount, _deferredRefreshes.Count); } @@ -206,8 +208,9 @@ private void ResolveDeferredRefreshLocked(nint view, bool overwritten, bool sten } var entry = TakeDeferredLocked(index); + var whole = overwritten && CoversWholeImage(entry, stencilOverwritten); CompleteDeferredLocked( - entry, overwritten && CoversWholeImage(entry, stencilOverwritten)); + entry, whole, layerOverwritten: overwritten && !whole && LayerDeferEnabled && CoversViewLayer(entry)); return; } } @@ -243,9 +246,10 @@ private static bool CoversWholeImage(in DeferredRefresh entry, bool stencilOverw // Makes or drops the upload, then marks the image written by the pass exactly as the // acquire used to right after its refresh. Caller holds the lock. - private void CompleteDeferredLocked(in DeferredRefresh entry, bool overwritten) + private void CompleteDeferredLocked(in DeferredRefresh entry, bool overwritten, bool layerOverwritten = false) { var image = entry.Image; + (MetalImageDirtyCause Cause, ulong Start, ulong End)? stale = null; if (entry.AliasesPending && (!overwritten || !TryDiscardOverwrittenAliases(entry.Identifier))) { SynchronizeAliases(entry.Identifier, takesGpuOwnership: true, role: overwritten ? "rt-overwrite" : "rt-load"); @@ -258,7 +262,7 @@ private void CompleteDeferredLocked(in DeferredRefresh entry, bool overwritten) (long)(image.Description.Data.Size + (image.Description.HasStencil ? image.Description.Stencil.Size : 0))); image.RefreshComplete(); } - else + else if (!TryLeaveOtherLayersStale(in entry, layerOverwritten, out stale)) { RefreshFromGuest(image); } @@ -266,16 +270,139 @@ private void CompleteDeferredLocked(in DeferredRefresh entry, bool overwritten) if (entry.Depth) { image.MarkGpuModified(depthPlaneChanged: !entry.StencilOnly); - NoteLinearGpuWrite(image); - image.GpuWriteSerial = _owner.CurrentSerial; - image.NoteUse(image.GpuWriteSerial); - return; + } + else + { + image.MarkGpuModified(); } - image.MarkGpuModified(); NoteLinearGpuWrite(image); image.GpuWriteSerial = _owner.CurrentSerial; image.NoteUse(image.GpuWriteSerial); + if (stale is { } run) + { + // The layers this pass neither wrote nor read stay stale under the GPU write; their next use refreshes + // just them (TryRefreshDirtyRun), or a later pass that overwrites them drops them as this one did. + image.MarkCpuDirty(run.Cause, run.Start, run.End); + } + } + + // SHARPEMU_METAL_V2_LAYER_DEFER (on; =0 off): an array target's upload waits for its pass as a single-layer + // target's does, a GPU-written one's too, and a pass proven to overwrite the one layer its view names drops that + // layer's stale bytes. Demon's Souls clears each of its four 1024x1024 shadow cascades in its own pass, and the + // array was uploaded whole, 16 MiB, before the first of them every frame. + internal bool LayerDeferEnabled { get; set; } = + Environment.GetEnvironmentVariable("SHARPEMU_METAL_V2_LAYER_DEFER") != "0"; + + private long _layerRefreshSkippedLayers, _layerRefreshSkippedBytes; + + /// Layers whose upload a proven overwrite dropped, and their stale guest bytes. + internal (long Layers, long Bytes) TakeLayerRefreshSkipped() => + (Interlocked.Exchange(ref _layerRefreshSkippedLayers, 0), Interlocked.Exchange(ref _layerRefreshSkippedBytes, 0)); + + // An array whose stale layers may wait under a pass on some of its layers: one level, not a volume, no stencil + // plane (a run never carries one) and no sparse residency. Its layers must tile its bytes (TryLayerBytes). + private static bool LayeredDeferralShape(MetalCachedImage image) => + image.Description.IsLayered && image.Description.Resources.Levels == 1 && image.Shape.MipLevels == 1 && + image.Description.Samples <= 1 && !image.Description.HasStencil && !image.Description.IsVolume && image.Shape.TextureType != Mtl.TextureType3D && + SparseOf(image) is null && image.Texture != 0 && !ImageDescription.IsEmptyRange(image.Description.Data); + + // A GPU-written array stale over some layers may leave the upload to its pass too: the pass may overwrite them, + // or not touch them at all. + private bool CanDeferLayerRefresh(MetalCachedImage image) => + LayerDeferEnabled && MetalV2Diagnostics.SkipOverwrittenRefresh && image.IsCpuDirty && image.IsGpuModified && + LayeredDeferralShape(image); + + // Whether a pass that overwrites the attachment overwrites every byte of the one layer its view names: a + // single-layer view of a one-level array, a depth target's depth plane with no stencil. + private static bool CoversViewLayer(in DeferredRefresh entry) + { + if (entry.LayerCount != 1 || !LayeredDeferralShape(entry.Image)) + { + return false; + } + + if (!entry.Depth) + { + return true; + } + + var aspects = ViewFormatRules.DepthAspects(entry.Image.Description.PixelFormat); + return (aspects & GpuImageAspect.DepthBit) != 0 && (aspects & GpuImageAspect.StencilBit) == 0; + } + + // Instead of the upload: drops the stale bytes of the view's layers when the pass is proven to overwrite them, + // and leaves the stale layers it does not touch stale. True with the interval still stale afterwards (or none); + // false - and the caller uploads as before - when the pass reads a stale layer, the cut would split the stale + // interval, or what is left is not a run a later refresh makes exactly. + private bool TryLeaveOtherLayersStale( + in DeferredRefresh entry, bool layerOverwritten, out (MetalImageDirtyCause Cause, ulong Start, ulong End)? stale) + { + stale = null; + var image = entry.Image; + if (!LayerDeferEnabled || !image.IsCpuDirty || !LayeredDeferralShape(image) || + !_transfer.TryLayerBytes(in image.Description, entry.BaseLayer, entry.LayerCount, out var viewStart, out var viewEnd)) + { + return false; + } + + // An empty interval on a dirty image is a new one, stale over all of it. + var (dirtyStart, dirtyEnd) = image.DirtyEnd > image.DirtyStart + ? (image.DirtyStart, image.DirtyEnd) + : (0UL, image.Description.Data.Size); + var (start, end) = (dirtyStart, dirtyEnd); + var overlaps = viewStart < dirtyEnd && viewEnd > dirtyStart; + if (overlaps) + { + if (!layerOverwritten) + { + return false; + } + + if (viewStart <= dirtyStart && viewEnd >= dirtyEnd) + { + (start, end) = (0, 0); + } + else if (viewStart <= dirtyStart) + { + start = viewEnd; + } + else if (viewEnd >= dirtyEnd) + { + end = viewStart; + } + else + { + return false; + } + } + + // What stays stale is refreshed later by TryRefreshDirtyRun alone (a GPU-written image is never uploaded + // whole): it must be a run that refresh makes exactly, and one it can read in place. Anything else uploads + // now, as before, rather than leave the stale keep in RefreshFromGuestCore an interval it did not have. + if (end > start && + (!SubRangeTransfersEnabled || + !TryCoveringRun(in image.Description, start, end, out var runStart, out var runEnd) || + runStart != start || runEnd != end || + !_guestMemory.TryResolveInPlace(image.Description.Data.Address + start, end - start, out _))) + { + return false; + } + + if (overlaps) + { + Interlocked.Increment(ref _layerRefreshSkippedLayers); + Interlocked.Add(ref _layerRefreshSkippedBytes, + (long)(Math.Min(viewEnd, dirtyEnd) - Math.Max(viewStart, dirtyStart))); + } + + // The GPU write that follows clears the stale interval; the caller marks what is left again after it. + if (end > start) + { + stale = (image.DirtyCause, start, end); + } + + return true; } // A released image's upload no longer has a texture to land in. Caller holds the lock. diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.cs index 2eac63103..3e7454054 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.cs @@ -1694,10 +1694,10 @@ public nint AcquireColorTargetView( var deferAliases = deferRefresh && AliasTransitionsEnabled && CanDeferRefresh(image) && !image.Description.HasStencil && !image.Description.IsBlock && !image.Description.IsVolume && image.Description.Resources.Levels == 1 && image.Description.TransferLayers == 1; - if (!deferAliases) SynchronizeAliases(imageIdentifier, takesGpuOwnership: true); + if (!deferAliases) SynchronizeAliases(imageIdentifier, takesGpuOwnership: true, role: "rt"); // The pass about to begin may clear or overwrite all of it; BeginRendering decides // whether the upload is worth making (MetalImageCache.DeferredRefresh). - var defer = deferRefresh && CanDeferRefresh(image); + var defer = deferRefresh && (CanDeferRefresh(image) || CanDeferLayerRefresh(image)); if (!defer) { RefreshFromGuest(image); @@ -1723,7 +1723,8 @@ public nint AcquireColorTargetView( { image.NoteUse(_owner.CurrentSerial); var deferredView = image.GetOrCreateView(request.View); - DeferRefreshLocked(deferredView, imageIdentifier, image, depth: false, stencilOnly: false, deferAliases); + DeferRefreshLocked(deferredView, imageIdentifier, image, depth: false, stencilOnly: false, deferAliases, + request.View.BaseLayer, request.View.LayerCount); return deferredView; } @@ -1775,7 +1776,7 @@ public nint AcquireDepthTargetView( // Only a target the pass writes can be one it clears. The refresh reads the // stencil plane from where the image has it, so a request that moves the plane // refreshes now, before the description changes. - var defer = deferRefresh && writes && CanDeferRefresh(image) && + var defer = deferRefresh && writes && (CanDeferRefresh(image) || CanDeferLayerRefresh(image)) && (!request.Description.HasStencil || stencil == image.Description.Stencil); if (!defer) { @@ -1811,7 +1812,8 @@ public nint AcquireDepthTargetView( { image.NoteUse(_owner.CurrentSerial); var deferredView = image.GetOrCreateView(request.View); - DeferRefreshLocked(deferredView, imageIdentifier, image, depth: true, stencilOnly, aliasesPending: false); + DeferRefreshLocked(deferredView, imageIdentifier, image, depth: true, stencilOnly, aliasesPending: false, + request.View.BaseLayer, request.View.LayerCount); return deferredView; } @@ -2864,9 +2866,13 @@ private bool TryRefreshDirtyRun(MetalCachedImage image) var residentEnd = image.ResidentEnd; var dirtyStart = Math.Max(image.DirtyStart, residentStart); var dirtyEnd = Math.Min(image.DirtyEnd, residentEnd); + // Past half the run still goes alone for a GPU-written array (layered deferral leaves one stale over the + // layers its passes have not overwritten yet): the whole refresh is no option there - it would replace the + // layers only the texture holds - so the half rule, a cost rule, would only keep the stale layers. + var pastHalfAllowed = LayerDeferEnabled && image.IsGpuModified && description.IsLayered; if (!SubRangeTransfersEnabled || description.HasStencil || dirtyEnd <= dirtyStart || - dirtyEnd - dirtyStart > (residentEnd - residentStart) / 2) + (dirtyEnd - dirtyStart > (residentEnd - residentStart) / 2 && !pastHalfAllowed)) { return false; } @@ -2930,19 +2936,30 @@ private bool TryRefreshDirtyRun(MetalCachedImage image) // or its first byte instead. A run that widens to the whole image is refused, and // the caller transfers the whole image as before: bytes a run dropped would stay // stale, and a texture that disagrees with guest memory never catches up. + // SHARPEMU_METAL_V2_DEPTH_LAYER_RUNS (on; =0 off): a depth run may begin at a layer boundary past the first. + private static readonly bool DepthLayerRuns = + Environment.GetEnvironmentVariable("SHARPEMU_METAL_V2_DEPTH_LAYER_RUNS") != "0"; + private bool TryCoveringRun( in ImageDescription description, ulong dirtyStart, ulong dirtyEnd, out ulong start, out ulong end) => TryCoveringRun(_transfer, in description, dirtyStart, dirtyEnd, out start, out end); internal static bool TryCoveringRun( IMetalImageTransfer transfer, in ImageDescription description, - ulong dirtyStart, ulong dirtyEnd, out ulong start, out ulong end) + ulong dirtyStart, ulong dirtyEnd, out ulong start, out ulong end) => + TryCoveringRun(transfer, in description, dirtyStart, dirtyEnd, DepthLayerRuns, out start, out end); + + internal static bool TryCoveringRun( + IMetalImageTransfer transfer, in ImageDescription description, + ulong dirtyStart, ulong dirtyEnd, bool depthLayerRuns, out ulong start, out ulong end) { // A colour surface begins a run at the cut it is dirty from: the texel row of a // linear one, the block row of a tiled one - a tile row of a 4 KiB mode, a macro - // tile row of a 64 KiB one. The depth kernels have no device test for a run past - // the first byte, so a depth run still starts at the image's first byte. - start = description.IsDepth + // tile row of a 64 KiB one. A depth run begins at the layer it is dirty from: the + // depth kernels walk a layer at a time, and MetalImageTransferTests.CoveringRuns + // moves runs from layers 1-3 of D32 and D32S8 bit for bit. + // SHARPEMU_METAL_V2_DEPTH_LAYER_RUNS=0 starts a depth run at the first byte again. + start = description.IsDepth && !depthLayerRuns ? 0 : transfer.AlignRunEnd(in description, 0, Math.Min(dirtyStart, dirtyEnd)); if (transfer.AlignRunStart(in description, start) != start) diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageTransfer.LayerSubset.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageTransfer.LayerSubset.cs index 67ee5c7f2..eaba2abc4 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageTransfer.LayerSubset.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageTransfer.LayerSubset.cs @@ -92,6 +92,47 @@ public bool TryMatchLayerSubset( return true; } + /// + /// The guest bytes, as offsets into the image, of layers [, + ) + /// of a one-level, non-volume image whose guest size is a whole number of equal layers: every byte of those layers + /// and no byte of any other. False for anything else. + /// + public bool TryLayerBytes(in ImageDescription description, uint baseLayer, uint count, out ulong start, out ulong end) + { + start = 0; + end = 0; + var layers = description.Resources.Layers; + if (_disposed || count == 0 || layers == 0 || baseLayer >= layers || count > layers - baseLayer || + description.IsVolume || description.Resources.Levels != 1 || ImageDescription.IsEmptyRange(description.Data)) + { + return false; + } + + var plan = PlanFor(description); + ulong stride; + if (plan.DepthStencil) + { + stride = plan.SliceSize; + if (plan.Layers != layers) + { + return false; + } + } + else if (plan.Volume || !TryLayerStride(plan, layers, out stride)) + { + return false; + } + + if (stride == 0 || stride * layers != description.Data.Size) + { + return false; + } + + start = baseLayer * stride; + end = start + count * stride; + return true; + } + private static bool SameLayerShape(in ImageDescription source, in ImageDescription target) => source.Type is GuestImageType.Color2D or GuestImageType.Color2DArray && target.Type is GuestImageType.Color2D or GuestImageType.Color2DArray && diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalV2Contracts.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalV2Contracts.cs index 4ad69493a..25cf69ae1 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalV2Contracts.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalV2Contracts.cs @@ -164,6 +164,14 @@ bool TryMatchLayerSubset(in ImageDescription source, in ImageDescription target, return false; } + // The guest bytes of whole layers of a one-level layered image (MetalImageTransfer.LayerSubset); false when its + // layers are not equal runs that tile its bytes. + bool TryLayerBytes(in ImageDescription description, uint baseLayer, uint count, out ulong start, out ulong end) + { + start = end = 0; + return false; + } + // Copies whole level-0 slices between two textures of one format and extent; false with nothing encoded otherwise. bool TryEncodeLayerSubsetCopy(IMetalSubmissionContext context, nint sourceTexture, uint sourceFirstLayer, nint targetTexture, uint targetFirstLayer, uint layers, uint width, uint height) => false; diff --git a/tests/SharpEmu.Gpu.Metal.Tests/MetalDeferredRefreshTests.cs b/tests/SharpEmu.Gpu.Metal.Tests/MetalDeferredRefreshTests.cs index 014b3fefb..54b9db1cc 100644 --- a/tests/SharpEmu.Gpu.Metal.Tests/MetalDeferredRefreshTests.cs +++ b/tests/SharpEmu.Gpu.Metal.Tests/MetalDeferredRefreshTests.cs @@ -116,6 +116,229 @@ public void ATextureBindingBeforeThePassSeesTheGuestBytes() AssertPixels(rig.Read(TargetAddress), [GuestPattern, GuestPattern, GuestPattern, GuestPattern]); } + // ---- Layered deferral (SHARPEMU_METAL_V2_LAYER_DEFER) -------------------------------------------------------- + // A four-layer D32 array whose layers are each cleared by a pass of their own, the way Demon's Souls clears its + // shadow cascades. Round one starts from a new image; round two from the GPU-written array after the guest + // rewrote all of it (LaterPattern). A front or back cut leaves the rest stale and uploads nothing; a cut from the + // middle uploads, never skips; a layer sampled before its clear is uploaded first. Every order leaves guest memory + // byte for byte as the switch off leaves it. + + private const ulong ArrayAddress = GuestBase + 0x10000; + private const uint ArrayWidth = 128; + private const uint ArrayHeight = 64; + private const uint ArrayLayers = 4; + private const float FirstClear = 0.25f; + private const float SecondClear = 0.75f; + + public static TheoryData LayerOrders => new() + { + // order, uploads on (round one + round two), layers dropped on + { new uint[] { 0, 1, 2, 3 }, 0, 8 }, + { new uint[] { 3, 2, 1, 0 }, 0, 8 }, + // The first clear cuts the middle: the whole array is uploaded, the rest are not stale any more. + { new uint[] { 2, 0, 3, 1 }, 2, 0 }, + { new uint[] { 1, 2, 3, 0 }, 2, 0 }, + // Layers 2 and 3 are never cleared: they are uploaded when the array is read, and only then. + { new uint[] { 0, 1 }, 2, 4 }, + }; + + [Theory] + [MemberData(nameof(LayerOrders))] + public void LayerClearsOfADepthArrayDropOnlyTheUploadsTheyOverwrite(uint[] order, int uploadsOn, int layersDropped) + { + if (!RequireDevice()) return; + if (!MetalV2Diagnostics.SkipOverwrittenRefresh) return; + var off = RunLayerClears(order, layerDefer: false, sampleBeforeClear: null); + var on = RunLayerClears(order, layerDefer: true, sampleBeforeClear: null); + output.WriteLine($"order={string.Join(",", order)} on: uploads={on.Uploads} dropped={on.Dropped} " + + $"off: uploads={off.Uploads} dropped={off.Dropped}"); + + Assert.Equal(off.Round1, on.Round1); + Assert.Equal(off.Round2, on.Round2); + Assert.Equal(uploadsOn, on.Uploads); + Assert.Equal(layersDropped, on.Dropped); + Assert.Equal(0, off.Dropped); + Assert.True(off.Uploads >= 2, "with the switch off each round uploads the array at its first clear"); + AssertLayers(on.Round2, order, SecondClear); + } + + // Layer 0 is cleared, leaving layers 1-3 stale; then layer 2 is sampled before its own clear. The sample uploads + // the stale layers first (one run upload): it sees the guest's bytes, not the texture's older ones. + [Fact] + public void ALayerSampledBeforeItsClearIsUploadedFirst() + { + if (!RequireDevice()) return; + if (!MetalV2Diagnostics.SkipOverwrittenRefresh) return; + uint[] order = [0, 2, 1, 3]; + var off = RunLayerClears(order, layerDefer: false, sampleBeforeClear: 2); + var on = RunLayerClears(order, layerDefer: true, sampleBeforeClear: 2); + output.WriteLine($"on: uploads={on.Uploads} dropped={on.Dropped} off: uploads={off.Uploads}"); + + Assert.Equal(off.Round1, on.Round1); + Assert.Equal(off.Round2, on.Round2); + Assert.Equal(off.Sampled, on.Sampled); + // Round one samples a new array's layer 2 the texture never held: the guest's GuestPattern; round two, after + // the guest rewrote it, LaterPattern. + Assert.Equal([GuestPattern, GuestPattern, GuestPattern, GuestPattern], on.Sampled[0]); + Assert.Equal([LaterPattern, LaterPattern, LaterPattern, LaterPattern], on.Sampled[1]); + // Each round: layer 0's clear drops its layer, the sample uploads layers 1-3 as one run. + Assert.Equal(2, on.Uploads); + Assert.Equal(2, on.Dropped); + } + + private sealed record LayerOutcome(byte[] Round1, byte[] Round2, long Uploads, long Dropped, List Sampled); + + private LayerOutcome RunLayerClears(uint[] order, bool layerDefer, uint? sampleBeforeClear) + { + using var rig = new Rig(Device.Value); + var host = rig.Host; + host.ImageCache.LayerDeferEnabled = layerDefer; + _ = host.ImageCache.TakeLayerRefreshSkipped(); + var size = ArrayLayerBytes() * ArrayLayers; + var uploads = host.ImageCache.Counters.Uploads; + var sampled = new List(); + var dropped = 0L; + ResourceSlotIdentifier image = default; + byte[] Round(float clear) + { + foreach (var layer in order) + { + if (layer == sampleBeforeClear) + { + using (host.BeginPreparation()) + { + var request = DepthArrayRequest(layer, ImageRole.Texture); + var found = host.ImageCache.FindImage(ref request); + Assert.Equal(image, found); + Assert.NotEqual(0, host.ImageCache.AcquireTextureView(found, in request)); + Assert.False(host.ImageCache.GetImage(found).IsCpuDirty); + } + + sampled.Add(LayerTexel(host, image, layer)); + } + + using (host.BeginPreparation()) + { + var acquisition = ((IRenderHost)host).AcquireDepthAttachment(DepthArrayTarget(image, layer, clear: true)); + host.BeginRendering(DepthPass(acquisition.View, clear)); + host.EndRendering(); + } + + dropped += host.ImageCache.TakeLayerRefreshSkipped().Layers; + } + + return rig.Read(ArrayAddress, size); + } + + using (host.BeginPreparation()) + { + var request = DepthArrayRequest(0, ImageRole.DepthTarget); + image = host.ImageCache.FindImage(ref request); + } + + var round1 = Round(FirstClear); + rig.FillBacking(ArrayAddress, size, LaterPattern); + host.ImageCache.InvalidateMemory(ArrayAddress, size); + var round2 = Round(SecondClear); + return new LayerOutcome(round1, round2, host.ImageCache.Counters.Uploads - uploads, dropped, sampled); + } + + // The first texel of a layer, read back from the texture: texel (0, 0) is the first element of the layer's tiles. + private static byte[] LayerTexel(MetalRenderHost host, ResourceSlotIdentifier image, uint layer) + { + host.FlushAndWaitForGpu(); + var texture = host.ImageCache.GetImage(image).Texture; + var device = MetalNative.Send(texture, MetalNative.Selector("device")); + var buffer = MetalNative.SendNewBuffer(device, MetalNative.Selector("newBufferWithLength:options:"), 4, 0); + var queue = MetalNative.Send(device, MetalNative.Selector("newCommandQueue")); + try + { + var commands = MetalNative.Send(queue, MetalNative.Selector("commandBuffer")); + var blit = MetalNative.Send(commands, MetalNative.Selector("blitCommandEncoder")); + MetalNative.SendCopyTextureToBuffer( + blit, MetalNative.Selector( + "copyFromTexture:sourceSlice:sourceLevel:sourceOrigin:sourceSize:toBuffer:destinationOffset:" + + "destinationBytesPerRow:destinationBytesPerImage:"), + texture, layer, 0, default, new MtlSize { Width = 1, Height = 1, Depth = 1 }, buffer, 0, 4, 4); + MetalNative.SendVoid(blit, MetalNative.Selector("endEncoding")); + MetalNative.SendVoid(commands, MetalNative.Selector("commit")); + MetalNative.SendVoid(commands, MetalNative.Selector("waitUntilCompleted")); + return new ReadOnlySpan((void*)MetalNative.Send(buffer, MetalNative.Selector("contents")), 4).ToArray(); + } + finally + { + MetalNative.SendVoid(buffer, MetalNative.Selector("release")); + MetalNative.SendVoid(queue, MetalNative.Selector("release")); + } + } + + // Each cleared layer's first texel holds the clear; every other layer's, the guest's LaterPattern. + private static void AssertLayers(byte[] guest, uint[] cleared, float clear) + { + var layerBytes = (int)ArrayLayerBytes(); + var clearBytes = BitConverter.GetBytes(clear); + for (var layer = 0u; layer < ArrayLayers; layer++) + { + var expected = Array.IndexOf(cleared, layer) >= 0 ? clearBytes : [LaterPattern, LaterPattern, LaterPattern, LaterPattern]; + Assert.Equal(expected, guest[(int)(layer * layerBytes)..(int)(layer * layerBytes + 4)]); + } + } + + private static ulong ArrayLayerBytes() + { + Assert.True(TileGeometry.TryGetDepthSize(ArrayWidth, ArrayHeight, 0, GuestDepthFormat.Z32Float, + GuestStencilFormat.Invalid, false, out _, out _, out var depthSize)); + return (ulong)depthSize.Size; + } + + private static ImageRequest DepthArrayRequest(uint layer, ImageRole role) + { + var size = ArrayLayerBytes() * ArrayLayers; + var pitch = TileGeometry.DepthPitch(ArrayWidth, 4); + var description = ImageDescription.Create(); + description.Data = new GuestSpan(ArrayAddress, size); + description.PixelFormat = GpuFormat.D32Sfloat; + description.GuestFormat = GuestPixelFormat.Bits32Float; + description.Type = GuestImageType.Color2D; + description.Extent = new GpuExtent3D(ArrayWidth, ArrayHeight, 1); + description.Resources = new SubresourceCount(1, ArrayLayers); + description.Pitch = pitch; + description.BytesPerBlock = 4; + description.Samples = 1; + description.TileMode = GuestTileMode.Depth; + description.MipLayout[0] = new MipLevelLayout { Offset = 0, Size = size, Pitch = pitch, Height = ArrayHeight }; + var view = ImageViewDescription.Default with + { + Format = GpuFormat.D32Sfloat, + Type = GpuImageViewType.Type2D, + Aspect = GpuImageAspect.DepthBit, + BaseLayer = layer, + LayerCount = 1, + Usage = role == ImageRole.DepthTarget ? GpuImageUsage.DepthStencilAttachmentBit : GpuImageUsage.SampledBit, + }; + return new ImageRequest(description, view, role); + } + + private static DepthAttachmentState DepthArrayTarget(ResourceSlotIdentifier image, uint layer, bool clear) + { + var request = DepthArrayRequest(layer, ImageRole.DepthTarget); + var resolution = new DepthTargetResolution( + request, GpuFormat.D32Sfloat, ArrayWidth, ArrayHeight, 1, false, false, + ArrayAddress, request.Description.Data.Size, 0, 0, 0, 0, clear, false, false, false); + var state = new DepthStencilState( + clear, 0f, true, true, GpuCompareOp.Always, false, 0f, 1f, false, 0, false, + StencilOperations.Default, default, StencilOperations.Default, default); + return new DepthAttachmentState(new DepthTargetState(resolution, state), image); + } + + private static RenderingState DepthPass(GpuImageHandle view, float clear) + { + var state = new RenderingState { Width = ArrayWidth, Height = ArrayHeight, Layers = 1, ColorAttachmentCount = 0, Samples = 1 }; + state.DepthStencilAttachment = new RenderingAttachment( + view, GpuFormat.D32Sfloat, BitConverter.SingleToUInt32Bits(clear), 0, 0, 0, true, true, true, false, false); + return state; + } + private static void AssertPixels(byte[] bytes, byte[] pixel) { for (var offset = 0; offset < bytes.Length; offset += 4) @@ -248,17 +471,21 @@ public static RenderingState PassOver(GpuImageHandle view, bool clear) // Writes guest memory directly, the way nothing the cache watches would. An upload // reads guest memory when the GPU runs it, so the GPU is let finish first. - public void FillBacking(ulong address, byte value) + public void FillBacking(ulong address, byte value) => FillBacking(address, ImageBytes, value); + + public void FillBacking(ulong address, ulong size, byte value) { Host.FlushAndWaitForGpu(); - var bytes = new byte[ImageBytes]; + var bytes = new byte[size]; Array.Fill(bytes, value); Assert.True(_backing.TryWriteBacking(address, bytes)); } - public byte[] Read(ulong address) + public byte[] Read(ulong address) => Read(address, ImageBytes); + + public byte[] Read(ulong address, ulong size) { - var bytes = new byte[ImageBytes]; + var bytes = new byte[size]; Assert.True(Host.TryReadGuest(address, bytes)); return bytes; } diff --git a/tests/SharpEmu.Gpu.Metal.Tests/MetalImageTransferTests.CoveringRuns.cs b/tests/SharpEmu.Gpu.Metal.Tests/MetalImageTransferTests.CoveringRuns.cs index 72b2d6ef8..bb9028ec3 100644 --- a/tests/SharpEmu.Gpu.Metal.Tests/MetalImageTransferTests.CoveringRuns.cs +++ b/tests/SharpEmu.Gpu.Metal.Tests/MetalImageTransferTests.CoveringRuns.cs @@ -105,4 +105,162 @@ public void AnOverlapWhoseRunIsTheWholeImageFallsBack(uint width, uint height, u Assert.False(MetalImageCache.TryCoveringRun(transfer, in description, dirtyStart, dirtyEnd, out _, out _)); } + + // ---- Depth runs from a layer past the first (SHARPEMU_METAL_V2_DEPTH_LAYER_RUNS) ---------------------------- + // A depth plane is cut a layer at a time: a run over the tail or the middle begins at the layer it is dirty from. + // With the switch off a depth run begins at the first byte, as it always did. + + [Theory] + [InlineData(false, 1u)] + [InlineData(false, 2u)] + [InlineData(false, 3u)] + [InlineData(true, 1u)] + [InlineData(true, 2u)] + [InlineData(true, 3u)] + public void ADepthRunBeginsAtTheLayerItIsDirtyFrom(bool stencil, uint layer) + { + using var transfer = new MetalImageTransfer(RequireDevice() ? Device.Value : CreateHeadlessDevice()); + var description = Depth(GuestDepthFormat.Z32Float, stencil, 128, 64, 4); + var slice = description.Data.Size / 4; + + Assert.True(MetalImageCache.TryCoveringRun( + transfer, in description, layer * slice + 0x10, description.Data.Size, true, out var start, out var end)); + Assert.Equal(layer * slice, start); + Assert.Equal(description.Data.Size, end); + + Assert.True(MetalImageCache.TryCoveringRun( + transfer, in description, layer * slice + 0x10, layer * slice + 0x20, true, out start, out end)); + Assert.Equal(layer * slice, start); + Assert.Equal((layer + 1) * slice, end); + + // Off: the tail run is the whole image, refused; the middle one starts at the first byte. + Assert.False(MetalImageCache.TryCoveringRun( + transfer, in description, layer * slice + 0x10, description.Data.Size, false, out _, out _)); + if (layer < 3) + { + Assert.True(MetalImageCache.TryCoveringRun( + transfer, in description, layer * slice + 0x10, layer * slice + 0x20, false, out start, out end)); + Assert.Equal(0UL, start); + Assert.Equal((layer + 1) * slice, end); + } + } + + // On the device: an upload of layers [layer, 4) over a texture holding another image, and a writeback of them over + // guest bytes holding another image, leave exactly what the whole transfer of the composite leaves - depth and + // stencil planes both, bit for bit. + [Theory] + [InlineData(false, 1u)] + [InlineData(false, 2u)] + [InlineData(false, 3u)] + [InlineData(true, 1u)] + [InlineData(true, 2u)] + [InlineData(true, 3u)] + public void ADepthRunFromALayerMovesExactlyItsLayers(bool stencil, uint layer) + { + if (!RequireDevice()) return; + using var harness = new MetalTransferHarness(Device.Value); + var description = Depth(GuestDepthFormat.Z32Float, stencil, 128, 64, 4); + var size = description.Data.Size; + var slice = size / 4; + var stencilSize = stencil ? description.Stencil.Size : 0; + var stencilSlice = stencilSize / 4; + var first = BuildGuest(description, 91); + var second = BuildGuest(description, 92); + var firstStencil = stencil ? TiledStencil(description, 93) : []; + var secondStencil = stencil ? TiledStencil(description, 94) : []; + var composite = Splice(first, second, layer * slice); + var compositeStencil = Splice(firstStencil, secondStencil, layer * stencilSlice); + var range = new SubresourceRange(0, 1, 0, 4); + var runSize = size - layer * slice; + var stencilRunSize = stencilSize - layer * stencilSlice; + + MetalGuestRange Whole(byte[] bytes) => new(harness.Buffer(bytes), 0, (ulong)bytes.Length, 0); + MetalGuestRange Tail(byte[] bytes, ulong from) => new(harness.Buffer(bytes[(int)from..]), 0, (ulong)bytes.Length - from, 0); + + // Upload: the first image whole, then the second's layers from `layer` as a run. + var texture = harness.Texture(harness.Transfer.ShapeFor(description)); + harness.Begin(); + Assert.True(harness.Transfer.EncodeGuestToTexture( + harness, description, range, Whole(first), stencil ? Whole(firstStencil) : default, texture, 0, size)); + harness.Submit(); + harness.Begin(); + Assert.True(harness.Transfer.EncodeGuestToTexture( + harness, description, range, Tail(second, layer * slice), + stencil ? Tail(secondStencil, layer * stencilSlice) : default, texture, layer * slice, runSize)); + harness.Submit(); + var (depthOut, stencilOut) = WriteBackWhole(harness, description, range, texture); + Assert.Equal(composite, depthOut); + Assert.Equal(compositeStencil, stencilOut); + + // Writeback: the composite whole into a texture, then its layers from `layer` as a run over the first image. + var compositeTexture = harness.Texture(harness.Transfer.ShapeFor(description)); + harness.Begin(); + Assert.True(harness.Transfer.EncodeGuestToTexture( + harness, description, range, Whole(composite), stencil ? Whole(compositeStencil) : default, + compositeTexture, 0, size)); + harness.Submit(); + var target = harness.Buffer(first); + var stencilTarget = stencil ? harness.Buffer(firstStencil) : 0; + harness.Begin(); + Assert.True(harness.Transfer.EncodeTextureToGuest( + harness, description, range, compositeTexture, new MetalGuestRange(target, layer * slice, runSize, 0), + stencil ? new MetalGuestRange(stencilTarget, layer * stencilSlice, stencilRunSize, 0) : default, + layer * slice, runSize)); + harness.Submit(); + Assert.Equal(composite, harness.Read(target, 0, size)); + if (stencil) + { + Assert.Equal(compositeStencil, harness.Read(stencilTarget, 0, stencilSize)); + } + } + + private static (byte[] Depth, byte[] Stencil) WriteBackWhole( + MetalTransferHarness harness, in ImageDescription description, SubresourceRange range, nint texture) + { + var target = harness.Buffer(description.Data.Size); + var stencilTarget = description.HasStencil ? harness.Buffer(description.Stencil.Size) : 0; + harness.Begin(); + Assert.True(harness.Transfer.EncodeTextureToGuest( + harness, description, range, texture, new MetalGuestRange(target, 0, description.Data.Size, 0), + stencilTarget != 0 ? new MetalGuestRange(stencilTarget, 0, description.Stencil.Size, 0) : default, + 0, description.Data.Size)); + harness.Submit(); + return (harness.Read(target, 0, description.Data.Size), + stencilTarget != 0 ? harness.Read(stencilTarget, 0, description.Stencil.Size) : []); + } + + private static byte[] Splice(byte[] head, byte[] tail, ulong at) + { + var bytes = (byte[])tail.Clone(); + head.AsSpan(0, (int)at).CopyTo(bytes); + return bytes; + } + + // A stencil plane with every byte its tiled transfer carries set and the rest zero (as RoundTrip builds it). + private static byte[] TiledStencil(in ImageDescription description, uint seed) + { + var linear = MetalTileOracle.Pattern((int)description.Stencil.Size, seed); + var tiled = new byte[description.Stencil.Size]; + var pitch = TileGeometry.DepthPitch(description.Extent.Width, 1); + var slice = description.Stencil.Size / description.Resources.Layers; + for (uint layer = 0; layer < description.Resources.Layers; layer++) + { + MetalTileOracle.Transfer(linear, tiled, new MetalTileTransfer + { + Kind = TileBlockKind.Depth64KB, + BytesPerElement = 1, + LinearOffset = slice * layer, + LinearSize = slice, + TiledOffset = slice * layer, + TiledSize = slice, + Width = description.Extent.Width, + Height = description.Extent.Height, + Depth = 1, + Pitch = pitch, + SurfaceZ = layer, + }, toTiled: true); + } + + return tiled; + } } From 706c65d152005bfa68340aef42b49b8e5b4c2ae1 Mon Sep 17 00:00:00 2001 From: kuba Date: Sun, 15 Nov 2026 06:51:46 +0000 Subject: [PATCH 032/178] [Metal] Count CP write order suspects at the reads answered from unlanded bytes SHARPEMU_METAL_V2_CP_WRITE_DEVICE_ORDER=verify now counts every read the host answers from bytes not yet landed (the command-processor overlay, a pending copy) and every hit in the pending-label table; a write its queue does not flag causal after that count moved since the queue's previous write is a suspect, logged once with the read's address and size. The fold's =verify skips GDS and occlusion copies, whose source GPU work still ahead produces. --- .../Gpu/GpuCommands/CommandStreamQueue.cs | 2 + .../Gpu/GpuCommands/GpuCommandInterpreter.cs | 57 ++++++++++++++++--- .../V2/MetalCommandStream.cs | 1 - .../V2/MetalRenderHost.CommandThread.cs | 1 + .../V2/MetalRenderHost.LabelLanding.cs | 37 ++++++------ .../V2/MetalRenderHost.LabelScatter.cs | 10 +++- .../V2/MetalRenderHost.Rendering.cs | 5 +- .../SharpEmu.Gpu.Metal/V2/MetalRenderHost.cs | 4 ++ 8 files changed, 90 insertions(+), 27 deletions(-) diff --git a/src/SharpEmu.Libs/Gpu/GpuCommands/CommandStreamQueue.cs b/src/SharpEmu.Libs/Gpu/GpuCommands/CommandStreamQueue.cs index fe18d863f..0cb578563 100644 --- a/src/SharpEmu.Libs/Gpu/GpuCommands/CommandStreamQueue.cs +++ b/src/SharpEmu.Libs/Gpu/GpuCommands/CommandStreamQueue.cs @@ -1144,6 +1144,7 @@ private bool TryGetPendingLabel(ulong address, bool is64Bit, out ulong value) if (_pendingLabels.TryGetValue(address, out var label) && label.Size >= (is64Bit ? 8 : 4)) { value = is64Bit ? label.Value : (uint)label.Value; + GpuCommandInterpreter.NotePendingAnswer(address, is64Bit ? 8 : 4); return true; } @@ -1151,6 +1152,7 @@ private bool TryGetPendingLabel(ulong address, bool is64Bit, out ulong value) if (!is64Bit && address >= 4 && _pendingLabels.TryGetValue(address - 4, out label) && label.Size == 8) { value = (uint)(label.Value >> 32); + GpuCommandInterpreter.NotePendingAnswer(address, 4); return true; } diff --git a/src/SharpEmu.Libs/Gpu/GpuCommands/GpuCommandInterpreter.cs b/src/SharpEmu.Libs/Gpu/GpuCommands/GpuCommandInterpreter.cs index 34b91cf36..ca9600860 100644 --- a/src/SharpEmu.Libs/Gpu/GpuCommands/GpuCommandInterpreter.cs +++ b/src/SharpEmu.Libs/Gpu/GpuCommands/GpuCommandInterpreter.cs @@ -67,17 +67,40 @@ public sealed partial class GpuCommandInterpreter // waits for nothing and publishes nothing for the CPU. private bool _cpWriteCausal; - private static long _pendingValueReads; - - /// Reads answered from a value not yet landed, on any queue (SHARPEMU_METAL_V2_CP_WRITE_DEVICE_ORDER=verify). - public static long PendingValueReads => Interlocked.Read(ref _pendingValueReads); - - private void NoteCausalRead() + private void NoteCausalRead() => _cpWriteCausal = true; + + // SHARPEMU_METAL_V2_CP_WRITE_DEVICE_ORDER=verify (the host sets CpWriteOrderVerify): every read answered from bytes + // not yet landed counts where it is answered (the host's unlanded command-processor bytes and held copies, this + // queue's pending-label table), on any queue. A write this queue does not flag causal, made after that count moved + // since its previous write, is a suspect: a causal read site the interpreter does not flag. The count is global, so + // another queue's read can raise a suspect too (a lead, never a miss); reads the GPU makes at execution (indirect + // arguments, resources) are not counted. + public static bool CpWriteOrderVerify { get; set; } + + private static long _pendingAnswers; + private static long _cpWriteOrderSuspects; + private static ulong _lastPendingAnswerAddress; + private static int _lastPendingAnswerSize; + private long _pendingAnswersAtWrite = Interlocked.Read(ref _pendingAnswers); + + /// A read answered from bytes not yet landed (verify only). + public static void NotePendingAnswer(ulong address, int size) { - _cpWriteCausal = true; - Interlocked.Increment(ref _pendingValueReads); + if (!CpWriteOrderVerify) + { + return; + } + + _lastPendingAnswerAddress = address; + _lastPendingAnswerSize = size; + Interlocked.Increment(ref _pendingAnswers); } + /// Unflagged command-processor writes made after a read answered from bytes not yet landed (verify only). + public static long TakeCpWriteOrderSuspects() => Interlocked.Exchange(ref _cpWriteOrderSuspects, 0); + + private static int _cpWriteOrderSuspectLogged; + private void EmitOrderingBarrier() { _cpWriteCausal = true; @@ -88,6 +111,24 @@ private bool TakeCommandProcessorWriteCausal() { var causal = _cpWriteCausal; _cpWriteCausal = false; + if (CpWriteOrderVerify) + { + var answers = Interlocked.Read(ref _pendingAnswers); + if (!causal && answers != _pendingAnswersAtWrite) + { + Interlocked.Increment(ref _cpWriteOrderSuspects); + if (Interlocked.Exchange(ref _cpWriteOrderSuspectLogged, 1) == 0) + { + Console.Error.WriteLine( + $"[LOADER][WARN] command_stream.cp_write_order_suspect queue={QueueId} " + + $"read=0x{_lastPendingAnswerAddress:X16} size={_lastPendingAnswerSize}: a command-processor write " + + "not flagged causal followed a read answered from bytes not yet landed."); + } + } + + _pendingAnswersAtWrite = answers; + } + return causal; } diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalCommandStream.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalCommandStream.cs index 8c62b8f3d..9c9f97819 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalCommandStream.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalCommandStream.cs @@ -1835,7 +1835,6 @@ private void EncodeLabelBarrier(nint commandBuffer, ReadOnlySpan destinatio _cpOverlay.Coverage(address, size, _signaledSerialReader ??= SignaledSerial) != MetalOverlayCoverage.None) { _cpOverlay.Apply(address, destination); + NotePendingAnswer(address, destination.Length); } return true; diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.LabelLanding.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.LabelLanding.cs index 0b702a181..76d28d53e 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.LabelLanding.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.LabelLanding.cs @@ -86,6 +86,9 @@ private void RequestLabelLanding(LabelLandCause cause) } } + /// Tests: the held copies land at the next boundary, as a join that ends a pass asks (Join). + internal void RequestLabelLandingForTest() => RequestLabelLanding(LabelLandCause.Join); + private static int LabelMixIndex(in DeferredLabelCopy copy) => copy.Kind switch { LabelCopyKind.CpWrite => 0, @@ -140,21 +143,31 @@ private void NoteLabelLanding(ReadOnlySpan copies, LabelLandC // since its previous write) is held device-ordered rather than CPU-visible. On the console such a WRITE_DATA waits // for no earlier work and publishes nothing for the CPU, so it needs no shared event, and a batch of them lands // inside the open compute encoder. Every Demon's Souls batch held one and paid the shared event for it. - // =verify keeps every write CPU-visible and counts (cp_write_order_suspects, logged once) the ones that would have - // been device-ordered while some queue had read a pending value since the last shared barrier: a causal read site - // the interpreter does not flag shows up there. + // =verify keeps every write CPU-visible and counts at the read: every read this host answers from bytes not yet + // landed (the command-processor overlay, a pending copy) and every hit in a queue's pending-label table bumps a + // counter, and a write its queue does not flag causal, made after that counter moved since the queue's previous + // write, is counted (cp_write_order_suspects) and logged once with the read's address and size + // (GpuCommandInterpreter.CpWriteOrderVerify). A causal read site the interpreter does not flag shows up there. private static readonly string? CpWriteDeviceOrderMode = Environment.GetEnvironmentVariable("SHARPEMU_METAL_V2_CP_WRITE_DEVICE_ORDER"); internal bool CpWritesDeviceOrdered { get; set; } = CpWriteDeviceOrderMode is not ("0" or "verify"); - private static readonly bool CpWriteDeviceOrderVerify = CpWriteDeviceOrderMode == "verify"; + private static readonly bool CpWriteDeviceOrderVerify = + SharpEmu.Libs.Gpu.GpuCommands.GpuCommandInterpreter.CpWriteOrderVerify = CpWriteDeviceOrderMode == "verify"; + + // A read answered from bytes not yet landed (counted for =verify only). + private static void NotePendingAnswer(ulong address, int size) + { + if (CpWriteDeviceOrderVerify) + { + SharpEmu.Libs.Gpu.GpuCommands.GpuCommandInterpreter.NotePendingAnswer(address, size); + } + } // A causal command-processor write is held: every later one is held CPU-visible behind it until the held copies // land, so none overtakes it and the order of the writes is kept across the landing. private bool _causalCpWriteHeld; - private long _pendingReadsAtSharedBarrier; - private long _cpWriteOrderSuspects; // Command-processor writes recorded as a dispatch in the open compute encoder rather than held (label_cp_in_encoder). private long _labelCpInEncoder; @@ -162,15 +175,6 @@ private void NoteLabelLanding(ReadOnlySpan copies, LabelLandC private (bool CpuVisible, LabelCopyKind Kind) CommandProcessorWriteClass(bool causal) { var ordered = causal || _causalCpWriteHeld; - if (CpWriteDeviceOrderVerify && !ordered && - SharpEmu.Libs.Gpu.GpuCommands.GpuCommandInterpreter.PendingValueReads != _pendingReadsAtSharedBarrier) - { - _cpWriteOrderSuspects++; - MetalV2Diagnostics.WarnOnce("cp-write-order-suspect", - "A command-processor write its queue did not flag as causal followed a read of a pending value since the " + - "last shared label barrier (SHARPEMU_METAL_V2_CP_WRITE_DEVICE_ORDER=verify)."); - } - return (!CpWritesDeviceOrdered || ordered, ordered ? LabelCopyKind.CpCausal : LabelCopyKind.CpWrite); } @@ -186,7 +190,8 @@ private void NoteCommandProcessorWriteHeld(bool causal, int heldBefore) private string TakeLabelLandingCounters() { var text = new System.Text.StringBuilder(256); - text.Append(" cp_write_order_suspects=").Append(Interlocked.Exchange(ref _cpWriteOrderSuspects, 0)); + text.Append(" cp_write_order_suspects=") + .Append(SharpEmu.Libs.Gpu.GpuCommands.GpuCommandInterpreter.TakeCpWriteOrderSuspects()); text.Append(" label_cp_in_encoder=").Append(Interlocked.Exchange(ref _labelCpInEncoder, 0)); Append(text, "label_land", LabelLandNames, _labelLand); Append(text, "label_batch", LabelBatchNames, _labelBatch); diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.LabelScatter.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.LabelScatter.cs index a43f6b8c9..5a96a9242 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.LabelScatter.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.LabelScatter.cs @@ -364,9 +364,17 @@ private unsafe void VerifyFoldedCopies(ReadOnlySpan copies) var expected = new Dictionary(); foreach (ref readonly var copy in copies) { - var staging = (byte*)MetalNative.Send(copy.StagingBuffer, SelLabelFoldContents); + // Only staging the host wrote (an end-of-pipe value, a command-processor write) holds its value now; a GDS or + // occlusion source is produced by GPU work still ahead, so its words are not checked, and a word it lands + // over is no longer what an earlier copy wrote. + var staging = copy.Kind == LabelCopyKind.Other ? null : (byte*)MetalNative.Send(copy.StagingBuffer, SelLabelFoldContents); if (staging == null) { + for (var offset = 0; offset < copy.Bytes; offset += sizeof(uint)) + { + expected.Remove(copy.GuestAddress + (ulong)offset); + } + continue; } diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Rendering.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Rendering.cs index 3a0ec929f..ea9a17583 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Rendering.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Rendering.cs @@ -1456,7 +1456,10 @@ private nint EnsureComputeEncoder(bool materializeClears) EndRendering(); EncodeStagedStores(); // Copies that land here and need no shared event land in the encoder this opens, after its fence wait - // (MetalRenderHost.LabelScatter.cs), instead of in a copy encoder of their own ahead of it. + // (MetalRenderHost.LabelScatter.cs), instead of in a copy encoder of their own ahead of it. A clear this + // dispatch sees cannot land after them: MaterializePendingClearsForCompute below encodes it through + // BeginTransfer, whose EndEncoders lands these copies first (EncodeDeferredLabelCopies), so the fold then + // finds none. foldAtOpen = _deferredLabelCopies.Count != 0 && (!LabelsAtCommit || _landDeferredLabels) && !_encodingDeferredLabels && MayFoldHeldCopies(System.Runtime.InteropServices.CollectionsMarshal.AsSpan(_deferredLabelCopies)); if (!foldAtOpen) diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.cs index f735d4524..e20d67810 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.cs @@ -1973,6 +1973,7 @@ public bool TryReadGuest(ulong address, Span destination) case MetalOverlayCoverage.Full: _cpOverlay.Apply(address, destination); Interlocked.Increment(ref _overlayReads); + NotePendingAnswer(address, destination.Length); return true; case MetalOverlayCoverage.Partial: if (!TryReadGuestCore(address, destination)) @@ -1982,6 +1983,7 @@ public bool TryReadGuest(ulong address, Span destination) _cpOverlay.Apply(address, destination); Interlocked.Increment(ref _overlayReads); + NotePendingAnswer(address, destination.Length); return true; } } @@ -2026,6 +2028,7 @@ private bool TryReadGuestCore(ulong address, Span destination) if (TryReadThroughPendingCopy(address, destination)) { + NotePendingAnswer(address, destination.Length); return true; } @@ -2208,6 +2211,7 @@ public bool TryReadGuestWaitOperand(ulong address, Span destination, bool // The poll reads bytes this host has yet to land as written: nothing to commit. _cpOverlay.Apply(address, destination); Interlocked.Increment(ref _overlayReads); + NotePendingAnswer(address, destination.Length); return true; } From ab095ec4663a49eab6f38df1c2edc546745ef5db Mon Sep 17 00:00:00 2001 From: kuba Date: Sun, 15 Nov 2026 06:51:46 +0000 Subject: [PATCH 033/178] [Tests] Label fold refusals, fold at open, switches off, and causal read sites --- .../V2/MetalRenderHost.StagedStorage.cs | 8 + .../MetalEndOfPipeOrderTests.LabelFold.cs | 213 ++++++++++++++++++ .../GpuCommands/CommandStreamQueueTests.cs | 110 +++++++++ .../GpuCommands/CommandStreamTestSupport.cs | 7 + 4 files changed, 338 insertions(+) diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.StagedStorage.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.StagedStorage.cs index fd25dbacb..4e7fbb77e 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.StagedStorage.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.StagedStorage.cs @@ -13,6 +13,14 @@ internal sealed partial class MetalRenderHost private MetalStagedStorage StagedStorage => _stagedStorageCopies ??= new MetalStagedStorage(_guestMemory, _stagedRanges); + /// Tests: a staged copy of these bytes, written by a recorded dispatch, to be written back at the encoder end. + internal void StageRecordedStoresForTest(ulong address, ulong size) + { + var staging = _guestMemory.Stage(address, size); + StagedStorage.Add(address, size, staging, _guestMemory.Stage(address, size), written: true); + StagedStorage.Arm(); + } + private bool _encodingStagedStores; /// diff --git a/tests/SharpEmu.Gpu.Metal.Tests/MetalEndOfPipeOrderTests.LabelFold.cs b/tests/SharpEmu.Gpu.Metal.Tests/MetalEndOfPipeOrderTests.LabelFold.cs index a3521942f..bdca7e6c3 100644 --- a/tests/SharpEmu.Gpu.Metal.Tests/MetalEndOfPipeOrderTests.LabelFold.cs +++ b/tests/SharpEmu.Gpu.Metal.Tests/MetalEndOfPipeOrderTests.LabelFold.cs @@ -318,4 +318,217 @@ public void ACpuVisibleLabelIsNeverSeenBeforeTheStoreAheadOfIt() Assert.Equal(0, early); } + + // A causal write the GPU path declines (an older label is owed by a completion) goes to the completion queue; a + // plain write to the same bytes after it, with a compute encoder open, is declined by the same guard + // (MayEncodeLabelOnGpu at the top of TryEncodeCommandProcessorWrite) before Step 3 or the fold can see it, so it + // lands after the first, in order: the final bytes are the second write's. + [Fact] + public void APlainWriteAfterADeclinedCausalWriteLandsAfterIt() + { + if (!RequireDevice()) return; + using var hold = new ManualResetEventSlim(false); + using var rig = new Rig(Device.Value); + var host = rig.Host; + try + { + host.RecordEndOfPipe(new EndOfPipeWrite(EndOfPipeWriteKind.Write32, 1, WindowedLabel, 0xA0)); + var held = host.SubmissionSerial; + host.Completions.Enqueue(held, () => hold.Wait(TimeSpan.FromSeconds(10))); + // No window covers it, so this label is owed by a completion. + host.RecordEndOfPipe(new EndOfPipeWrite(EndOfPipeWriteKind.Write32, 1, UnwindowedLabel, 1)); + var inEncoder = host.CpWritesEncodedInEncoder; + + host.RecordCommandProcessorWrite(LaterLabel, BitConverter.GetBytes(0x11UL), "WRITE_DATA", causal: true); + _ = host.EnsureComputeEncoder(); + Assert.True(host.ComputeEncoderOpen); + host.RecordCommandProcessorWrite(LaterLabel, BitConverter.GetBytes(0x22UL), "WRITE_DATA", causal: false); + Assert.Equal(inEncoder, host.CpWritesEncodedInEncoder); + Assert.Equal(0, host.DeferredLabelCopyCount); + + host.FlushCommandBuffer(); + WaitForGpu(host, host.LastWorkSerial); + Assert.Equal(0UL, rig.Backing.Read64(LaterLabel)); + hold.Set(); + WaitForCompletions(host); + Assert.Equal(0x22UL, rig.Backing.Read64(LaterLabel)); + } + finally + { + hold.Set(); + } + } + + // Stores a dispatch recorded into a staged copy are written back when the encoder ends, so a held copy is not folded + // into the encoder ahead of them (counted as staged) and a plain write is held rather than encoded in it at once. + [Fact] + public void RecordedStagedStoresRefuseTheFoldAndHoldAPlainWrite() + { + if (!RequireDevice()) return; + using var rig = new Rig(Device.Value); + var host = rig.Host; + _ = host.TakeLabelInEncoderRefusals(); + _ = host.TakeLabelBarrierKinds(); + + _ = host.EnsureComputeEncoder(); + host.StageRecordedStoresForTest(GuestBase + 0x10000, 0x100); + host.RecordEndOfPipe(new EndOfPipeWrite(EndOfPipeWriteKind.Write64, 1, WindowedLabel, 7)); + var folded = host.LabelsFolded; + host.OrderAfterDeferredCopies(WindowedLabel, 8); + Assert.False(host.ComputeEncoderOpen); + Assert.Equal(folded, host.LabelsFolded); + Assert.Equal(1L, host.TakeLabelInEncoderRefusals()[3]); + Assert.Equal(new long[] { 0, 1, 0, 0 }, host.TakeLabelBarrierKinds()); + + _ = host.EnsureComputeEncoder(); + host.StageRecordedStoresForTest(LaterLabel, 0x100); + var inEncoder = host.CpWritesEncodedInEncoder; + host.RecordCommandProcessorWrite(LaterLabel, BitConverter.GetBytes(0x55UL), "WRITE_DATA", causal: false); + Assert.Equal(inEncoder, host.CpWritesEncodedInEncoder); + + host.FlushCommandBuffer(); + WaitForGpu(host, host.LastWorkSerial); + WaitForCompletions(host); + Assert.Equal(7UL, rig.Backing.Read64(WindowedLabel)); + Assert.Equal(0x55UL, rig.Backing.Read64(LaterLabel)); + } + + // Held copies a join asked to land, with no compute encoder open, land in the one the next dispatch opens, after its + // fence wait. + [Fact] + public void HeldCopiesFoldIntoTheComputeEncoderTheyOpen() + { + if (!RequireDevice()) return; + using var rig = new Rig(Device.Value); + var host = rig.Host; + Assert.False(host.ComputeEncoderOpen); + host.RecordEndOfPipe(new EndOfPipeWrite(EndOfPipeWriteKind.Write64, 1, WindowedLabel, 0x31)); + Assert.Equal(1, host.DeferredLabelCopyCount); + var folded = host.LabelsFolded; + _ = host.TakeLabelBarrierKinds(); + + host.RequestLabelLandingForTest(); + _ = host.EnsureComputeEncoder(); + Assert.True(host.ComputeEncoderOpen); + Assert.Equal(0, host.DeferredLabelCopyCount); + Assert.Equal(folded + 1, host.LabelsFolded); + Assert.Equal(new long[] { 0, 0, 0, 1 }, host.TakeLabelBarrierKinds()); + + host.FlushCommandBuffer(); + WaitForGpu(host, host.LastWorkSerial); + WaitForCompletions(host); + Assert.Equal(0x31UL, rig.Backing.Read64(WindowedLabel)); + } + + // A held copy that is not whole aligned words refuses the whole fold (counted as scatter): in the open encoder + // (atOpen false) and in the one a dispatch opens (atOpen true, the decline fallback that ends it and opens + // another). The old path lands the list in order behind the device event: the later label overwrites the unaligned + // write's upper half, the unaligned write the earlier label's middle. + [Theory] + [InlineData(false)] + [InlineData(true)] + public void AnUnalignedHeldCopyRefusesTheWholeFoldAndTheListLandsInOrder(bool atOpen) + { + if (!RequireDevice()) return; + using var rig = new Rig(Device.Value); + var host = rig.Host; + _ = host.TakeLabelInEncoderRefusals(); + _ = host.TakeLabelBarrierKinds(); + if (!atOpen) + { + _ = host.EnsureComputeEncoder(); + } + + host.RecordEndOfPipe(new EndOfPipeWrite(EndOfPipeWriteKind.Write64, 1, LaterLabel, 0x11111111_11111111UL)); + host.RecordCommandProcessorWrite(LaterLabel + 2, BitConverter.GetBytes(0xAABBCCDDu), "WRITE_DATA", causal: false); + host.RecordEndOfPipe(new EndOfPipeWrite(EndOfPipeWriteKind.Write32, 1, LaterLabel + 4, 0x22222222)); + Assert.Equal(3, host.DeferredLabelCopyCount); + var folded = host.LabelsFolded; + if (atOpen) + { + host.RequestLabelLandingForTest(); + _ = host.EnsureComputeEncoder(); + Assert.True(host.ComputeEncoderOpen); + } + else + { + host.OrderAfterDeferredCopies(LaterLabel, 8); + Assert.False(host.ComputeEncoderOpen); + } + + Assert.Equal(0, host.DeferredLabelCopyCount); + Assert.Equal(folded, host.LabelsFolded); + Assert.Equal(1L, host.TakeLabelInEncoderRefusals()[1]); + Assert.Equal(new long[] { 0, 1, 0, 0 }, host.TakeLabelBarrierKinds()); + + host.FlushCommandBuffer(); + WaitForGpu(host, host.LastWorkSerial); + WaitForCompletions(host); + Assert.Equal(0x22222222_CCDD1111UL, rig.Backing.Read64(LaterLabel)); + } + + // Two held copies into the same words in one fold: the scatter keeps the later source per word. + [Fact] + public void TheLaterOfTwoHeldCopiesToTheSameWordWinsInsideOneFold() + { + if (!RequireDevice()) return; + using var rig = new Rig(Device.Value); + var host = rig.Host; + _ = host.EnsureComputeEncoder(); + host.RecordEndOfPipe(new EndOfPipeWrite(EndOfPipeWriteKind.Write32, 1, WindowedLabel, 0x11)); + host.RecordEndOfPipe(new EndOfPipeWrite(EndOfPipeWriteKind.Write64, 1, WindowedLabel, 0x33333333_33333333UL)); + host.RecordEndOfPipe(new EndOfPipeWrite(EndOfPipeWriteKind.Write32, 1, WindowedLabel + 4, 0x22)); + var folded = host.LabelsFolded; + host.OrderAfterDeferredCopies(WindowedLabel, 8); + Assert.True(host.ComputeEncoderOpen); + Assert.Equal(folded + 1, host.LabelsFolded); + + host.FlushCommandBuffer(); + WaitForGpu(host, host.LastWorkSerial); + WaitForCompletions(host); + Assert.Equal(0x00000022_33333333UL, rig.Backing.Read64(WindowedLabel)); + } + + // With SHARPEMU_METAL_V2_LABELS_IN_ENCODER, _CP_WRITE_DEVICE_ORDER and _CP_WRITES_IN_ENCODER all 0, a mixed sequence + // lands as before the change: a batch with a command-processor write is CPU-visible and takes the shared event, a + // device-only label batch the device event, each ending the encoder; nothing is folded or encoded in the encoder. + [Fact] + public void WithTheThreeSwitchesOffAMixedSequenceLandsAsBefore() + { + if (!RequireDevice()) return; + using var rig = new Rig(Device.Value); + var host = rig.Host; + host.LabelsInEncoder = false; + host.CpWritesDeviceOrdered = false; + host.CpWritesInEncoder = false; + _ = host.TakeLabelBarriers(); + _ = host.TakeLabelBarrierKinds(); + var folded = host.LabelsFolded; + var inEncoder = host.CpWritesEncodedInEncoder; + + _ = host.EnsureComputeEncoder(); + host.RecordEndOfPipe(new EndOfPipeWrite(EndOfPipeWriteKind.Write64, 1, WindowedLabel, 1)); + host.RecordCommandProcessorWrite(LaterLabel, BitConverter.GetBytes(2UL), "WRITE_DATA", causal: false); + host.RecordCommandProcessorWrite(WindowedLabel, BitConverter.GetBytes(4u), "WRITE_DATA", causal: false); + Assert.Equal(3, host.DeferredLabelCopyCount); + host.OrderAfterDeferredCopies(LaterLabel, 8, MetalRenderHost.LabelLandCause.BindRead); + Assert.False(host.ComputeEncoderOpen); + Assert.Equal(new long[] { 1, 0, 0, 0 }, host.TakeLabelBarrierKinds()); + + _ = host.EnsureComputeEncoder(); + host.RecordEndOfPipe(new EndOfPipeWrite(EndOfPipeWriteKind.Write32, 1, LaterLabel + 0x10, 3)); + host.OrderAfterDeferredCopies(LaterLabel + 0x10, 4); + Assert.False(host.ComputeEncoderOpen); + Assert.Equal(new long[] { 0, 1, 0, 0 }, host.TakeLabelBarrierKinds()); + Assert.Equal(2L, host.TakeLabelBarriers()); + Assert.Equal(folded, host.LabelsFolded); + Assert.Equal(inEncoder, host.CpWritesEncodedInEncoder); + + host.FlushCommandBuffer(); + WaitForGpu(host, host.LastWorkSerial); + WaitForCompletions(host); + Assert.Equal(4UL, rig.Backing.Read64(WindowedLabel)); + Assert.Equal(2UL, rig.Backing.Read64(LaterLabel)); + Assert.Equal(3u, rig.Backing.Read32(LaterLabel + 0x10)); + } } diff --git a/tests/SharpEmu.Libs.Tests/Gpu/GpuCommands/CommandStreamQueueTests.cs b/tests/SharpEmu.Libs.Tests/Gpu/GpuCommands/CommandStreamQueueTests.cs index 04b100d06..3433aaae6 100644 --- a/tests/SharpEmu.Libs.Tests/Gpu/GpuCommands/CommandStreamQueueTests.cs +++ b/tests/SharpEmu.Libs.Tests/Gpu/GpuCommands/CommandStreamQueueTests.cs @@ -486,6 +486,116 @@ public void AStoreIsCausalOnlyAfterAPendingReadOrABarrierOnItsQueue() host.CommandProcessorWriteCausal); } + // A wait on another queue's label still in the pending table is met by the recorded value: the store after it + // depends on work not yet done, so it is causal. + [Fact] + public void AWaitOnAnotherQueuesPendingLabelMarksTheNextStoreCausal() + { + var (host, queue) = NewQueue(); + host.DefersEndOfPipeLabels = true; + host.DefersCommandProcessorWrites = true; + host.PendingLabelTick = 5; + host.WriteDword(Label, 0); + Enqueue(host, queue, Graphics, 1, ReleaseMemoryInterrupt(Label, 1)); + Assert.Equal(SliceResult.Completed, queue.ProcessOne()); + + EnqueueCompute(host, queue, 0x20, Compute, 2, WriteLabel(Label + 0x10, 1), WaitEqual(Label, 1), WriteLabel(Label + 0x20, 2)); + Assert.Equal(SliceResult.Completed, queue.ProcessOne()); + Assert.Equal([(Label + 0x10, false), (Label + 0x20, true)], host.CommandProcessorWriteCausal); + } + + // A wait that parks and resumes once the label landed reads memory, not the pending table, and leaves the next store + // plain. That is sound because a label leaves the pending table only in NotifyCompletedGpuTick, after its command + // buffer completed, when every store before it is already published to the CPU: nothing the store could overtake + // is still owed. + [Fact] + public void AWaitThatParksAndResumesAfterTheLabelLandedLeavesTheNextStorePlain() + { + var (host, queue) = NewQueue(); + host.DefersEndOfPipeLabels = true; + host.DefersCommandProcessorWrites = true; + host.PendingLabelTick = 5; + host.WriteDword(Label, 0); + EnqueueCompute(host, queue, 0x20, Compute, 1, WaitEqual(Label, 1), WriteLabel(Label + 0x20, 2)); + Assert.Equal(SliceResult.BlockedWithoutProgress, queue.ProcessOne()); + + // The label is recorded, its command buffer completes, and it lands. + queue.GetInterpreter(0).PendingLabelRecorded!(Label, 4, 1); + queue.NotifyCompletedGpuTick(5); + host.WriteDword(Label, 1); + Assert.Equal(SliceResult.Completed, queue.ProcessOne()); + Assert.Equal([(Label + 0x20, false)], host.CommandProcessorWriteCausal); + } + + // A COND_EXEC whose flag the GPU still owes, taken as zero, skips packets on a value not yet landed: the store + // after it is causal. + [Fact] + public void AConditionalExecuteOverAnOwedFlagMarksTheNextStoreCausal() + { + var (host, queue) = NewQueue(); + host.DefersCommandProcessorWrites = true; + host.TakesOwedOperandsAsZero = true; + var flag = Label + 0x300; + host.WriteDword(flag, 0); + for (var read = 0; read < 32; read++) + { + ConditionalExecuteSpeculation.Observe(flag, 0); + } + + Assert.True(ConditionalExecuteSpeculation.ShouldTakeAsZero(flag)); + host.OwedOperandWrites.Add((flag, 4)); + var skipped = WriteLabel(Label + 0x30, 9); + Enqueue(host, queue, Graphics, 1, + WriteLabel(Label + 0x10, 1), + StreamRunner.Packet(PacketOpcode.ConditionalExecute, StreamRunner.Low(flag), StreamRunner.High(flag), 0, (uint)skipped.Length), + skipped, + WriteLabel(Label + 0x20, 2)); + Assert.Equal(SliceResult.Completed, queue.ProcessOne()); + Assert.Equal([(Label + 0x10, false), (Label + 0x20, true)], host.CommandProcessorWriteCausal); + } + + // A COPY_DATA from a label still pending copies a value not yet landed: the store after it is causal. + [Fact] + public void ACopyDataFromAPendingLabelMarksTheNextStoreCausal() + { + var (host, queue) = NewQueue(); + host.DefersEndOfPipeLabels = true; + host.DefersCommandProcessorWrites = true; + host.PendingLabelTick = 5; + host.WriteDword(Label, 0); + var copy = StreamRunner.Packet(PacketOpcode.CopyData, 2u | (2u << 8), + StreamRunner.Low(Label), StreamRunner.High(Label), StreamRunner.Low(Label + 0x40), StreamRunner.High(Label + 0x40)); + Enqueue(host, queue, Graphics, 1, + ReleaseMemoryInterrupt(Label, 1), WriteLabel(Label + 0x10, 1), copy, WriteLabel(Label + 0x20, 2)); + Assert.Equal(SliceResult.Completed, queue.ProcessOne()); + Assert.Equal((Label + 0x20, true), host.CommandProcessorWriteCausal[^1]); + Assert.DoesNotContain((Label + 0x40, false), host.CommandProcessorWriteCausal); + } + + // =verify: a read answered from bytes not yet landed, then a write its queue does not flag causal, is a suspect. + [Fact] + public void AnUnflaggedWriteAfterAPendingAnswerIsASuspectUnderVerify() + { + var (host, queue) = NewQueue(); + host.DefersCommandProcessorWrites = true; + var verify = GpuCommandInterpreter.CpWriteOrderVerify; + GpuCommandInterpreter.CpWriteOrderVerify = true; + try + { + Enqueue(host, queue, Graphics, 1, WriteLabel(Label + 0x10, 1)); + Assert.Equal(SliceResult.Completed, queue.ProcessOne()); + _ = GpuCommandInterpreter.TakeCpWriteOrderSuspects(); + GpuCommandInterpreter.NotePendingAnswer(Label, 4); + Enqueue(host, queue, Graphics, 2, WriteLabel(Label + 0x20, 2)); + Assert.Equal(SliceResult.Completed, queue.ProcessOne()); + Assert.True(GpuCommandInterpreter.TakeCpWriteOrderSuspects() >= 1); + } + finally + { + GpuCommandInterpreter.CpWriteOrderVerify = verify; + } + } + [Fact] public void AStoreAfterAWaitOnARecordedLabelIsRecordedBehindTheLabel() { diff --git a/tests/SharpEmu.Libs.Tests/Gpu/GpuCommands/CommandStreamTestSupport.cs b/tests/SharpEmu.Libs.Tests/Gpu/GpuCommands/CommandStreamTestSupport.cs index b3fe4fd2b..cc0bd7ee0 100644 --- a/tests/SharpEmu.Libs.Tests/Gpu/GpuCommands/CommandStreamTestSupport.cs +++ b/tests/SharpEmu.Libs.Tests/Gpu/GpuCommands/CommandStreamTestSupport.cs @@ -409,6 +409,13 @@ public bool CommitPendingOperandWrite(ulong address, ulong size) return true; } + /// Whether an owed operand a COND_EXEC may take as zero is taken (off: the read parks). + public bool TakesOwedOperandsAsZero { get; set; } + + public bool TryTakeOwedOperandAsZero(ulong address, ulong size) => + TakesOwedOperandsAsZero && + OwedOperandWrites.Exists(range => address < range.Address + range.Size && range.Address < address + size); + public List IndirectCpuReads { get; } = []; public void NoteIndirectArgumentsReadOnCpu(ulong address, ulong size) => IndirectCpuReads.Add(address); From 51d72f6007b1d9a8d97c125f386fcbb40f086f54 Mon Sep 17 00:00:00 2001 From: kuba Date: Sun, 15 Nov 2026 06:55:59 +0000 Subject: [PATCH 034/178] [Metal] Name a new image stale over all of it, not over an empty interval A new image was CPU-dirty with DirtyStart = DirtyEnd = 0, meaning "all of it". MarkCpuDirty(cause, start, end) on it widened with min/max to [0, end), so the first alias run marked on a new image shrank "whole" to a prefix: a run of at most half was then refreshed alone and the rest of the texture was never uploaded. The constructor now says [0, Size), and the two workarounds that normalised the empty interval (layer-subset copy, layered deferral) go. Test: MetalImageAliasTests.ANewImageOverAGpuWrittenAliasUploadsAllOfItself (failed before: texture tail zero from byte 4096). --- .../SharpEmu.Gpu.Metal/V2/MetalCachedImage.cs | 8 +++++- .../V2/MetalImageCache.AliasSubset.cs | 15 ++-------- .../V2/MetalImageCache.DeferredRefresh.cs | 5 +--- .../SharpEmu.Gpu.Metal/V2/MetalImageCache.cs | 5 ++-- .../MetalImageAliasTests.cs | 28 +++++++++++++++++++ 5 files changed, 41 insertions(+), 20 deletions(-) diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalCachedImage.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalCachedImage.cs index 546d68033..1424a243d 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalCachedImage.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalCachedImage.cs @@ -163,8 +163,14 @@ public MetalCachedImage(in ImageDescription description, in MetalTextureShape sh Texture = texture; ResidentEnd = description.Data.Size; // A newly created image starts with the guest's bytes as its contents, so the - // first use uploads unless the GPU takes ownership first. + // first use uploads unless the GPU takes ownership first. Stale over all of it, said + // as such: an empty interval would let the next run widen it to that run alone. _cpuDirty = !ImageDescription.IsEmptyRange(description.Data); + if (_cpuDirty) + { + DirtyEnd = description.Data.Size; + } + NoteContentChanged(); } diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.AliasSubset.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.AliasSubset.cs index a5c3d51ed..59a84aee9 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.AliasSubset.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.AliasSubset.cs @@ -71,7 +71,7 @@ private bool TryPublishAliasLayerSubset( var targetEnd = targetStart + layers * stride; var otherInside = sourceStart == 0 && sourceEnd == other.Description.Data.Size; if (sourceStart != otherStart || sourceEnd != otherEnd || - (other.IsCpuDirty && (other.DirtyEnd <= other.DirtyStart || (other.DirtyStart < sourceEnd && other.DirtyEnd > sourceStart))) || + (other.IsCpuDirty && other.DirtyStart < sourceEnd && other.DirtyEnd > sourceStart) || !CopyLeavesRunCurrent(image, targetStart, targetEnd) || // A write leaves the other image stale over the run and GPU-modified for the rest; one stale interval // cannot hold the run apart from one it already has, and widening it would cover bytes only its texture holds. @@ -99,13 +99,7 @@ private bool TryPublishAliasLayerSubset( EncodeAliasSubsetCheck(context, image, other, targetStart, sourceStart, sourceEnd - sourceStart); } - // The texture changed whether or not it was stale there; then it is current over the run. A new image is - // stale over an empty interval, which means all of it: that is named first, or the cut would clear it all. - if (image.IsCpuDirty && image.DirtyEnd <= image.DirtyStart) - { - image.MarkCpuDirty(image.DirtyCause, 0, image.Description.Data.Size); - } - + // The texture changed whether or not it was stale there; then it is current over the run. image.NoteContentChanged(); image.RefreshComplete(targetStart, targetEnd); if (takesGpuOwnership) @@ -132,7 +126,6 @@ private bool TryPublishAliasLayerSubset( // Whether marking [start, end) refreshed leaves none of it stale: one stale interval cannot lose its middle // (MetalCachedImage.RefreshComplete), and a refresh of what stays stale would put the guest's older bytes back // over the copy. - // An empty stale interval on a dirty image is a new one, stale over all of it. private static bool CopyLeavesRunCurrent(MetalCachedImage image, ulong start, ulong end) { if (!image.IsCpuDirty) @@ -140,9 +133,7 @@ private static bool CopyLeavesRunCurrent(MetalCachedImage image, ulong start, ul return true; } - var (dirtyStart, dirtyEnd) = image.DirtyEnd > image.DirtyStart - ? (image.DirtyStart, image.DirtyEnd) - : (0UL, image.Description.Data.Size); + var (dirtyStart, dirtyEnd) = (image.DirtyStart, image.DirtyEnd); return dirtyEnd <= start || dirtyStart >= end || start <= dirtyStart || end >= dirtyEnd; } diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.DeferredRefresh.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.DeferredRefresh.cs index 2296fa4d7..1957f5bf4 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.DeferredRefresh.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.DeferredRefresh.cs @@ -346,10 +346,7 @@ private bool TryLeaveOtherLayersStale( return false; } - // An empty interval on a dirty image is a new one, stale over all of it. - var (dirtyStart, dirtyEnd) = image.DirtyEnd > image.DirtyStart - ? (image.DirtyStart, image.DirtyEnd) - : (0UL, image.Description.Data.Size); + var (dirtyStart, dirtyEnd) = (image.DirtyStart, image.DirtyEnd); var (start, end) = (dirtyStart, dirtyEnd); var overlaps = viewStart < dirtyEnd && viewEnd > dirtyStart; if (overlaps) diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.cs index 3e7454054..c2bf65731 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.cs @@ -2780,11 +2780,10 @@ private void RefreshFromGuestCore(MetalCachedImage image) ref readonly var description = ref image.Description; // A texture held from its BASE_LEVEL reads only the coarser levels' bytes; guest - // memory changing anywhere else changes nothing it holds. (An empty interval is a - // new image, dirty over all of it.) + // memory changing anywhere else changes nothing it holds. var residentStart = image.ResidentStart; var residentEnd = image.ResidentEnd; - if (image.FirstLevel != 0 && image.DirtyEnd > image.DirtyStart && + if (image.FirstLevel != 0 && (image.DirtyEnd <= residentStart || image.DirtyStart >= residentEnd)) { image.RefreshComplete(); diff --git a/tests/SharpEmu.Gpu.Metal.Tests/MetalImageAliasTests.cs b/tests/SharpEmu.Gpu.Metal.Tests/MetalImageAliasTests.cs index 2489dfd2c..1bea9edc2 100644 --- a/tests/SharpEmu.Gpu.Metal.Tests/MetalImageAliasTests.cs +++ b/tests/SharpEmu.Gpu.Metal.Tests/MetalImageAliasTests.cs @@ -292,6 +292,34 @@ public void ATailAliasRefreshesOnlyItsRun() Assert.Equal((long)(LargeSize - SmallSize), partial.UploadBytes); } + // A new image is stale over all of it. Its first use over bytes a GPU-written alias owns marks the run the two + // share stale on top of that, and the run is at most half of it: the whole image must still be uploaded, not + // just the run (an empty interval meaning "all of it" used to widen to [0, run end) and drop the tail). + [Fact] + public void ANewImageOverAGpuWrittenAliasUploadsAllOfItself() + { + if (!RequireDevice()) return; + using var rig = new Rig(Device.Value); + var written = MetalTileOracle.Pattern((int)SmallSize, 0x5A); + rig.WriteGuest(ImageAddress, written); + var small = rig.Cache.GetImage( + rig.Acquire(Rig.Request(ImageAddress, LargeSide, AliasRows, ImageRole.ColorTarget))); + Assert.True(small.IsGpuModified); + rig.Harness.Submit(); + rig.Harness.Begin(); + var stale = MetalTileOracle.Pattern((int)LargeSize, 0xC3); + rig.WriteGuest(ImageAddress, stale); + + var large = rig.Cache.GetImage(rig.Acquire(ImageAddress, LargeSide, ImageRole.Texture)); + rig.Harness.Submit(); + rig.Harness.Begin(); + + var expected = stale.ToArray(); + written.CopyTo(expected, 0); + Assert.False(large.IsCpuDirty); + Assert.Equal(expected, ReadTexture(rig, large)); + } + // A read through an alias whose rows do not line up with the GPU-written image's // (here a narrower pitch over the same bytes) is served nothing: the image is not // retiled out to guest memory and stays GPU-modified, and the reader is not marked From df5f4b2d3ee5205ab94f5184c5a25d4ff19fd514 Mon Sep 17 00:00:00 2001 From: kuba Date: Sun, 15 Nov 2026 06:59:05 +0000 Subject: [PATCH 035/178] [Metal] Check a subset copy's stale run reloads exactly; forget a publication the copy overwrote Write path: a layer-subset copy leaves the other image GPU-modified and stale over the run, which only TryRefreshDirtyRun reloads. With sub-range transfers or layered deferral off, or a covering run that widens or cannot be read in place, that reload was refused and the image kept its older texels over a run of up to 8/9 of it. The copy now asks CanReloadRunExactly first and refuses (alias_transition_refused subset-stale-run-inexact). Read path: a copy into a GPU-written image that had published a run left the published interval claiming guest memory holds the image's bytes there, while the texture had just been given the source's newer ones. ForgetPublished trims it over the copied run. TryNarrowReloadRun and TryRefreshDirtyRun now share NarrowRefreshPastHalf. Tests: ASubsetWriteLeavesTheArrayStaleOnlyOverARunItReloadsExactly, ACopyIntoAPublishedRunForgetsThePublication. --- .../SharpEmu.Gpu.Metal/V2/MetalCachedImage.cs | 37 ++++++++ .../V2/MetalImageCache.AliasSubset.cs | 20 +++- .../V2/MetalImageCache.AliasTransitions.cs | 3 + .../V2/MetalImageCache.ConsumerRuns.cs | 7 +- .../SharpEmu.Gpu.Metal/V2/MetalImageCache.cs | 27 +++++- .../MetalImageAliasTests.Subset.cs | 91 ++++++++++++++++++- 6 files changed, 174 insertions(+), 11 deletions(-) diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalCachedImage.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalCachedImage.cs index 1424a243d..40f8474b8 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalCachedImage.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalCachedImage.cs @@ -818,6 +818,43 @@ public void MarkPublished(ulong start, ulong end) public bool IsPublished(ulong start, ulong end) => PublishedEnd > PublishedStart && start >= PublishedStart && end <= PublishedEnd; + /// + /// The texture got bytes over [start, end) guest memory does not hold (a copy from an alias that still + /// owes them): what was published there is not this image's any more. A cut from the middle keeps the longer + /// side; forgetting a run only costs publishing it again. + /// + public void ForgetPublished(ulong start, ulong end) + { + if (PublishedEnd <= PublishedStart || end <= PublishedStart || start >= PublishedEnd) + { + return; + } + + if (start <= PublishedStart && end >= PublishedEnd) + { + PublishedStart = PublishedEnd = 0; + } + else if (start <= PublishedStart) + { + PublishedStart = end; + } + else if (end >= PublishedEnd) + { + PublishedEnd = start; + } + else if (start - PublishedStart >= PublishedEnd - end) + { + PublishedEnd = start; + } + else + { + PublishedStart = end; + } + + BindingVersion++; + Epochs?.NoteBindingChanged(); + } + public void ClearGpuModified() { var wasModified = _gpuModified; diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.AliasSubset.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.AliasSubset.cs index 59a84aee9..dcd9ac636 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.AliasSubset.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.AliasSubset.cs @@ -81,6 +81,21 @@ private bool TryPublishAliasLayerSubset( return false; } + if (takesGpuOwnership && !otherInside) + { + // The other image stays GPU-modified and stale over the run, and only TryRefreshDirtyRun reloads a stale run + // of such an image (a whole refresh would replace bytes only its texture holds). Unless that reload is + // certain to make exactly this run, its next use would keep its older texels there (alias_run_refresh_refused). + var (staleStart, staleEnd) = other.IsCpuDirty + ? (Math.Min(other.DirtyStart, sourceStart), Math.Max(other.DirtyEnd, sourceEnd)) + : (sourceStart, sourceEnd); + if (!CanReloadRunExactly(other, staleStart, staleEnd)) + { + RefuseAliasTransition("subset-stale-run-inexact"); + return false; + } + } + EnsureSparseBacked(image); var context = _owner.BeginTransfer(MetalTransferCause.Writeback, other.Texture, image.Texture); if (!_transfer.TryEncodeLayerSubsetCopy( @@ -99,9 +114,12 @@ private bool TryPublishAliasLayerSubset( EncodeAliasSubsetCheck(context, image, other, targetStart, sourceStart, sourceEnd - sourceStart); } - // The texture changed whether or not it was stale there; then it is current over the run. + // The texture changed whether or not it was stale there; then it is current over the run. It now holds the + // other image's bytes there, which guest memory does not (the other still owes them): a run this image had + // published is no longer its bytes in guest memory, and would let a later hand-over or consumer skip them. image.NoteContentChanged(); image.RefreshComplete(targetStart, targetEnd); + image.ForgetPublished(targetStart, targetEnd); if (takesGpuOwnership) { if (otherInside) diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.AliasTransitions.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.AliasTransitions.cs index e0bd50077..83c74d7cf 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.AliasTransitions.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.AliasTransitions.cs @@ -24,6 +24,9 @@ internal sealed partial class MetalImageCache private long _aliasMovedWritebackBytes, _aliasMovedBlitBytes; private long _aliasRunRefreshRefused; + /// Test hook: GPU-written images that kept older texels over a stale run they could not reload alone. + internal long AliasRunRefreshRefused => Interlocked.Read(ref _aliasRunRefreshRefused); + private void NoteAliasRoundTrip(bool whole, ulong sharedSize) { _aliasRoundTrip++; diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.ConsumerRuns.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.ConsumerRuns.cs index 2240f0672..084af4add 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.ConsumerRuns.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.ConsumerRuns.cs @@ -191,13 +191,16 @@ private bool CanKeepGpuOwnership(MetalCachedImage image, ulong start, ulong end) } // The run TryRefreshDirtyRun reloads for a stale interval, when it reloads just that run: - // the same conditions, in the same order, so the answer here is the answer there. + // the same conditions, in the same order, so the answer here is the answer there. The + // image is run-shaped (IsRunShaped: no stencil, the whole chain resident), so the half + // rule there, over the resident bytes, is this one over all of them. private bool TryNarrowReloadRun(MetalCachedImage image, ulong staleStart, ulong staleEnd, out ulong runStart, out ulong runEnd) { runStart = runEnd = 0; ref readonly var description = ref image.Description; - if (staleEnd <= staleStart || staleEnd - staleStart > description.Data.Size / 2 || + if (staleEnd <= staleStart || + (staleEnd - staleStart > description.Data.Size / 2 && !NarrowRefreshPastHalf(image)) || !TryCoveringRun(in description, staleStart, staleEnd, out runStart, out runEnd)) { return false; diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.cs index c2bf65731..f43f104bc 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.cs @@ -2865,13 +2865,9 @@ private bool TryRefreshDirtyRun(MetalCachedImage image) var residentEnd = image.ResidentEnd; var dirtyStart = Math.Max(image.DirtyStart, residentStart); var dirtyEnd = Math.Min(image.DirtyEnd, residentEnd); - // Past half the run still goes alone for a GPU-written array (layered deferral leaves one stale over the - // layers its passes have not overwritten yet): the whole refresh is no option there - it would replace the - // layers only the texture holds - so the half rule, a cost rule, would only keep the stale layers. - var pastHalfAllowed = LayerDeferEnabled && image.IsGpuModified && description.IsLayered; if (!SubRangeTransfersEnabled || description.HasStencil || dirtyEnd <= dirtyStart || - (dirtyEnd - dirtyStart > (residentEnd - residentStart) / 2 && !pastHalfAllowed)) + (dirtyEnd - dirtyStart > (residentEnd - residentStart) / 2 && !NarrowRefreshPastHalf(image))) { return false; } @@ -2924,6 +2920,27 @@ private bool TryRefreshDirtyRun(MetalCachedImage image) return true; } + // Past half a stale run still goes alone for a GPU-written array (layered deferral leaves one stale over the + // layers its passes have not overwritten yet): the whole refresh is no option there - it would replace the + // layers only the texture holds - so the half rule, a cost rule, would only keep the stale layers. + // TryRefreshDirtyRun and TryNarrowReloadRun both ask this, so they give one answer. + private bool NarrowRefreshPastHalf(MetalCachedImage image) => + LayerDeferEnabled && image.IsGpuModified && image.Description.IsLayered; + + // Whether TryRefreshDirtyRun, given [start, end) as the image's whole stale interval, reloads exactly that run + // and nothing past it: sub-range transfers on, the half rule met, a covering run that does not widen, and guest + // bytes it reads in place. A GPU-written image left stale over a run that fails this would keep its older texels. + private bool CanReloadRunExactly(MetalCachedImage image, ulong start, ulong end) + { + ref readonly var description = ref image.Description; + var resident = image.ResidentEnd - image.ResidentStart; + return end > start && SubRangeTransfersEnabled && !description.HasStencil && image.FirstLevel == 0 && + (end - start <= resident / 2 || NarrowRefreshPastHalf(image)) && + TryCoveringRun(in description, start, end, out var runStart, out var runEnd) && + runStart == start && runEnd == end && + _guestMemory.TryResolveInPlace(description.Data.Address + start, end - start, out _); + } + // The run a restricted transfer may be given for a dirty range. The plan's own // alignments move *into* a range - a start forward, an end back - because they exist // to cut an image into runs that together cover it, where a byte one run drops the diff --git a/tests/SharpEmu.Gpu.Metal.Tests/MetalImageAliasTests.Subset.cs b/tests/SharpEmu.Gpu.Metal.Tests/MetalImageAliasTests.Subset.cs index bf7e09361..353fe7df2 100644 --- a/tests/SharpEmu.Gpu.Metal.Tests/MetalImageAliasTests.Subset.cs +++ b/tests/SharpEmu.Gpu.Metal.Tests/MetalImageAliasTests.Subset.cs @@ -58,16 +58,19 @@ private static byte[] ReadLayers(Rig rig, MetalCachedImage image) return rig.Harness.Read(buffer, 0, size); } - private sealed record SubsetOutcome(byte[] First, byte[] Second, byte[] Guest, long Copies, long Writebacks, string Text); + private sealed record SubsetOutcome( + byte[] First, byte[] Second, byte[] Guest, long Copies, long Writebacks, string Text, long RefreshRefused = 0); // The first array is written by the GPU (its texture holds `written`, guest memory something else), then the // second is acquired with the given role. Then both are read back and every GPU write is flushed. private static SubsetOutcome RunSubset( - bool subset, ImageRequest first, ImageRequest second, ImageRole secondRole, bool verify = false) + bool subset, ImageRequest first, ImageRequest second, ImageRole secondRole, bool verify = false, + bool layerDefer = true) { using var rig = new Rig(Device.Value); rig.Cache.AliasSubsetDeviceEnabled = subset; rig.Cache.AliasSubsetVerify = verify; + rig.Cache.LayerDeferEnabled = layerDefer; var start = Math.Min(first.Description.Data.Address, second.Description.Data.Address); var end = Math.Max(first.Description.Data.End, second.Description.Data.End); var span = end - start; @@ -105,7 +108,8 @@ private static SubsetOutcome RunSubset( rig.Cache.FlushGpuWrites(start, span, MetalWritebackCause.HostRead); rig.Harness.Submit(); rig.Harness.Begin(); - return new SubsetOutcome(firstBytes, secondBytes, rig.ReadGuest(start, span), copies, writebacks, text); + return new SubsetOutcome( + firstBytes, secondBytes, rig.ReadGuest(start, span), copies, writebacks, text, rig.Cache.AliasRunRefreshRefused); } private static void AssertSameOutcome(SubsetOutcome on, SubsetOutcome off) @@ -259,4 +263,85 @@ public void ASourceStaleInsideTheSubsetIsRefused() Assert.Equal(outcomes[1].Second, outcomes[0].Second); Assert.Equal(outcomes[1].Guest, outcomes[0].Guest); } + + // A write through 8 of 9 layers (Demon's Souls' 64 of 72) leaves the 9-layer array GPU-modified and stale over + // the 8 - past half, which with layered deferral off only a whole refresh would reload, and that is no option for a + // GPU-written image. The copy is refused unless that reload is certain; nothing keeps older texels + // (alias_run_refresh_refused), and the bytes are those of the path with every switch off. + [Theory] + [InlineData(GuestTileMode.RenderTarget)] + [InlineData(GuestTileMode.Standard64KB)] + public void ASubsetWriteLeavesTheArrayStaleOnlyOverARunItReloadsExactly(GuestTileMode tile) + { + if (!RequireDevice()) return; + var first = SubsetArray(ImageAddress, 9, tile, ImageRole.StorageImage); + var second = SubsetArray(ImageAddress, 8, tile, ImageRole.StorageImage); + var on = RunSubset(subset: true, first, second, ImageRole.StorageImage, layerDefer: false); + var off = RunSubset(subset: false, first, second, ImageRole.StorageImage, layerDefer: false); + output.WriteLine($"{tile}: on copies={on.Copies} refused={on.RefreshRefused}\n on: {on.Text}\n off: {off.Text}"); + Assert.Equal(0, on.RefreshRefused); + Assert.Equal(0, off.RefreshRefused); + AssertSameOutcome(on, off); + } + + // A copy into an array the GPU wrote, which had published a run (a CPU read of its first layer): the texture now + // holds the source's newer bytes there, which guest memory does not, so the run is not published any more. Then + // everything is read back and flushed: the same bytes as the round trip. + [Fact] + public void ACopyIntoAPublishedRunForgetsThePublication() + { + if (!RequireDevice()) return; + var outcomes = new List<(byte[] First, byte[] Guest, long Copies, bool Published)>(); + foreach (var subset in new[] { true, false }) + { + using var rig = new Rig(Device.Value); + rig.Cache.AliasSubsetDeviceEnabled = subset; + var tile = GuestTileMode.Standard64KB; + var first = SubsetArray(ImageAddress, 9, tile, ImageRole.StorageImage); + var size = first.Description.Data.Size; + var layer = LayerBytes(tile); + rig.WriteGuest(ImageAddress, MetalTileOracle.Pattern((int)size, 0x5A)); + var firstImage = rig.Cache.GetImage(rig.Acquire(first)); + rig.Harness.Submit(); + rig.Harness.Begin(); + rig.WriteGuest(ImageAddress, MetalTileOracle.Pattern((int)size, 0xC3)); + rig.Cache.FlushGpuWrites(ImageAddress, layer, MetalWritebackCause.HostRead); + rig.Harness.Submit(); + rig.Harness.Begin(); + Assert.True(firstImage.IsGpuModified); + Assert.True(firstImage.IsPublished(0, layer)); + + // The 8-layer array takes its layers and its texture is then written, as a dispatch into it would. + var second = rig.Cache.GetImage(rig.Acquire(SubsetArray(ImageAddress, 8, tile, ImageRole.StorageImage))); + Assert.True(second.IsGpuModified); + var drawn = MetalTileOracle.Pattern((int)second.Description.Data.Size, 0x77); + Assert.True(rig.Harness.Transfer.EncodeGuestToTexture( + rig.Harness, second.Description, new SubresourceRange(0, 1, 0, second.Description.TransferLayers), + new MetalGuestRange(rig.Harness.Buffer(drawn), 0, (ulong)drawn.Length, 0), default, second.Texture, + 0, (ulong)drawn.Length)); + rig.Harness.Submit(); + rig.Harness.Begin(); + + var copies = rig.Cache.AliasSubsetCounters.Copies; + rig.Acquire(first with { Role = ImageRole.Texture }); + rig.Harness.Submit(); + rig.Harness.Begin(); + copies = rig.Cache.AliasSubsetCounters.Copies - copies; + var published = firstImage.IsGpuModified && firstImage.IsPublished(0, layer); + var firstBytes = ReadLayers(rig, firstImage); + rig.Cache.FlushGpuWrites(ImageAddress, size, MetalWritebackCause.HostRead); + rig.Harness.Submit(); + rig.Harness.Begin(); + outcomes.Add((firstBytes, rig.ReadGuest(ImageAddress, size), copies, published)); + Assert.Equal(0, rig.Cache.AliasRunRefreshRefused); + } + + output.WriteLine($"on: copies={outcomes[0].Copies} published={outcomes[0].Published}; " + + $"off: copies={outcomes[1].Copies} published={outcomes[1].Published}"); + Assert.True(outcomes[0].Copies >= 1); + // Guest memory holds layer 0 as the first array had it, not as the copy left its texture. + Assert.False(outcomes[0].Published); + Assert.Equal(outcomes[1].First, outcomes[0].First); + Assert.Equal(outcomes[1].Guest, outcomes[0].Guest); + } } From e77c48de436e2a4d3c37bf9c33b027611275274f Mon Sep 17 00:00:00 2001 From: kuba Date: Sun, 15 Nov 2026 07:13:08 +0000 Subject: [PATCH 036/178] [Metal] Hold several stale and published runs per image; reload a run past half alone Plan Step 3 (SHARPEMU_METAL_V2_ALIAS_RUN_SETS, on; =0 is the single interval as before). A GPU-written image holds up to four stale runs and four published runs apart instead of one interval each: - an alias hand-over is declined only when the run set is full (RunSetFull, replacing OtherDirtyOutsideRun), and a run past half of the image is no longer a decline: TryRefreshDirtyRun reloads each run alone for any GPU-written image (NarrowRefreshPastHalf), planning every run before encoding any; - a full set merges only by publishing first (the caller's whole writeback, or the refresh-first in MarkAliasRunDirty), counted; an image-level merge over texture-only bytes is counted as unpublished and warned about (must stay 0); - RefreshComplete cuts a run from the middle into two while the set has room; layered deferral keeps both and re-marks every run after MarkGpuModified; - RefreshBeforeWriteback, consumer runs (GuestHoldsImageBytes over published and stale runs), the subset copy and TryWriteBackRun ask the runs, not the hull. Counters: alias_runs=[sets_max,merged,refresh_over_half,unpublished]. Layer-subset copy (Step 1) fixes found by the run-set tests: the copy is refused when an alias this sync has not reached yet still owes bytes of the reader (its turn re-marks the reader stale over the copy), and when what the copy leaves stale on the reader would be reloaded whole (past half on an image the GPU did not write), which put guest bytes over the copy. Both are counted (alias_transition_refused subset-later-owner, subset-rest-reload). Tests: MetalImageAliasTests.RunSets (two disjoint aliases, a 62.5% run, a set overflowing at five, a writer through the old alias, a CPU read after narrow hand-overs, a subset copy over a source stale apart from the run), each run sets on vs off bit for bit; ASourceStaleInsideTheSubsetIsRefused over layers 0 and 2 with run sets on and off; LayerClearsOfADepthArray: middle-first orders now upload nothing (0 uploads, 8 layers dropped) and match the switch-off bytes. --- .../SharpEmu.Gpu.Metal/V2/MetalCachedImage.cs | 403 +++++++++++++++--- .../V2/MetalImageCache.AliasSubset.cs | 101 ++++- .../V2/MetalImageCache.AliasTrace.cs | 4 +- .../V2/MetalImageCache.AliasTransitions.cs | 2 +- .../V2/MetalImageCache.ConsumerRuns.cs | 40 +- .../V2/MetalImageCache.DeferredRefresh.cs | 81 ++-- .../V2/MetalImageCache.RunSets.cs | 111 +++++ .../SharpEmu.Gpu.Metal/V2/MetalImageCache.cs | 136 ++++-- .../MetalDeferredRefreshTests.cs | 8 +- .../MetalImageAliasTests.RunSets.cs | 204 +++++++++ .../MetalImageAliasTests.Subset.cs | 20 +- .../MetalImageAliasTests.cs | 8 +- 12 files changed, 914 insertions(+), 204 deletions(-) create mode 100644 src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.RunSets.cs create mode 100644 tests/SharpEmu.Gpu.Metal.Tests/MetalImageAliasTests.RunSets.cs diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalCachedImage.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalCachedImage.cs index 40f8474b8..244705ed5 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalCachedImage.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalCachedImage.cs @@ -168,7 +168,8 @@ public MetalCachedImage(in ImageDescription description, in MetalTextureShape sh _cpuDirty = !ImageDescription.IsEmptyRange(description.Data); if (_cpuDirty) { - DirtyEnd = description.Data.Size; + _stale[0] = (0, description.Data.Size); + _staleCount = 1; } NoteContentChanged(); @@ -460,8 +461,7 @@ public void MarkWindowLinearView() { _windowLinearView = true; _cpuDirty = false; - DirtyStart = 0; - DirtyEnd = 0; + _staleCount = 0; NoteContentChanged(); } @@ -611,15 +611,42 @@ private bool IsSrgbTwin(ulong viewFormat) => // Why the next upload will happen; purely diagnostic. public MetalImageDirtyCause DirtyCause { get; private set; } = MetalImageDirtyCause.Created; + /// The most stale runs, and the most published runs, an image holds apart with run sets on. + public const int MaxRuns = 4; + + /// + /// How many stale runs and how many published runs this image holds apart. One - a single + /// merged interval each, as before - unless the cache admitted it with run sets on + /// (SHARPEMU_METAL_V2_ALIAS_RUN_SETS), when it is . + /// + public int RunCapacity { get; set; } = 1; + + /// Where the cache counts what run sets do; null outside a cache. + public MetalRunSetStats? RunStats; + + // Sorted, and none overlaps or touches the next. + private readonly (ulong Start, ulong End)[] _stale = new (ulong, ulong)[MaxRuns]; + private int _staleCount; + private readonly (ulong Start, ulong End)[] _published = new (ulong, ulong)[MaxRuns]; + private int _publishedCount; + /// /// The guest bytes of this image, as offsets into it, that guest memory holds a newer - /// version of than the texture does. One merged interval rather than a set: a second - /// range that does not touch the first widens it to cover both, which costs an upload - /// of the bytes between them and never an upload too few. + /// version of than the texture does. With one run (run sets off) a second range that + /// does not touch the first widens it to cover both, which costs an upload of the bytes + /// between them and never an upload too few - for an image the texture owns no byte of. + /// A GPU-written image holds bytes only its texture has between two runs, so its runs are + /// kept apart, up to . /// - public ulong DirtyStart { get; private set; } + public ReadOnlySpan<(ulong Start, ulong End)> StaleRuns => _stale.AsSpan(0, _staleCount); + + public int StaleRunCount => _staleCount; + + /// Where the first stale run starts: with one run, the stale interval. + public ulong DirtyStart => _staleCount == 0 ? 0 : _stale[0].Start; - public ulong DirtyEnd { get; private set; } + /// Where the last stale run ends. + public ulong DirtyEnd => _staleCount == 0 ? 0 : _stale[_staleCount - 1].End; /// /// The bytes already published to guest memory since this image was last written by @@ -627,9 +654,166 @@ private bool IsSrgbTwin(ulong viewFormat) => /// the image stays GPU-modified and this is what keeps the next alias from publishing /// the same bytes again. /// - public ulong PublishedStart { get; private set; } + public ReadOnlySpan<(ulong Start, ulong End)> PublishedRuns => _published.AsSpan(0, _publishedCount); + + // Adds [start, end) to sorted runs that neither overlap nor touch, absorbing every run it overlaps or touches, + // into `into` (room for one more than the runs), and returns how many runs that makes. + internal static int UnionRun( + ReadOnlySpan<(ulong Start, ulong End)> runs, ulong start, ulong end, Span<(ulong Start, ulong End)> into) + { + var count = 0; + var placed = false; + foreach (var run in runs) + { + if (run.End < start) + { + into[count++] = run; + } + else if (run.Start > end) + { + if (!placed) + { + into[count++] = (start, end); + placed = true; + } + + into[count++] = run; + } + else + { + start = Math.Min(start, run.Start); + end = Math.Max(end, run.End); + } + } + + if (!placed) + { + into[count++] = (start, end); + } + + return count; + } + + // Removes [start, end) from sorted runs into `into` (room for one more than the runs: a cut from the middle of + // one makes two), and returns how many runs are left. + internal static int SubtractRun( + ReadOnlySpan<(ulong Start, ulong End)> runs, ulong start, ulong end, Span<(ulong Start, ulong End)> into) + { + var count = 0; + foreach (var run in runs) + { + if (run.End <= start || run.Start >= end) + { + into[count++] = run; + continue; + } + + if (run.Start < start) + { + into[count++] = (run.Start, start); + } + + if (run.End > end) + { + into[count++] = (end, run.End); + } + } + + return count; + } - public ulong PublishedEnd { get; private set; } + private static bool Contains(ReadOnlySpan<(ulong Start, ulong End)> runs, ulong start, ulong end) + { + foreach (var run in runs) + { + if (run.Start <= start && end <= run.End) + { + return true; + } + } + + return false; + } + + /// True when the texture is stale over all of [start, end): one run holds it. + public bool IsStaleOver(ulong start, ulong end) => _cpuDirty && Contains(StaleRuns, start, end); + + /// True when the texture is stale over any byte of [start, end). + public bool StaleOverlaps(ulong start, ulong end) + { + foreach (var run in StaleRuns) + { + if (run.Start < end && run.End > start) + { + return true; + } + } + + return false; + } + + /// + /// Whether [start, end) can be marked stale without widening a run over bytes between + /// two runs: the runs it does not overlap or touch, and it, fit in . + /// + public bool CanAddStaleRun(ulong start, ulong end) + { + if (!_cpuDirty) + { + return true; + } + + var apart = 0; + foreach (var run in StaleRuns) + { + if (run.End < start || run.Start > end) + { + apart++; + } + } + + return apart + 1 <= RunCapacity; + } + + /// The run [start, end) becomes once marked stale: it and every run it overlaps or touches. + public (ulong Start, ulong End) MergedStaleRun(ulong start, ulong end) + { + foreach (var run in StaleRuns) + { + if (run.End >= start && run.Start <= end) + { + start = Math.Min(start, run.Start); + end = Math.Max(end, run.End); + } + } + + return (start, end); + } + + /// + /// Whether marking [start, end) current leaves none of it stale. A cut from the middle + /// of a run makes two; with one run (or a full set) the run is kept whole instead + /// (), so bytes that are not guest memory's must not + /// be put there. + /// + public bool CanCutStale(ulong start, ulong end) + { + foreach (var run in StaleRuns) + { + if (run.Start < start && run.End > end) + { + return _staleCount < RunCapacity; + } + } + + return true; + } + + /// Where the first published run starts. + public ulong PublishedStart => _publishedCount == 0 ? 0 : _published[0].Start; + + /// Where the last published run ends. + public ulong PublishedEnd => _publishedCount == 0 ? 0 : _published[_publishedCount - 1].End; public void MarkCpuDirty(MetalImageDirtyCause cause = MetalImageDirtyCause.Invalidated) => MarkCpuDirty(cause, 0, Description.Data.Size); @@ -655,21 +839,70 @@ public void MarkCpuDirty(MetalImageDirtyCause cause, ulong start, ulong end) if (!_cpuDirty) { DirtyCause = cause; - DirtyStart = start; - DirtyEnd = end; + _stale[0] = (start, end); + _staleCount = 1; _cpuDirty = true; BindingVersion++; Epochs?.NoteBindingChanged(); return; } - if (start < DirtyStart || end > DirtyEnd) + if (Contains(StaleRuns, start, end)) { - DirtyStart = Math.Min(DirtyStart, start); - DirtyEnd = Math.Max(DirtyEnd, end); - BindingVersion++; - Epochs?.NoteBindingChanged(); + return; + } + + if (RunCapacity <= 1) + { + _stale[0] = (Math.Min(_stale[0].Start, start), Math.Max(_stale[0].End, end)); + } + else + { + Span<(ulong Start, ulong End)> runs = stackalloc (ulong, ulong)[MaxRuns + 1]; + var count = UnionRun(StaleRuns, start, end, runs); + if (count > RunCapacity) + { + count = MergeClosest(runs[..count]); + } + + runs[..count].CopyTo(_stale); + _staleCount = count; + RunStats?.NoteSets(count); + } + + BindingVersion++; + Epochs?.NoteBindingChanged(); + } + + // One run too many: the two runs with the least between them become one. The bytes between them are marked + // stale too, which is exact only while guest memory holds them for this image - always, when the texture owns + // none of its bytes; for a GPU-written image the cache never lets it come to this (CanAddStaleRun), and if it + // does anyway it is counted and warned about, since a refresh of the merged run replaces bytes only the + // texture holds. + private int MergeClosest(Span<(ulong Start, ulong End)> runs) + { + var closest = 0; + for (var index = 1; index + 1 < runs.Length; index++) + { + if (runs[index + 1].Start - runs[index].End < runs[closest + 1].Start - runs[closest].End) + { + closest = index; + } + } + + runs[closest] = (runs[closest].Start, runs[closest + 1].End); + runs[(closest + 2)..].CopyTo(runs[(closest + 1)..]); + RunStats?.NoteMerged(unpublished: _gpuModified); + if (_gpuModified) + { + MetalV2Diagnostics.WarnOnce( + $"run-set-unpublished-merge:{Description.PixelFormat}", + "A GPU-written image's stale runs were merged over bytes only its texture holds; its next refresh " + + $"replaces them with older guest bytes: {Description.PixelFormat} {Description.Extent.Width}x" + + $"{Description.Extent.Height} 0x{Description.Data.Address:X16}+0x{Description.Data.Size:X}."); } + + return runs.Length - 1; } /// The whole image is in the texture again. @@ -678,8 +911,7 @@ public void RefreshComplete() NoteContentChanged(); var wasDirty = _cpuDirty; _cpuDirty = false; - DirtyStart = 0; - DirtyEnd = 0; + _staleCount = 0; if (wasDirty) { BindingVersion++; @@ -702,27 +934,49 @@ public void RefreshComplete(ulong start, ulong end) return; } + if (RunCapacity > 1) + { + // A cut from the middle of a run makes two of it while the set has room; a full + // set keeps that run whole, as one interval does (CanCutStale). + Span<(ulong Start, ulong End)> runs = stackalloc (ulong, ulong)[MaxRuns + 1]; + var count = SubtractRun(StaleRuns, start, end, runs); + if (count > RunCapacity || + (count == _staleCount && runs[..count].SequenceEqual(StaleRuns))) + { + return; + } + + runs[..count].CopyTo(_stale); + _staleCount = count; + RunStats?.NoteSets(count); + BindingVersion++; + Epochs?.NoteBindingChanged(); + return; + } + // A cut from the front or the back narrows the interval; a cut from the middle // would split it, and one interval cannot hold two, so it keeps the wider half. - if (start <= DirtyStart && end > DirtyStart) + var (dirtyStart, dirtyEnd) = _stale[0]; + if (start <= dirtyStart && end > dirtyStart) { - DirtyStart = end; + dirtyStart = end; } - else if (end >= DirtyEnd && start < DirtyEnd) + else if (end >= dirtyEnd && start < dirtyEnd) { - DirtyEnd = start; + dirtyEnd = start; } else { return; } - if (DirtyEnd <= DirtyStart) + if (dirtyEnd <= dirtyStart) { RefreshComplete(); return; } + _stale[0] = (dirtyStart, dirtyEnd); BindingVersion++; Epochs?.NoteBindingChanged(); } @@ -753,15 +1007,15 @@ public void MarkGpuModified(bool depthPlaneChanged = true) var wasModified = _gpuModified; var wasDirty = _cpuDirty; - var wasPublished = PublishedEnd > PublishedStart; + var wasPublished = _publishedCount != 0; // Claimed before the image is GPU-modified: the guest process never sees it so unclaimed. + // Every stale run goes: a caller whose write leaves some of them stale marks those again + // after this (MetalImageCache.CompleteDeferredLocked). ClaimPendingWriteback(); _gpuModified = true; _cpuDirty = false; - DirtyStart = 0; - DirtyEnd = 0; - PublishedStart = 0; - PublishedEnd = 0; + _staleCount = 0; + _publishedCount = 0; GpuWriteSequence = Interlocked.Increment(ref _gpuWriteCounter); if (!wasModified) { @@ -779,78 +1033,92 @@ public void MarkGpuModified(bool depthPlaneChanged = true) public void MarkPublished(ulong start, ulong end) { end = Math.Min(end, Description.Data.Size); - if (end <= start) + if (end <= start || Contains(PublishedRuns, start, end)) { return; } - var (wasStart, wasEnd) = (PublishedStart, PublishedEnd); - if (PublishedEnd <= PublishedStart) + if (RunCapacity > 1) + { + // Runs with unpublished bytes between them stay apart: widening one over the gap + // would claim bytes guest memory never got. A set one too full forgets its shortest + // run, which only costs publishing it again. + Span<(ulong Start, ulong End)> runs = stackalloc (ulong, ulong)[MaxRuns + 1]; + var count = UnionRun(PublishedRuns, start, end, runs); + if (count > RunCapacity) + { + count = DropShortest(runs[..count]); + } + + runs[..count].CopyTo(_published); + _publishedCount = count; + } + else if (_publishedCount == 0) { - PublishedStart = start; - PublishedEnd = end; + _published[0] = (start, end); + _publishedCount = 1; } - else if (start > PublishedEnd || end < PublishedStart) + else if (start > _published[0].End || end < _published[0].Start) { // Two runs with unpublished bytes between them: one interval cannot hold both, // and widening it over the gap would claim bytes guest memory never got. The // longer run is kept; forgetting the other only costs publishing it again. - if (end - start > PublishedEnd - PublishedStart) + if (end - start <= _published[0].End - _published[0].Start) { - PublishedStart = start; - PublishedEnd = end; + return; } + + _published[0] = (start, end); } else { - PublishedStart = Math.Min(PublishedStart, start); - PublishedEnd = Math.Max(PublishedEnd, end); + _published[0] = (Math.Min(_published[0].Start, start), Math.Max(_published[0].End, end)); } - if (PublishedStart != wasStart || PublishedEnd != wasEnd) + BindingVersion++; + Epochs?.NoteBindingChanged(); + } + + private static int DropShortest(Span<(ulong Start, ulong End)> runs) + { + var shortest = 0; + for (var index = 1; index < runs.Length; index++) { - BindingVersion++; - Epochs?.NoteBindingChanged(); + // On a tie the later run goes, as one interval keeps the earlier half. + if (runs[index].End - runs[index].Start <= runs[shortest].End - runs[shortest].Start) + { + shortest = index; + } } + + runs[(shortest + 1)..].CopyTo(runs[shortest..]); + return runs.Length - 1; } /// True when guest memory already holds this run of the image. - public bool IsPublished(ulong start, ulong end) => - PublishedEnd > PublishedStart && start >= PublishedStart && end <= PublishedEnd; + public bool IsPublished(ulong start, ulong end) => Contains(PublishedRuns, start, end); /// /// The texture got bytes over [start, end) guest memory does not hold (a copy from an alias that still - /// owes them): what was published there is not this image's any more. A cut from the middle keeps the longer - /// side; forgetting a run only costs publishing it again. + /// owes them): what was published there is not this image's any more. A cut from the middle of the one run + /// (or of a full set) keeps the longer side; forgetting a run only costs publishing it again. /// public void ForgetPublished(ulong start, ulong end) { - if (PublishedEnd <= PublishedStart || end <= PublishedStart || start >= PublishedEnd) + Span<(ulong Start, ulong End)> runs = stackalloc (ulong, ulong)[MaxRuns + 1]; + var count = SubtractRun(PublishedRuns, start, end, runs); + if (count == _publishedCount && runs[..count].SequenceEqual(PublishedRuns)) { return; } - if (start <= PublishedStart && end >= PublishedEnd) - { - PublishedStart = PublishedEnd = 0; - } - else if (start <= PublishedStart) - { - PublishedStart = end; - } - else if (end >= PublishedEnd) - { - PublishedEnd = start; - } - else if (start - PublishedStart >= PublishedEnd - end) - { - PublishedEnd = start; - } - else + if (count > RunCapacity) { - PublishedStart = end; + count = DropShortest(runs[..count]); } + runs[..count].CopyTo(_published); + _publishedCount = count; BindingVersion++; Epochs?.NoteBindingChanged(); } @@ -860,8 +1128,7 @@ public void ClearGpuModified() var wasModified = _gpuModified; _gpuModified = false; ReleasePendingWriteback(); - PublishedStart = 0; - PublishedEnd = 0; + _publishedCount = 0; if (wasModified) { BindingVersion++; diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.AliasSubset.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.AliasSubset.cs index dcd9ac636..5458ebb29 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.AliasSubset.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.AliasSubset.cs @@ -71,24 +71,39 @@ private bool TryPublishAliasLayerSubset( var targetEnd = targetStart + layers * stride; var otherInside = sourceStart == 0 && sourceEnd == other.Description.Data.Size; if (sourceStart != otherStart || sourceEnd != otherEnd || - (other.IsCpuDirty && other.DirtyStart < sourceEnd && other.DirtyEnd > sourceStart) || - !CopyLeavesRunCurrent(image, targetStart, targetEnd) || + (other.IsCpuDirty && other.StaleOverlaps(sourceStart, sourceEnd)) || + // Whether marking the run current leaves none of it stale: a refresh of what stays stale would put the + // guest's older bytes back over the copy. + !image.CanCutStale(targetStart, targetEnd) || // A write leaves the other image stale over the run and GPU-modified for the rest; one stale interval - // cannot hold the run apart from one it already has, and widening it would cover bytes only its texture holds. + // cannot hold the run apart from one it already has, and widening it would cover bytes only its texture + // holds. Run sets hold it apart while the set has room. (takesGpuOwnership && !otherInside && other.IsCpuDirty && - (other.DirtyEnd < sourceStart || other.DirtyStart > sourceEnd))) + (other.RunCapacity > 1 + ? !other.CanAddStaleRun(sourceStart, sourceEnd) + : other.DirtyEnd < sourceStart || other.DirtyStart > sourceEnd))) { return false; } + if (LaterOwnerOverlaps(image, other)) + { + RefuseAliasTransition("subset-later-owner"); + return false; + } + + if (!RestReloadsAround(image, targetStart, targetEnd)) + { + RefuseAliasTransition("subset-rest-reload"); + return false; + } + if (takesGpuOwnership && !otherInside) { // The other image stays GPU-modified and stale over the run, and only TryRefreshDirtyRun reloads a stale run // of such an image (a whole refresh would replace bytes only its texture holds). Unless that reload is // certain to make exactly this run, its next use would keep its older texels there (alias_run_refresh_refused). - var (staleStart, staleEnd) = other.IsCpuDirty - ? (Math.Min(other.DirtyStart, sourceStart), Math.Max(other.DirtyEnd, sourceEnd)) - : (sourceStart, sourceEnd); + var (staleStart, staleEnd) = other.MergedStaleRun(sourceStart, sourceEnd); if (!CanReloadRunExactly(other, staleStart, staleEnd)) { RefuseAliasTransition("subset-stale-run-inexact"); @@ -141,18 +156,78 @@ private bool TryPublishAliasLayerSubset( return true; } - // Whether marking [start, end) refreshed leaves none of it stale: one stale interval cannot lose its middle - // (MetalCachedImage.RefreshComplete), and a refresh of what stays stale would put the guest's older bytes back - // over the copy. - private static bool CopyLeavesRunCurrent(MetalCachedImage image, ulong start, ulong end) + // Whether an alias this sync has not reached yet still owes bytes it shares with this image: on its own turn it + // publishes them and marks this image stale over all it shares with it (MarkAliasRunDirty). Over the run, the + // reload would replace the copy with guest bytes the source has not given guest memory; anywhere else, it can + // tip what is left stale past the narrow refresh (RestReloadsAround). One that has nothing to give (stale over all + // it shares) is skipped by the sync, and one already reached marked this image before the copy, which the copy's + // cut then clears. Caller holds the lock, inside SynchronizeAliases. + private bool LaterOwnerOverlaps(MetalCachedImage image, MetalCachedImage other) + { + var address = image.Description.Data.Address; + var size = image.Description.Data.Size; + foreach (var identifier in FindImagesInRange(address, size, pageOverlap: false)) + { + if (_slots.TryGet(identifier) is not { } owner || owner == image || owner == other || + !owner.IsGpuModified || !owner.Overlaps(address, size) || _syncedScratch.Contains(owner)) + { + continue; + } + + var (shareStart, shareEnd) = owner.OverlapWithin(address, size); + if (shareEnd > shareStart && owner.IsStaleOver(shareStart, shareEnd)) + { + continue; + } + + return true; + } + + return false; + } + + // Whether what stays stale on this image once [start, end) is marked current is reloaded without touching the + // run: by TryRefreshDirtyRun, each run alone (the half rule met, as the image is now), over a covering run that + // does not reach into the copied one, read in place. Otherwise the reload is a whole one, and it would put guest + // bytes - which do not have the source's yet - over the copy. + private bool RestReloadsAround(MetalCachedImage image, ulong start, ulong end) { if (!image.IsCpuDirty) { return true; } - var (dirtyStart, dirtyEnd) = (image.DirtyStart, image.DirtyEnd); - return dirtyEnd <= start || dirtyStart >= end || start <= dirtyStart || end >= dirtyEnd; + Span<(ulong Start, ulong End)> left = stackalloc (ulong, ulong)[MetalCachedImage.MaxRuns + 1]; + var count = MetalCachedImage.SubtractRun(image.StaleRuns, start, end, left); + ulong stale = 0; + foreach (var run in left[..count]) + { + stale += run.End - run.Start; + } + + if (count == 0) + { + return true; + } + + ref readonly var description = ref image.Description; + if (!SubRangeTransfersEnabled || description.HasStencil || + (stale > description.Data.Size / 2 && !NarrowRefreshPastHalf(image))) + { + return false; + } + + foreach (var run in left[..count]) + { + if (!TryCoveringRun(in description, run.Start, run.End, out var runStart, out var runEnd) || + (runStart < end && runEnd > start) || + !_guestMemory.TryResolveInPlace(description.Data.Address + runStart, runEnd - runStart, out _)) + { + return false; + } + } + + return true; } // Verify mode: what the round trip would have published (the source's run, retiled) and what the copy put in the diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.AliasTrace.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.AliasTrace.cs index 9e1a102cb..b19f71faf 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.AliasTrace.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.AliasTrace.cs @@ -23,11 +23,13 @@ internal enum MetalAliasFallbackReason : byte RunUnmapped, // The transfer refused the run and retiled nothing. RetileRefused, + // Run sets: the other image already holds as many stale runs apart as it may. + RunSetFull, } internal sealed partial class MetalImageCache { - private const int AliasFallbackReasons = (int)MetalAliasFallbackReason.RetileRefused + 1; + private const int AliasFallbackReasons = (int)MetalAliasFallbackReason.RunSetFull + 1; // SHARPEMU_METAL_V2_ALIAS_TRACE=1 logs the first alias declines and publications of // every report window with both image descriptions; =depth logs only pairs with a depth // image in them, ten times as many, which a frame of other aliases would otherwise crowd out. diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.AliasTransitions.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.AliasTransitions.cs index 83c74d7cf..b4d812114 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.AliasTransitions.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.AliasTransitions.cs @@ -74,7 +74,7 @@ internal string TakeAliasTransitionText() $"round-trip:{Mb(counts.RoundTripBytes)}] " + $"alias_moved_mib=[wb:{Mb(Interlocked.Exchange(ref _aliasMovedWritebackBytes, 0))}," + $"blit:{Mb(Interlocked.Exchange(ref _aliasMovedBlitBytes, 0))}] " + - $"alias_run_refresh_refused={Interlocked.Exchange(ref _aliasRunRefreshRefused, 0)} " + + $"alias_run_refresh_refused={Interlocked.Exchange(ref _aliasRunRefreshRefused, 0)} {TakeAliasRunText()} " + $"layer_refresh_skipped=[{layerSkips.Layers},{Mb(layerSkips.Bytes)}] " + $"alias_subset_verify=[checked:{Interlocked.Exchange(ref _aliasSubsetVerified, 0)}," + $"mismatch:{Interlocked.Read(ref _aliasSubsetMismatches)},unverified:{Interlocked.Exchange(ref _aliasSubsetUnverified, 0)}] " + diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.ConsumerRuns.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.ConsumerRuns.cs index 084af4add..ef7c89c69 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.ConsumerRuns.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.ConsumerRuns.cs @@ -63,7 +63,7 @@ cause is not (MetalWritebackCause.HostRead or MetalWritebackCause.BufferBinding // Stale over these bytes already: guest memory, or the alias this same loop // publishes, holds the newer copy, so the image has nothing of them to give. // Anything else keeps the whole writeback, which reloads the stale run first. - if (start < image.DirtyStart || end > image.DirtyEnd || + if (!image.IsStaleOver(start, end) || (written && !CanKeepGpuOwnership(image, start, end))) { return false; @@ -172,18 +172,20 @@ private bool CanKeepGpuOwnership(MetalCachedImage image, ulong start, ulong end) return false; } - // One stale interval: a write apart from the one already stale would merge the - // bytes between them, which only the texture holds. + // A write apart from the runs already stale must not merge into them over the bytes + // between, which only the texture holds: with one interval that is any write apart, + // with run sets one the full set has no room for. var (staleStart, staleEnd) = (start, end); if (image.IsCpuDirty) { - if (start > image.DirtyEnd || end < image.DirtyStart) + if (image.RunCapacity > 1 + ? !image.CanAddStaleRun(start, end) + : start > image.DirtyEnd || end < image.DirtyStart) { return false; } - staleStart = Math.Min(staleStart, image.DirtyStart); - staleEnd = Math.Max(staleEnd, image.DirtyEnd); + (staleStart, staleEnd) = image.MergedStaleRun(start, end); } return TryNarrowReloadRun(image, staleStart, staleEnd, out var runStart, out var runEnd) && @@ -209,30 +211,4 @@ private bool TryNarrowReloadRun(MetalCachedImage image, ulong staleStart, ulong var source = _guestMemory.Resolve(description.Data.Address + runStart, runEnd - runStart); return source.IsValid && source.Size >= runEnd - runStart; } - - // Every byte of [runStart, runEnd) is one guest memory holds for the image: inside the - // published run, or inside the stale interval, where guest memory is the newer copy. - private static bool GuestHoldsImageBytes( - MetalCachedImage image, ulong runStart, ulong runEnd, ulong staleStart, ulong staleEnd) - { - if (runStart >= staleStart && runEnd <= staleEnd) - { - return true; - } - - var (publishedStart, publishedEnd) = (image.PublishedStart, image.PublishedEnd); - if (publishedEnd <= publishedStart) - { - return false; - } - - if (publishedStart <= staleEnd && staleStart <= publishedEnd) - { - // Touching or overlapping: together one interval. - publishedStart = Math.Min(publishedStart, staleStart); - publishedEnd = Math.Max(publishedEnd, staleEnd); - } - - return runStart >= publishedStart && runEnd <= publishedEnd; - } } diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.DeferredRefresh.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.DeferredRefresh.cs index 1957f5bf4..7b7789b88 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.DeferredRefresh.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.DeferredRefresh.cs @@ -249,7 +249,7 @@ private static bool CoversWholeImage(in DeferredRefresh entry, bool stencilOverw private void CompleteDeferredLocked(in DeferredRefresh entry, bool overwritten, bool layerOverwritten = false) { var image = entry.Image; - (MetalImageDirtyCause Cause, ulong Start, ulong End)? stale = null; + (MetalImageDirtyCause Cause, (ulong Start, ulong End)[] Runs)? stale = null; if (entry.AliasesPending && (!overwritten || !TryDiscardOverwrittenAliases(entry.Identifier))) { SynchronizeAliases(entry.Identifier, takesGpuOwnership: true, role: overwritten ? "rt-overwrite" : "rt-load"); @@ -279,11 +279,14 @@ private void CompleteDeferredLocked(in DeferredRefresh entry, bool overwritten, NoteLinearGpuWrite(image); image.GpuWriteSerial = _owner.CurrentSerial; image.NoteUse(image.GpuWriteSerial); - if (stale is { } run) + if (stale is { } left) { // The layers this pass neither wrote nor read stay stale under the GPU write; their next use refreshes // just them (TryRefreshDirtyRun), or a later pass that overwrites them drops them as this one did. - image.MarkCpuDirty(run.Cause, run.Start, run.End); + foreach (var (start, end) in left.Runs) + { + image.MarkCpuDirty(left.Cause, start, end); + } } } @@ -332,11 +335,13 @@ private static bool CoversViewLayer(in DeferredRefresh entry) } // Instead of the upload: drops the stale bytes of the view's layers when the pass is proven to overwrite them, - // and leaves the stale layers it does not touch stale. True with the interval still stale afterwards (or none); - // false - and the caller uploads as before - when the pass reads a stale layer, the cut would split the stale - // interval, or what is left is not a run a later refresh makes exactly. + // and leaves the stale layers it does not touch stale. True with the runs still stale afterwards (or none); + // false - and the caller uploads as before - when the pass reads a stale layer, the cut would split a stale run + // the image has no room to hold as two (one interval never has), or what is left is not runs a later refresh + // makes exactly. private bool TryLeaveOtherLayersStale( - in DeferredRefresh entry, bool layerOverwritten, out (MetalImageDirtyCause Cause, ulong Start, ulong End)? stale) + in DeferredRefresh entry, bool layerOverwritten, + out (MetalImageDirtyCause Cause, (ulong Start, ulong End)[] Runs)? stale) { stale = null; var image = entry.Image; @@ -346,9 +351,9 @@ private bool TryLeaveOtherLayersStale( return false; } - var (dirtyStart, dirtyEnd) = (image.DirtyStart, image.DirtyEnd); - var (start, end) = (dirtyStart, dirtyEnd); - var overlaps = viewStart < dirtyEnd && viewEnd > dirtyStart; + Span<(ulong Start, ulong End)> left = stackalloc (ulong, ulong)[MetalCachedImage.MaxRuns + 1]; + var overlaps = image.StaleOverlaps(viewStart, viewEnd); + int count; if (overlaps) { if (!layerOverwritten) @@ -356,47 +361,51 @@ private bool TryLeaveOtherLayersStale( return false; } - if (viewStart <= dirtyStart && viewEnd >= dirtyEnd) - { - (start, end) = (0, 0); - } - else if (viewStart <= dirtyStart) - { - start = viewEnd; - } - else if (viewEnd >= dirtyEnd) - { - end = viewStart; - } - else + count = MetalCachedImage.SubtractRun(image.StaleRuns, viewStart, viewEnd, left); + if (count > image.RunCapacity) { return false; } } + else + { + count = image.StaleRuns.Length; + image.StaleRuns.CopyTo(left); + } // What stays stale is refreshed later by TryRefreshDirtyRun alone (a GPU-written image is never uploaded - // whole): it must be a run that refresh makes exactly, and one it can read in place. Anything else uploads - // now, as before, rather than leave the stale keep in RefreshFromGuestCore an interval it did not have. - if (end > start && - (!SubRangeTransfersEnabled || - !TryCoveringRun(in image.Description, start, end, out var runStart, out var runEnd) || - runStart != start || runEnd != end || - !_guestMemory.TryResolveInPlace(image.Description.Data.Address + start, end - start, out _))) + // whole): each run must be one that refresh makes exactly, and one it can read in place. Anything else uploads + // now, as before, rather than leave the stale keep in RefreshFromGuestCore runs it did not have. + foreach (var (start, end) in left[..count]) { - return false; + if (!SubRangeTransfersEnabled || + !TryCoveringRun(in image.Description, start, end, out var runStart, out var runEnd) || + runStart != start || runEnd != end || + !_guestMemory.TryResolveInPlace(image.Description.Data.Address + start, end - start, out _)) + { + return false; + } } if (overlaps) { + ulong dropped = 0; + foreach (var run in image.StaleRuns) + { + if (run.Start < viewEnd && run.End > viewStart) + { + dropped += Math.Min(viewEnd, run.End) - Math.Max(viewStart, run.Start); + } + } + Interlocked.Increment(ref _layerRefreshSkippedLayers); - Interlocked.Add(ref _layerRefreshSkippedBytes, - (long)(Math.Min(viewEnd, dirtyEnd) - Math.Max(viewStart, dirtyStart))); + Interlocked.Add(ref _layerRefreshSkippedBytes, (long)dropped); } - // The GPU write that follows clears the stale interval; the caller marks what is left again after it. - if (end > start) + // The GPU write that follows clears the stale runs; the caller marks what is left again after it. + if (count > 0) { - stale = (image.DirtyCause, start, end); + stale = (image.DirtyCause, left[..count].ToArray()); } return true; diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.RunSets.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.RunSets.cs new file mode 100644 index 000000000..335f8f1c3 --- /dev/null +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.RunSets.cs @@ -0,0 +1,111 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +namespace SharpEmu.Gpu.Metal.V2; + +/// +/// What run sets did (MetalCachedImage.StaleRuns): the most stale runs one image held, sets that were full and merged +/// by publishing the image first, reloads of a run over half an image, and merges over bytes only a texture held (a +/// bug: must stay 0). +/// +internal sealed class MetalRunSetStats +{ + private long _setsMax, _merged, _refreshOverHalf, _unpublished; + + public void NoteSets(int count) + { + long seen; + while (count > (seen = Interlocked.Read(ref _setsMax)) && + Interlocked.CompareExchange(ref _setsMax, count, seen) != seen) + { + } + } + + public void NoteMerged(bool unpublished = false) + { + Interlocked.Increment(ref _merged); + if (unpublished) + { + Interlocked.Increment(ref _unpublished); + } + } + + public void NoteRefreshOverHalf() => Interlocked.Increment(ref _refreshOverHalf); + + public MetalImageCache.AliasRunCounts Read() => + new(Interlocked.Read(ref _setsMax), Interlocked.Read(ref _merged), Interlocked.Read(ref _refreshOverHalf), + Interlocked.Read(ref _unpublished)); + + public MetalImageCache.AliasRunCounts Take() => + new(Interlocked.Exchange(ref _setsMax, 0), Interlocked.Exchange(ref _merged, 0), + Interlocked.Exchange(ref _refreshOverHalf, 0), Interlocked.Exchange(ref _unpublished, 0)); +} + +// SHARPEMU_METAL_V2_ALIAS_RUN_SETS (on; =0 off): a GPU-written image holds up to four stale runs and four published runs +// apart, instead of one interval each, and reloads a stale run alone however much of the image it is. An alias that +// takes a second run apart from the first, or a run over half of the image, used to cost a whole writeback of the +// image and a whole reload of the alias (Demon's Souls: the R32Uint 960x540 transient between its shadow array and the +// 72-layer array, the mip chain, the 1080p R16F pair). A set that is full is merged only by publishing the image first, +// the whole writeback as before, and counted. Off is the single interval exactly as before. +internal sealed partial class MetalImageCache +{ + internal readonly record struct AliasRunCounts(long SetsMax, long Merged, long RefreshOverHalf, long Unpublished); + + internal bool AliasRunSetsEnabled { get; set; } = + Environment.GetEnvironmentVariable("SHARPEMU_METAL_V2_ALIAS_RUN_SETS") != "0"; + + private readonly MetalRunSetStats _runStats = new(); + + /// Test hook: the run-set counters so far. + internal AliasRunCounts AliasRunCounters => _runStats.Read(); + + // A new image takes the setting the cache has when it admits it, for its whole life. + private void AdmitRunSets(MetalCachedImage image) + { + image.RunCapacity = AliasRunSetsEnabled ? MetalCachedImage.MaxRuns : 1; + image.RunStats = _runStats; + } + + private string TakeAliasRunText() + { + var runs = _runStats.Take(); + return $"alias_runs=[sets_max:{runs.SetsMax},merged:{runs.Merged},refresh_over_half:{runs.RefreshOverHalf}," + + $"unpublished:{runs.Unpublished}]"; + } + + // Every byte of [runStart, runEnd) is one guest memory holds for the image: inside a published run, or inside a + // stale run (the image's, or [staleStart, staleEnd) about to be one), where guest memory is the newer copy. + private static bool GuestHoldsImageBytes( + MetalCachedImage image, ulong runStart, ulong runEnd, ulong staleStart, ulong staleEnd) + { + var at = runStart; + while (at < runEnd) + { + var next = staleStart <= at && at < staleEnd ? staleEnd : at; + foreach (var run in image.PublishedRuns) + { + if (run.Start <= at && at < run.End) + { + next = Math.Max(next, run.End); + } + } + + foreach (var run in image.StaleRuns) + { + if (run.Start <= at && at < run.End) + { + next = Math.Max(next, run.End); + } + } + + if (next == at) + { + return false; + } + + at = next; + } + + return true; + } +} diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.cs index f43f104bc..b50bf2ae9 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.cs @@ -600,8 +600,7 @@ private void SynchronizeAliases( other.Description.Data.Address + other.Description.Data.Size); var sharedSize = sharedEnd > sharedStart ? sharedEnd - sharedStart : 0; var (otherStart, otherEnd) = other.OverlapWithin(sharedStart, sharedSize); - if (other.IsCpuDirty && otherEnd > otherStart && - otherStart >= other.DirtyStart && otherEnd <= other.DirtyEnd) + if (otherEnd > otherStart && other.IsStaleOver(otherStart, otherEnd)) { // The other image already gave these bytes up to a write through an // alias and owns only the rest: its texture is stale here, so it has @@ -1235,18 +1234,28 @@ private static void NoteForeignStencilShare(MetalCachedImage depth, MetalCachedI // is certain to be a narrow one: an image dirty over the run while it stays // GPU-modified must never be refreshed whole, since that would replace bytes only its // texture holds. A run already stale on the image is refused for the same reason - // when it lies outside the stale interval, which one interval cannot hold apart. + // when it lies outside the stale interval, which one interval cannot hold apart. With + // run sets (MetalImageCache.RunSets) it is refused only when the set is full, which the + // caller's whole writeback then merges by publishing; and a run past half of the image + // is reloaded alone like any other (NarrowRefreshPastHalf). private bool TryHandOverAliasRun( MetalCachedImage other, ulong start, ulong end, out MetalAliasFallbackReason declined) { + var runSets = other.RunCapacity > 1; declined = !SubRangeTransfersEnabled ? MetalAliasFallbackReason.SubRangeDisabled : end <= start ? MetalAliasFallbackReason.EmptyRun : other.Description.HasStencil ? MetalAliasFallbackReason.Stencil : start == 0 && end >= other.Description.Data.Size ? MetalAliasFallbackReason.RunIsWholeOther - : end - start > other.Description.Data.Size / 2 ? MetalAliasFallbackReason.RunPastHalf - : other.IsCpuDirty && (start < other.DirtyStart || end > other.DirtyEnd) + : !runSets && end - start > other.Description.Data.Size / 2 ? MetalAliasFallbackReason.RunPastHalf + : runSets && !other.CanAddStaleRun(start, end) ? MetalAliasFallbackReason.RunSetFull + : !runSets && other.IsCpuDirty && (start < other.DirtyStart || end > other.DirtyEnd) ? MetalAliasFallbackReason.OtherDirtyOutsideRun : MetalAliasFallbackReason.None; + if (declined == MetalAliasFallbackReason.RunSetFull) + { + _runStats.NoteMerged(); + } + if (declined != MetalAliasFallbackReason.None) { return false; @@ -1268,12 +1277,19 @@ private bool TryHandOverAliasRun( // them - a refresh of the merged interval would replace those bytes with the guest's. // The run it holds is refreshed first instead. That is safe here: an alias still // owing those bytes overlaps this image too, so this same loop publishes it and marks - // the run stale again. + // the run stale again. With run sets only a full set is refreshed first. private void MarkAliasRunDirty(MetalCachedImage image, ulong start, ulong end) { if (image.IsGpuModified && image.IsCpuDirty && end > start && - (start > image.DirtyEnd || end < image.DirtyStart)) + (image.RunCapacity > 1 + ? !image.CanAddStaleRun(start, end) + : start > image.DirtyEnd || end < image.DirtyStart)) { + if (image.RunCapacity > 1) + { + _runStats.NoteMerged(); + } + RefreshFromGuest(image); } @@ -2217,7 +2233,7 @@ private bool TryWriteBackRun( return false; } - if (image.IsCpuDirty && aligned < image.DirtyEnd && alignedEnd > image.DirtyStart) + if (image.IsCpuDirty && image.StaleOverlaps(aligned, alignedEnd)) { RefreshBeforeWriteback(image); } @@ -2500,6 +2516,7 @@ private ResourceSlotIdentifier InsertImage( LevelsChangedFrame = _idleClock.Frames, Sparse = sparse, }; + AdmitRunSets(image); if (windowView) { image.MarkWindowLinearView(); @@ -2856,6 +2873,8 @@ private void RefreshFromGuestCore(MetalCachedImage image) // the run is most of the image, cannot be aligned or cannot be mapped - the whole // image is then refreshed as before, because a partial refresh that loses bytes would // leave the texture disagreeing with guest memory for good. + // With run sets an image may be stale over several runs: each is refreshed alone, every + // one planned before any is encoded, and the half rule counts them all. private bool TryRefreshDirtyRun(MetalCachedImage image) { ref readonly var description = ref image.Description; @@ -2863,47 +2882,77 @@ private bool TryRefreshDirtyRun(MetalCachedImage image) // held from its BASE_LEVEL the coarser levels' run. var residentStart = image.ResidentStart; var residentEnd = image.ResidentEnd; - var dirtyStart = Math.Max(image.DirtyStart, residentStart); - var dirtyEnd = Math.Min(image.DirtyEnd, residentEnd); - if (!SubRangeTransfersEnabled || description.HasStencil || - dirtyEnd <= dirtyStart || - (dirtyEnd - dirtyStart > (residentEnd - residentStart) / 2 && !NarrowRefreshPastHalf(image))) + if (!SubRangeTransfersEnabled || description.HasStencil) { return false; } - if (!TryCoveringRun(in description, dirtyStart, dirtyEnd, out var start, out var end)) + Span<(ulong Start, ulong End)> runs = stackalloc (ulong, ulong)[MetalCachedImage.MaxRuns]; + var count = 0; + ulong stale = 0; + foreach (var run in image.StaleRuns) { - return false; + var dirtyStart = Math.Max(run.Start, residentStart); + var dirtyEnd = Math.Min(run.End, residentEnd); + if (dirtyEnd > dirtyStart) + { + runs[count++] = (dirtyStart, dirtyEnd); + stale += dirtyEnd - dirtyStart; + } } - // The run's ends widen outward to cuts of the whole chain; the resident run's own - // ends are where its levels' transfers start and stop, so cutting there loses none. - start = Math.Max(start, residentStart); - end = Math.Min(end, residentEnd); - var source = ResolveUploadSource(description.Data.Address + start, end - start); - if (!source.IsValid || source.Size < end - start) + var overHalf = stale > (residentEnd - residentStart) / 2; + if (count == 0 || (overHalf && !NarrowRefreshPastHalf(image))) { return false; } - PrepareSparseUpload(image, start, end); - _owner.LandHeldCopies(description.Data.Address + start, end - start); - var context = _owner.BeginTransfer(MetalTransferCause.Upload, image.Texture); - if (!EncodeUpload( - context, in description, ResidentRange(image), source, default, image.Texture, start, end - start, - image.FirstLevel)) + for (var index = 0; index < count; index++) { - // Nothing reached the texture; the whole refresh decides what becomes of the image. - return false; + if (!TryCoveringRun(in description, runs[index].Start, runs[index].End, out var start, out var end)) + { + return false; + } + + // The run's ends widen outward to cuts of the whole chain; the resident run's own + // ends are where its levels' transfers start and stop, so cutting there loses none. + runs[index] = (Math.Max(start, residentStart), Math.Min(end, residentEnd)); } - _uploadCauses[(int)image.DirtyCause]++; - _partialUploads++; - _partialUploadBytesSaved += (long)(residentEnd - residentStart - (end - start)); - if (context.WantsEncodedLabels) + var cause = image.DirtyCause; + foreach (var (start, end) in runs[..count]) { - context.ProfileEncoded(ProfileLabel("upload-run", in description)); + var source = ResolveUploadSource(description.Data.Address + start, end - start); + if (!source.IsValid || source.Size < end - start) + { + return false; + } + + PrepareSparseUpload(image, start, end); + _owner.LandHeldCopies(description.Data.Address + start, end - start); + var context = _owner.BeginTransfer(MetalTransferCause.Upload, image.Texture); + if (!EncodeUpload( + context, in description, ResidentRange(image), source, default, image.Texture, start, end - start, + image.FirstLevel)) + { + // Nothing of this run reached the texture; the whole refresh decides what becomes of the image. + return false; + } + + _uploadCauses[(int)cause]++; + _partialUploads++; + _partialUploadBytesSaved += (long)(residentEnd - residentStart - (end - start)); + if (context.WantsEncodedLabels) + { + context.ProfileEncoded(ProfileLabel("upload-run", in description)); + } + + if (image.FirstLevel == 0) + { + image.RefreshComplete(start, end); + } + + Interlocked.Increment(ref _uploads); } if (image.FirstLevel != 0) @@ -2911,12 +2960,12 @@ private bool TryRefreshDirtyRun(MetalCachedImage image) // What is still dirty lies outside the levels the texture holds. image.RefreshComplete(); } - else + + if (overHalf) { - image.RefreshComplete(start, end); + _runStats.NoteRefreshOverHalf(); } - Interlocked.Increment(ref _uploads); return true; } @@ -2924,8 +2973,9 @@ private bool TryRefreshDirtyRun(MetalCachedImage image) // layers its passes have not overwritten yet): the whole refresh is no option there - it would replace the // layers only the texture holds - so the half rule, a cost rule, would only keep the stale layers. // TryRefreshDirtyRun and TryNarrowReloadRun both ask this, so they give one answer. + // With run sets every GPU-written image goes the same way: a whole refresh is forbidden for any of them. private bool NarrowRefreshPastHalf(MetalCachedImage image) => - LayerDeferEnabled && image.IsGpuModified && image.Description.IsLayered; + image.IsGpuModified && (image.RunCapacity > 1 || (LayerDeferEnabled && image.Description.IsLayered)); // Whether TryRefreshDirtyRun, given [start, end) as the image's whole stale interval, reloads exactly that run // and nothing past it: sub-range transfers on, the half rule met, a covering run that does not widen, and guest @@ -3148,9 +3198,15 @@ private void RefreshBeforeWriteback(MetalCachedImage image) return; } - var (cause, start, end) = (image.DirtyCause, image.DirtyStart, image.DirtyEnd); + var cause = image.DirtyCause; + Span<(ulong Start, ulong End)> runs = stackalloc (ulong, ulong)[MetalCachedImage.MaxRuns]; + var count = image.StaleRuns.Length; + image.StaleRuns.CopyTo(runs); RefreshFromGuest(image); - image.MarkCpuDirty(cause, start, end); + foreach (var (start, end) in runs[..count]) + { + image.MarkCpuDirty(cause, start, end); + } } // Retiles a GPU-written image back into guest memory; afterwards guest memory and diff --git a/tests/SharpEmu.Gpu.Metal.Tests/MetalDeferredRefreshTests.cs b/tests/SharpEmu.Gpu.Metal.Tests/MetalDeferredRefreshTests.cs index 54b9db1cc..e67ab5aae 100644 --- a/tests/SharpEmu.Gpu.Metal.Tests/MetalDeferredRefreshTests.cs +++ b/tests/SharpEmu.Gpu.Metal.Tests/MetalDeferredRefreshTests.cs @@ -132,12 +132,12 @@ public void ATextureBindingBeforeThePassSeesTheGuestBytes() public static TheoryData LayerOrders => new() { - // order, uploads on (round one + round two), layers dropped on + // order, uploads on (round one + round two), layers dropped on; run sets on (SHARPEMU_METAL_V2_ALIAS_RUN_SETS) { new uint[] { 0, 1, 2, 3 }, 0, 8 }, { new uint[] { 3, 2, 1, 0 }, 0, 8 }, - // The first clear cuts the middle: the whole array is uploaded, the rest are not stale any more. - { new uint[] { 2, 0, 3, 1 }, 2, 0 }, - { new uint[] { 1, 2, 3, 0 }, 2, 0 }, + // The first clear cuts the middle: two stale runs are left (run sets), and the later clears drop them. + { new uint[] { 2, 0, 3, 1 }, 0, 8 }, + { new uint[] { 1, 2, 3, 0 }, 0, 8 }, // Layers 2 and 3 are never cleared: they are uploaded when the array is read, and only then. { new uint[] { 0, 1 }, 2, 4 }, }; diff --git a/tests/SharpEmu.Gpu.Metal.Tests/MetalImageAliasTests.RunSets.cs b/tests/SharpEmu.Gpu.Metal.Tests/MetalImageAliasTests.RunSets.cs new file mode 100644 index 000000000..5d4127f3d --- /dev/null +++ b/tests/SharpEmu.Gpu.Metal.Tests/MetalImageAliasTests.RunSets.cs @@ -0,0 +1,204 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using SharpEmu.Gpu.Metal.V2; +using SharpEmu.Libs.Gpu.Images; +using Xunit; + +namespace SharpEmu.Gpu.Metal.Tests; + +// Run sets (SHARPEMU_METAL_V2_ALIAS_RUN_SETS): a GPU-written image holds up to four stale runs and four published ones +// instead of one interval each, and reloads a stale run alone however much of it the run is. Every case runs with run +// sets on and off and must end bit-identical: the large image's texture and every alias's texture read back, and +// guest memory after every GPU write is flushed. Neither arm may keep older texels over a stale run +// (alias_run_refresh_refused) or merge stale runs over bytes only the texture holds. +public sealed unsafe partial class MetalImageAliasTests +{ + private sealed record RunSetOutcome( + byte[] Large, byte[] Guest, byte[]? GuestBeforeRead, List Aliases, long Writebacks, + MetalImageCache.AliasRunCounts Runs, string Text); + + // The large 64x64 linear image written by the GPU (its texture holds one pattern, guest memory another), then + // each alias of whole rows of it drawn as a colour target with a texture of its own, in order. Then, when asked, + // a CPU read of all of it; then the large image is sampled, every texture read back and every GPU write flushed. + private static RunSetOutcome RunAliasDraws(bool runSets, (ulong Offset, uint Rows)[] draws, bool cpuReadFirst = false) + { + using var rig = new Rig(Device.Value); + rig.Cache.AliasRunSetsEnabled = runSets; + var (image, _, _) = GpuWrittenLarge(rig); + var writebacks = rig.Cache.Counters.Writebacks; + var aliases = new List(); + byte seed = 0x11; + foreach (var (offset, rows) in draws) + { + aliases.Add(DrawAlias(rig, offset, rows, seed)); + seed += 0x22; + } + + byte[]? before = null; + if (cpuReadFirst) + { + rig.Cache.FlushGpuWrites(ImageAddress, LargeSize, MetalWritebackCause.HostRead); + rig.Harness.Submit(); + rig.Harness.Begin(); + before = rig.ReadGuest(ImageAddress, LargeSize); + } + + var text = $"large_dirty={image.IsCpuDirty}:0x{image.DirtyStart:X}-0x{image.DirtyEnd:X} " + + $"runs={image.StaleRunCount} gpu={image.IsGpuModified}"; + rig.Acquire(ImageAddress, LargeSide, ImageRole.Texture); + rig.Harness.Submit(); + rig.Harness.Begin(); + var large = ReadTexture(rig, image); + var aliasBytes = aliases.Select(alias => ReadTexture(rig, alias)).ToList(); + rig.Cache.FlushGpuWrites(ImageAddress, LargeSize, MetalWritebackCause.HostRead); + rig.Harness.Submit(); + rig.Harness.Begin(); + writebacks = rig.Cache.Counters.Writebacks - writebacks; + var runs = rig.Cache.AliasRunCounters; + Assert.Equal(0, rig.Cache.AliasRunRefreshRefused); + Assert.Equal(0, runs.Unpublished); + return new RunSetOutcome( + large, rig.ReadGuest(ImageAddress, LargeSize), before, aliasBytes, writebacks, runs, + text + " " + rig.Cache.TakeAliasTransitionText()); + } + + // An alias of `rows` whole rows of the large image at `offset`, drawn: its texture given bytes of its own. + private static MetalCachedImage DrawAlias(Rig rig, ulong offset, uint rows, byte seed) + { + var alias = rig.Cache.GetImage( + rig.Acquire(Rig.Request(ImageAddress + offset, LargeSide, rows, ImageRole.ColorTarget))); + Assert.True(alias.IsGpuModified); + var size = alias.Description.Data.Size; + var drawn = MetalTileOracle.Pattern((int)size, seed); + rig.Harness.Transfer.EncodeGuestToTexture( + rig.Harness, alias.Description, new SubresourceRange(0, 1, 0, 1), + new MetalGuestRange(rig.Harness.Buffer(drawn), 0, size, 0), default, alias.Texture, 0, size); + rig.Harness.Submit(); + rig.Harness.Begin(); + return alias; + } + + private RunSetOutcome[] OnAndOff((ulong Offset, uint Rows)[] draws, bool cpuReadFirst = false) + { + var on = RunAliasDraws(runSets: true, draws, cpuReadFirst); + var off = RunAliasDraws(runSets: false, draws, cpuReadFirst); + output.WriteLine($"on: wb={on.Writebacks} runs={on.Runs} {on.Text}"); + output.WriteLine($"off: wb={off.Writebacks} runs={off.Runs} {off.Text}"); + Assert.Equal(off.Large, on.Large); + Assert.Equal(off.Aliases.Count, on.Aliases.Count); + for (var index = 0; index < on.Aliases.Count; index++) + { + Assert.Equal(off.Aliases[index], on.Aliases[index]); + } + + Assert.Equal(off.Guest, on.Guest); + Assert.Equal(off.GuestBeforeRead, on.GuestBeforeRead); + return [on, off]; + } + + // Two aliases apart from each other take their runs from the large image, which stays GPU-modified and stale + // over both (one interval cannot hold them apart: the off arm writes it back whole), then it is read. + [Fact] + public void TwoDisjointAliasesTakeRunsAndTheReadIsExact() + { + if (!RequireDevice()) return; + var outcomes = OnAndOff([(0, AliasRows), (0x3000, AliasRows)]); + Assert.True(outcomes[0].Runs.SetsMax >= 2); + // On, the large image kept its texture's bytes outside the two runs; off, it was written back whole. + Assert.Contains("runs=2 gpu=True", outcomes[0].Text); + Assert.Contains("gpu=False", outcomes[1].Text); + } + + // A run of 62.5% of the image: handed over and reloaded alone while the image stays GPU-modified (off: past half + // is a decline, and the image is written back whole). + [Fact] + public void ARunOverSixtyPercentIsReloadedAloneWhileGpuModified() + { + if (!RequireDevice()) return; + var outcomes = OnAndOff([(0, 40)]); + Assert.True(outcomes[0].Runs.RefreshOverHalf >= 1); + Assert.Equal(0, outcomes[1].Runs.RefreshOverHalf); + } + + // Five aliases apart from each other: the fifth finds the run set full. It merges only by publishing the image + // first (the whole writeback), never by widening a stale run over bytes only the texture holds. + [Fact] + public void AFullRunSetPublishesBeforeItMerges() + { + if (!RequireDevice()) return; + var outcomes = OnAndOff([(0, 4), (0x800, 4), (0x1000, 4), (0x1800, 4), (0x2000, 4)]); + Assert.Equal(MetalCachedImage.MaxRuns, (int)outcomes[0].Runs.SetsMax); + Assert.True(outcomes[0].Runs.Merged >= 1); + } + + // A takes a run, B takes half of A's run and more of the large image, then A is drawn again over its run while B + // is GPU-modified: B publishes what they share first, and the large image is stale over the union of both. + [Fact] + public void AWriterThroughTheOldAliasAfterAHandOverIsExact() + { + if (!RequireDevice()) return; + OnAndOff([(0, AliasRows), (0x800, AliasRows), (0, AliasRows)]); + } + + // A CPU read of the whole image after two narrow hand-overs: guest memory gets each alias's run from the alias + // and the rest from the large image's texture, and the large image reloads only its stale runs after. + [Fact] + public void ACpuReadAfterNarrowHandOversIsExact() + { + if (!RequireDevice()) return; + OnAndOff([(0x1000, AliasRows), (0x3000, AliasRows / 2)], cpuReadFirst: true); + } + + // The layer-subset copy (MetalImageAliasTests.Subset) into an array whose source is already stale apart from the + // run (a one-layer alias took layer 8): with run sets the source holds both stale runs and the copy goes ahead. + [Fact] + public void ASubsetCopyProceedsOverASourceStaleApartFromTheRun() + { + if (!RequireDevice()) return; + var outcomes = new List<(byte[] First, byte[] Second, byte[] Guest, long Copies)>(); + foreach (var runSets in new[] { true, false }) + { + using var rig = new Rig(Device.Value); + rig.Cache.AliasRunSetsEnabled = runSets; + var tile = GuestTileMode.Standard64KB; + var first = SubsetArray(ImageAddress, 9, tile, ImageRole.StorageImage); + var size = first.Description.Data.Size; + var layer = LayerBytes(tile); + rig.WriteGuest(ImageAddress, MetalTileOracle.Pattern((int)size, 0x5A)); + var firstImage = rig.Cache.GetImage(rig.Acquire(first)); + rig.Harness.Submit(); + rig.Harness.Begin(); + rig.WriteGuest(ImageAddress, MetalTileOracle.Pattern((int)size, 0xC3)); + rig.Acquire(SubsetArray(ImageAddress + 8 * layer, 1, tile, ImageRole.StorageImage)); + rig.Harness.Submit(); + rig.Harness.Begin(); + Assert.True(firstImage.IsGpuModified); + Assert.Equal((8 * layer, 9 * layer), (firstImage.DirtyStart, firstImage.DirtyEnd)); + + var copies = rig.Cache.AliasSubsetCounters.Copies; + var second = rig.Cache.GetImage(rig.Acquire(SubsetArray(ImageAddress, 4, tile, ImageRole.StorageImage))); + rig.Harness.Submit(); + rig.Harness.Begin(); + copies = rig.Cache.AliasSubsetCounters.Copies - copies; + rig.Acquire(first with { Role = ImageRole.Texture }); + rig.Harness.Submit(); + rig.Harness.Begin(); + var firstBytes = ReadLayers(rig, firstImage); + var secondBytes = ReadLayers(rig, second); + rig.Cache.FlushGpuWrites(ImageAddress, size, MetalWritebackCause.HostRead); + rig.Harness.Submit(); + rig.Harness.Begin(); + Assert.Equal(0, rig.Cache.AliasRunRefreshRefused); + Assert.Equal(0, rig.Cache.AliasRunCounters.Unpublished); + outcomes.Add((firstBytes, secondBytes, rig.ReadGuest(ImageAddress, size), copies)); + } + + output.WriteLine($"on: copies={outcomes[0].Copies} off: copies={outcomes[1].Copies}"); + Assert.Equal(1, outcomes[0].Copies); + Assert.Equal(0, outcomes[1].Copies); + Assert.Equal(outcomes[1].First, outcomes[0].First); + Assert.Equal(outcomes[1].Second, outcomes[0].Second); + Assert.Equal(outcomes[1].Guest, outcomes[0].Guest); + } +} diff --git a/tests/SharpEmu.Gpu.Metal.Tests/MetalImageAliasTests.Subset.cs b/tests/SharpEmu.Gpu.Metal.Tests/MetalImageAliasTests.Subset.cs index 353fe7df2..71df3bcfc 100644 --- a/tests/SharpEmu.Gpu.Metal.Tests/MetalImageAliasTests.Subset.cs +++ b/tests/SharpEmu.Gpu.Metal.Tests/MetalImageAliasTests.Subset.cs @@ -219,10 +219,17 @@ public void TheLayerMatchFollowsTheSliceSwizzle() } } - // The source already stale inside the run (a one-layer alias took its layer 2): copying it would carry its old - // bytes there, so the array is refused (the alias, a subset itself, may still be copied). Same bytes either way. - [Fact] - public void ASourceStaleInsideTheSubsetIsRefused() + // The source already stale inside the run (a one-layer alias took its layer 2, or 0): copying it would carry its + // old bytes there, so the array is refused. The alias, a subset itself, may still be copied - unless the array, + // which this sync reaches after it, would mark the reader stale over the copy again, or what the copy leaves + // stale on the new 8-layer reader (7 of 8 layers) would be reloaded whole, over the copy. Same bytes either way, + // with run sets on (a cut from the middle of the reader's stale run is two runs) and off. + [Theory] + [InlineData(2u, true)] + [InlineData(2u, false)] + [InlineData(0u, true)] + [InlineData(0u, false)] + public void ASourceStaleInsideTheSubsetIsRefused(uint aliasLayer, bool runSets) { if (!RequireDevice()) return; var outcomes = new List<(byte[] Second, byte[] Guest, long Copies)>(); @@ -230,6 +237,7 @@ public void ASourceStaleInsideTheSubsetIsRefused() { using var rig = new Rig(Device.Value); rig.Cache.AliasSubsetDeviceEnabled = subset; + rig.Cache.AliasRunSetsEnabled = runSets; var first = SubsetArray(ImageAddress, 9, GuestTileMode.Standard64KB, ImageRole.StorageImage); var size = first.Description.Data.Size; var layer = LayerBytes(GuestTileMode.Standard64KB); @@ -238,12 +246,12 @@ public void ASourceStaleInsideTheSubsetIsRefused() rig.Harness.Submit(); rig.Harness.Begin(); rig.WriteGuest(ImageAddress, MetalTileOracle.Pattern((int)size, 0xC3)); - rig.Acquire(SubsetArray(ImageAddress + 2 * layer, 1, GuestTileMode.Standard64KB, ImageRole.StorageImage)); + rig.Acquire(SubsetArray(ImageAddress + aliasLayer * layer, 1, GuestTileMode.Standard64KB, ImageRole.StorageImage)); rig.Harness.Submit(); rig.Harness.Begin(); Assert.True(firstImage.IsGpuModified); Assert.True(firstImage.IsCpuDirty); - Assert.Equal((2 * layer, 3 * layer), (firstImage.DirtyStart, firstImage.DirtyEnd)); + Assert.Equal((aliasLayer * layer, (aliasLayer + 1) * layer), (firstImage.DirtyStart, firstImage.DirtyEnd)); var copies = rig.Cache.AliasSubsetCounters.Copies; var second = rig.Cache.GetImage(rig.Acquire( SubsetArray(ImageAddress, 8, GuestTileMode.Standard64KB, ImageRole.Texture))); diff --git a/tests/SharpEmu.Gpu.Metal.Tests/MetalImageAliasTests.cs b/tests/SharpEmu.Gpu.Metal.Tests/MetalImageAliasTests.cs index 1bea9edc2..92f02150f 100644 --- a/tests/SharpEmu.Gpu.Metal.Tests/MetalImageAliasTests.cs +++ b/tests/SharpEmu.Gpu.Metal.Tests/MetalImageAliasTests.cs @@ -594,14 +594,16 @@ public void AWholeWritebackOfAnImageStaleOverARunKeepsTheGuestBytesThere() Assert.Equal(0x2000UL + SmallSize, image.DirtyEnd); } - // A run past half of the GPU-written image cannot be handed over narrowly - its reload - // would be a whole one - so the image is written back whole and gives up ownership, - // as before. + // With run sets off, a run past half of the GPU-written image cannot be handed over + // narrowly - its reload would be a whole one - so the image is written back whole and + // gives up ownership, as before. (With them on it is reloaded alone: + // MetalImageAliasTests.RunSets.) [Fact] public void AnAliasRunPastHalfTheImageIsWrittenBackWhole() { if (!RequireDevice()) return; using var rig = new Rig(Device.Value); + rig.Cache.AliasRunSetsEnabled = false; var (image, written, _) = GpuWrittenLarge(rig); const uint rows = 36; const ulong offset = 0x1000; From e0387a8668ce4722827ad7d18781142a0fc92963 Mon Sep 17 00:00:00 2001 From: kuba Date: Sun, 15 Nov 2026 07:26:31 +0000 Subject: [PATCH 037/178] [Metal] Count a stale-run reload widened over texture-only bytes; a device alias copy forgets the target's publication --- .../V2/MetalImageCache.RunSets.cs | 2 +- .../SharpEmu.Gpu.Metal/V2/MetalImageCache.cs | 21 ++++++++++++++++++- 2 files changed, 21 insertions(+), 2 deletions(-) diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.RunSets.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.RunSets.cs index 335f8f1c3..2508be146 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.RunSets.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.RunSets.cs @@ -70,7 +70,7 @@ private string TakeAliasRunText() { var runs = _runStats.Take(); return $"alias_runs=[sets_max:{runs.SetsMax},merged:{runs.Merged},refresh_over_half:{runs.RefreshOverHalf}," + - $"unpublished:{runs.Unpublished}]"; + $"unpublished:{runs.Unpublished}] alias_run_widened={Interlocked.Exchange(ref _aliasRunWidened, 0)}"; } // Every byte of [runStart, runEnd) is one guest memory holds for the image: inside a published run, or inside a diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.cs index b50bf2ae9..62322dd69 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.cs @@ -2147,8 +2147,10 @@ private bool TryPublishAliasOnDevice(MetalCachedImage image, MetalCachedImage ot { context.ProfileEncoded(ProfileLabel("alias-on-device", in image.Description)); } - // The target now holds what the source holds, so it owes guest memory no upload. + // The target now holds what the source holds, so it owes guest memory no upload - and what it had + // published is not its content any more (the source still owes these bytes). image.RefreshComplete(); + image.ForgetPublished(0, image.Description.Data.Size); image.NotePublishedFrom(other); _deviceAliasPublishes++; return true; @@ -2916,7 +2918,22 @@ private bool TryRefreshDirtyRun(MetalCachedImage image) // The run's ends widen outward to cuts of the whole chain; the resident run's own // ends are where its levels' transfers start and stop, so cutting there loses none. + var staleRun = runs[index]; runs[index] = (Math.Max(start, residentStart), Math.Min(end, residentEnd)); + // A GPU-written image owns the bytes around its stale run. Where the widened run reaches bytes guest + // memory was never given (not published, not stale), the reload puts older bytes over them: counted + // and warned about, since nothing here can reload less than a whole block row. + if (image.IsGpuModified && runs[index] != staleRun && + !GuestHoldsImageBytes(image, runs[index].Start, runs[index].End, staleRun.Start, staleRun.End)) + { + Interlocked.Increment(ref _aliasRunWidened); + MetalV2Diagnostics.WarnOnce( + $"alias-run-widened:{description.PixelFormat}:{description.Extent.Width}x{description.Extent.Height}", + "A GPU-written image reloads a stale run widened over bytes only its texture holds: " + + $"{description.PixelFormat} {description.Extent.Width}x{description.Extent.Height} " + + $"0x{description.Data.Address:X16}+0x{description.Data.Size:X} " + + $"stale=0x{staleRun.Start:X}..0x{staleRun.End:X} reload=0x{runs[index].Start:X}..0x{runs[index].End:X}."); + } } var cause = image.DirtyCause; @@ -2974,6 +2991,8 @@ private bool TryRefreshDirtyRun(MetalCachedImage image) // layers only the texture holds - so the half rule, a cost rule, would only keep the stale layers. // TryRefreshDirtyRun and TryNarrowReloadRun both ask this, so they give one answer. // With run sets every GPU-written image goes the same way: a whole refresh is forbidden for any of them. + private long _aliasRunWidened; + private bool NarrowRefreshPastHalf(MetalCachedImage image) => image.IsGpuModified && (image.RunCapacity > 1 || (LayerDeferEnabled && image.Description.IsLayered)); From 3feeb7b128ca7fdde80dd5e146440c75be42a0f6 Mon Sep 17 00:00:00 2001 From: kuba Date: Sun, 15 Nov 2026 07:28:27 +0000 Subject: [PATCH 038/178] [Metal] SHARPEMU_METAL_V2_UPLOAD_TRACE=1: name the images uploaded again and again, by cause --- .../V2/MetalImageCache.UploadTrace.cs | 83 +++++++++++++++++++ .../SharpEmu.Gpu.Metal/V2/MetalImageCache.cs | 2 + .../SharpEmu.Gpu.Metal/V2/MetalRenderHost.cs | 1 + 3 files changed, 86 insertions(+) create mode 100644 src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.UploadTrace.cs diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.UploadTrace.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.UploadTrace.cs new file mode 100644 index 000000000..25b32919c --- /dev/null +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.UploadTrace.cs @@ -0,0 +1,83 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using System.Text; + +namespace SharpEmu.Gpu.Metal.V2; + +// SHARPEMU_METAL_V2_UPLOAD_TRACE=1: which images are uploaded again and again, and why. The CHURN line counts +// uploads by cause only; a texture the guest's CPU rewrites every frame, or one an unrelated write keeps +// invalidating, costs an upload and often an ended render pass each time, and only its address says which it is. +// One [METAL-V2][UPLOAD-TRACE] line per report interval: the images with the most uploaded bytes whose cause is +// not an alias run (those have their own trace), with count, bytes, cause, format, extent, levels and address. +internal sealed partial class MetalImageCache +{ + private static readonly bool UploadTraceEnabled = + Environment.GetEnvironmentVariable("SHARPEMU_METAL_V2_UPLOAD_TRACE") == "1"; + + private readonly Dictionary<(ulong Address, ulong Size, MetalImageDirtyCause Cause, bool Run), (long Count, long Bytes, string Shape)> + _uploadTrace = []; + + private void NoteUploadForTrace(MetalCachedImage image, MetalImageDirtyCause cause, ulong bytes, bool run) + { + if (!UploadTraceEnabled || cause == MetalImageDirtyCause.AliasWrite) + { + return; + } + + ref readonly var description = ref image.Description; + var key = (description.Data.Address, description.Data.Size, cause, run); + lock (_uploadTrace) + { + if (_uploadTrace.TryGetValue(key, out var seen)) + { + _uploadTrace[key] = (seen.Count + 1, seen.Bytes + (long)bytes, seen.Shape); + } + else + { + _uploadTrace[key] = (1, (long)bytes, + $"{description.PixelFormat} {description.Extent.Width}x{description.Extent.Height} " + + $"levels={description.Resources.Levels} layers={description.TransferLayers} tile={description.TileMode}"); + } + } + } + + /// Writes the interval's upload trace line, if the trace is on and anything was uploaded; resets it. + internal void WriteUploadTrace() + { + if (!UploadTraceEnabled) + { + return; + } + + var text = new StringBuilder(); + lock (_uploadTrace) + { + if (_uploadTrace.Count == 0) + { + return; + } + + long uploads = 0, total = 0; + foreach (var entry in _uploadTrace.Values) + { + uploads += entry.Count; + total += entry.Bytes; + } + + text.Append($"[METAL-V2][UPLOAD-TRACE] images={_uploadTrace.Count} uploads={uploads} mb={total / (1024.0 * 1024.0):F1} top=["); + var shown = 0; + foreach (var (key, entry) in _uploadTrace.OrderByDescending(pair => pair.Value.Bytes).Take(12)) + { + text.Append(shown++ == 0 ? string.Empty : "; "); + text.Append($"n={entry.Count} kb={entry.Bytes / 1024} cause={key.Cause}{(key.Run ? " run" : string.Empty)} " + + $"{entry.Shape} addr=0x{key.Address:X}+0x{key.Size:X}"); + } + + text.Append(']'); + _uploadTrace.Clear(); + } + + Console.Error.WriteLine(text.ToString()); + } +} diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.cs index 62322dd69..cfceb9fc4 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.cs @@ -2861,6 +2861,7 @@ private void RefreshFromGuestCore(MetalCachedImage image) } _uploadCauses[(int)image.DirtyCause]++; + NoteUploadForTrace(image, image.DirtyCause, residentEnd - residentStart, run: false); if (context.WantsEncodedLabels) { context.ProfileEncoded(ProfileLabel("upload", in description)); @@ -2957,6 +2958,7 @@ private bool TryRefreshDirtyRun(MetalCachedImage image) } _uploadCauses[(int)cause]++; + NoteUploadForTrace(image, cause, end - start, run: true); _partialUploads++; _partialUploadBytesSaved += (long)(residentEnd - residentStart - (end - start)); if (context.WantsEncodedLabels) diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.cs index 69ec0a00e..8399c593d 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.cs @@ -2877,6 +2877,7 @@ public void ReportCounters() } WriteCopyReadTraces(); + _imageCache.WriteUploadTrace(); var causes = _imageCache.TakeTransferCauses(); var subRange = _imageCache.TakePartialTransfers(); var aliases = _imageCache.AliasCounters; From d0e3ebfbf626e937062806090a8b24db47bde4ab Mon Sep 17 00:00:00 2001 From: kuba Date: Sun, 15 Nov 2026 07:57:21 +0000 Subject: [PATCH 039/178] [Tests] Pin the image run sets: merges, cuts, full sets, writebacks, device alias copy Test hook: MetalImageCache.DeviceAliasPublishEnabled is an instance setting. --- .../SharpEmu.Gpu.Metal/V2/MetalImageCache.cs | 3 +- .../MetalCachedImageRunSetTests.cs | 531 ++++++++++++++++++ .../MetalImageAliasTests.RunSetHardening.cs | 327 +++++++++++ 3 files changed, 860 insertions(+), 1 deletion(-) create mode 100644 tests/SharpEmu.Gpu.Metal.Tests/MetalCachedImageRunSetTests.cs create mode 100644 tests/SharpEmu.Gpu.Metal.Tests/MetalImageAliasTests.RunSetHardening.cs diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.cs index cfceb9fc4..013c7b1db 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.cs @@ -2178,7 +2178,8 @@ private bool TryPublishAliasOnDevice(MetalCachedImage image, MetalCachedImage ot // (MetalImageTransfer.TryEncodeTextureToTexture): neither transfer converts anything // for those pairs, so texel for texel the target gets exactly the bits the round trip // would have detiled into it. - private static readonly bool DeviceAliasPublishEnabled = + // Test hook: an instance setting, so a test runs the same pair with the device copy off. + internal bool DeviceAliasPublishEnabled { get; set; } = Environment.GetEnvironmentVariable("SHARPEMU_METAL_V2_ALIAS_ON_DEVICE") != "0"; // Publishes just the shared bytes of a GPU-written image, leaving the texture diff --git a/tests/SharpEmu.Gpu.Metal.Tests/MetalCachedImageRunSetTests.cs b/tests/SharpEmu.Gpu.Metal.Tests/MetalCachedImageRunSetTests.cs new file mode 100644 index 000000000..28c316fc1 --- /dev/null +++ b/tests/SharpEmu.Gpu.Metal.Tests/MetalCachedImageRunSetTests.cs @@ -0,0 +1,531 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using SharpEmu.Gpu.Metal.V2; +using SharpEmu.HLE.GpuMemory; +using SharpEmu.Libs.Gpu.Abstractions; +using SharpEmu.Libs.Gpu.Images; +using Xunit; + +namespace SharpEmu.Gpu.Metal.Tests; + +/// +/// The stale-run and published-run sets of a cached image (MetalCachedImage.StaleRuns / PublishedRuns, at most +/// MaxRuns of each with run sets on, one interval each with them off), exercised on an image with no texture: no +/// device is needed. Each case pins what the code does today, including what a full set does. +/// +public sealed class MetalCachedImageRunSetTests +{ + private const ulong Size = 0x10000; + + private static MetalCachedImage CreateImage(int capacity, out MetalRunSetStats stats, bool clean = true) + { + var description = ImageDescription.Create(); + description.PixelFormat = GpuFormat.R8G8B8A8Unorm; + description.BytesPerBlock = 4; + description.Pitch = 1; + description.Data = new GuestSpan(0x2_0000_0000, Size); + var shape = new MetalTextureShape( + MtlFormat.Rgba8Unorm, Mtl.TextureType2D, 1, 1, 1, 1, 1, 1, Mtl.TextureUsageShaderRead); + stats = new MetalRunSetStats(); + var image = new MetalCachedImage(in description, in shape, 0) { RunCapacity = capacity, RunStats = stats }; + if (clean) + { + // A new image is stale over all of it; the cases below start from a current one. + image.RefreshComplete(); + } + + return image; + } + + private static MetalCachedImage Clean(int capacity = MetalCachedImage.MaxRuns) => CreateImage(capacity, out _); + + private static (ulong Start, ulong End)[] Stale(MetalCachedImage image) => image.StaleRuns.ToArray(); + + private static (ulong Start, ulong End)[] Published(MetalCachedImage image) => image.PublishedRuns.ToArray(); + + private static void Dirty(MetalCachedImage image, ulong start, ulong end) => + image.MarkCpuDirty(MetalImageDirtyCause.CpuWrite, start, end); + + // ---- stale runs: marking ---- + + [Fact] + public void TouchingStaleRunsMergeIntoOne() + { + var image = Clean(); + Dirty(image, 0x1000, 0x2000); + Dirty(image, 0x2000, 0x3000); + Assert.Equal([(0x1000UL, 0x3000UL)], Stale(image)); + + // Touching at the front as well. + Dirty(image, 0x0800, 0x1000); + Assert.Equal([(0x0800UL, 0x3000UL)], Stale(image)); + } + + [Fact] + public void RunsOneByteApartStayApart() + { + var image = Clean(); + Dirty(image, 0x1000, 0x2000); + Dirty(image, 0x2001, 0x3000); + Assert.Equal([(0x1000UL, 0x2000UL), (0x2001UL, 0x3000UL)], Stale(image)); + } + + [Fact] + public void OverlappingStaleRunsMergeAndAWideRunAbsorbsEveryRunItCovers() + { + var image = Clean(); + Dirty(image, 0x1000, 0x3000); + Dirty(image, 0x2000, 0x4000); + Assert.Equal([(0x1000UL, 0x4000UL)], Stale(image)); + + Dirty(image, 0x8000, 0x9000); + Dirty(image, 0xA000, 0xB000); + Assert.Equal(3, image.StaleRunCount); + Dirty(image, 0x3000, 0xA800); + Assert.Equal([(0x1000UL, 0xB000UL)], Stale(image)); + } + + [Fact] + public void DisjointStaleRunsStayApartAndSorted() + { + var image = Clean(); + Dirty(image, 0x8000, 0x9000); + Dirty(image, 0x1000, 0x2000); + Dirty(image, 0x4000, 0x5000); + Assert.Equal([(0x1000UL, 0x2000UL), (0x4000UL, 0x5000UL), (0x8000UL, 0x9000UL)], Stale(image)); + Assert.Equal(0x1000UL, image.DirtyStart); + Assert.Equal(0x9000UL, image.DirtyEnd); + Assert.True(image.IsStaleOver(0x4000, 0x5000)); + Assert.False(image.IsStaleOver(0x1000, 0x5000)); + Assert.True(image.StaleOverlaps(0x1800, 0x4800)); + Assert.False(image.StaleOverlaps(0x2000, 0x4000)); + } + + [Fact] + public void AStaleRunInsideARunChangesNothing() + { + var image = Clean(); + Dirty(image, 0x1000, 0x5000); + var version = image.BindingVersion; + Dirty(image, 0x2000, 0x3000); + Assert.Equal([(0x1000UL, 0x5000UL)], Stale(image)); + Assert.Equal(version, image.BindingVersion); + } + + [Fact] + public void WithRunSetsOffASecondStaleRunWidensTheOneInterval() + { + var image = Clean(capacity: 1); + Dirty(image, 0x1000, 0x2000); + Dirty(image, 0x8000, 0x9000); + Assert.Equal([(0x1000UL, 0x9000UL)], Stale(image)); + } + + [Fact] + public void ACleanImageMarkedStaleHoldsExactlyThatRun() + { + var image = Clean(); + Assert.False(image.IsCpuDirty); + Dirty(image, 0x2000, 0x2000 + 0x100); + Assert.True(image.IsCpuDirty); + Assert.Equal([(0x2000UL, 0x2100UL)], Stale(image)); + // Marked past the end: clamped to the image; an empty range marks nothing. + var other = Clean(); + Dirty(other, Size - 0x100, Size + 0x4000); + Assert.Equal([(Size - 0x100, Size)], Stale(other)); + var none = Clean(); + Dirty(none, Size, Size + 0x100); + Assert.False(none.IsCpuDirty); + } + + // ---- stale runs: a fifth disjoint run on a full set ---- + + private static MetalCachedImage FullStaleSet(out MetalRunSetStats stats, bool gpuModified = false) + { + var image = CreateImage(MetalCachedImage.MaxRuns, out stats); + if (gpuModified) + { + image.MarkGpuModified(); + } + + Dirty(image, 0x0000, 0x0100); + Dirty(image, 0x1000, 0x1100); + Dirty(image, 0x2000, 0x2100); + Dirty(image, 0x3000, 0x3100); + Assert.Equal(MetalCachedImage.MaxRuns, image.StaleRunCount); + return image; + } + + // The documented outcome of MetalCachedImage.MergeClosest: the two runs with the least between them become one + // and the bytes between them are marked stale too. The cache never lets a GPU-written image get here + // (CanAddStaleRun), so for an image the texture owns nothing of it is exact, and counted. + [Fact] + public void AFifthDisjointStaleRunMergesTheTwoClosestAndCountsIt() + { + var image = FullStaleSet(out var stats); + Assert.False(image.CanAddStaleRun(0x5000, 0x5100)); + + Dirty(image, 0x3180, 0x3200); + + Assert.Equal( + [(0x0000UL, 0x0100UL), (0x1000UL, 0x1100UL), (0x2000UL, 0x2100UL), (0x3000UL, 0x3200UL)], Stale(image)); + var counts = stats.Read(); + Assert.Equal(1, counts.Merged); + Assert.Equal(0, counts.Unpublished); + Assert.Equal(MetalCachedImage.MaxRuns, (int)counts.SetsMax); + } + + // With every gap the same the earlier pair is merged (the closest is replaced only by a strictly smaller gap). + [Fact] + public void AFifthStaleRunWithEveryGapEqualMergesTheFirstPair() + { + var image = FullStaleSet(out var stats); + + Dirty(image, 0x4000, 0x4100); + + Assert.Equal([(0x0000UL, 0x1100UL), (0x2000UL, 0x2100UL), (0x3000UL, 0x3100UL), (0x4000UL, 0x4100UL)], Stale(image)); + Assert.Equal(1, stats.Read().Merged); + } + + // A GPU-written image whose set is full and is merged anyway: counted as an unpublished merge (the bug counter + // the run-set tests keep at 0), and the bytes between the two runs are stale now. + [Fact] + public void AMergeOnAGpuWrittenImageCountsAsUnpublished() + { + var image = FullStaleSet(out var stats, gpuModified: true); + Assert.True(image.IsGpuModified); + + Dirty(image, 0x4000, 0x4100); + + Assert.Equal(4, image.StaleRunCount); + var counts = stats.Read(); + Assert.Equal(1, counts.Merged); + Assert.Equal(1, counts.Unpublished); + } + + // ---- stale runs: cutting ---- + + [Fact] + public void AFreshImageRefreshedOverItsFrontLeavesTheRest() + { + var image = CreateImage(MetalCachedImage.MaxRuns, out _, clean: false); + Assert.Equal([(0UL, Size)], Stale(image)); + image.RefreshComplete(0, 0x4000); + Assert.Equal([(0x4000UL, Size)], Stale(image)); + Assert.True(image.IsCpuDirty); + } + + [Fact] + public void AFreshImageRefreshedOverItsBackLeavesTheRest() + { + var image = CreateImage(MetalCachedImage.MaxRuns, out _, clean: false); + image.RefreshComplete(Size - 0x4000, Size); + Assert.Equal([(0UL, Size - 0x4000)], Stale(image)); + } + + [Fact] + public void AFreshImageRefreshedOverItsMiddleHoldsTwoRuns() + { + var image = CreateImage(MetalCachedImage.MaxRuns, out var stats, clean: false); + image.RefreshComplete(0x4000, 0x6000); + Assert.Equal([(0UL, 0x4000UL), (0x6000UL, Size)], Stale(image)); + Assert.Equal(2, (int)stats.Read().SetsMax); + Assert.True(image.IsStaleOver(0, 0x4000)); + Assert.False(image.IsStaleOver(0x3000, 0x7000)); + } + + [Fact] + public void ARefreshOverAWholeImageOrAllItsRunsLeavesNothingStale() + { + var fresh = CreateImage(MetalCachedImage.MaxRuns, out _, clean: false); + fresh.RefreshComplete(0, Size); + Assert.False(fresh.IsCpuDirty); + Assert.Equal(0, fresh.StaleRunCount); + + // The span of every run clears them all, whatever lies between them. + var image = Clean(); + Dirty(image, 0x2000, 0x3000); + Dirty(image, 0x6000, 0x7000); + image.RefreshComplete(0x1000, 0x8000); + Assert.False(image.IsCpuDirty); + Assert.Equal(0, image.StaleRunCount); + } + + [Fact] + public void ARefreshOnACurrentImageIsIgnoredAndOneThatMissesAllRunsChangesNothing() + { + var current = Clean(); + var contentVersion = current.ContentVersion; + current.RefreshComplete(0, 0x1000); + Assert.Equal(contentVersion, current.ContentVersion); + Assert.False(current.IsCpuDirty); + + var image = Clean(); + Dirty(image, 0x2000, 0x3000); + Dirty(image, 0x6000, 0x7000); + var version = image.BindingVersion; + image.RefreshComplete(0x4000, 0x5000); + Assert.Equal([(0x2000UL, 0x3000UL), (0x6000UL, 0x7000UL)], Stale(image)); + Assert.Equal(version, image.BindingVersion); + } + + // With one interval a cut from the middle keeps the whole run (nothing becomes current that was not refreshed); + // a cut from the front or the back narrows it. + [Fact] + public void WithRunSetsOffAMiddleCutKeepsTheWholeRunAndAnEdgeCutNarrowsIt() + { + var middle = CreateImage(1, out _, clean: false); + middle.RefreshComplete(0x4000, 0x6000); + Assert.Equal([(0UL, Size)], Stale(middle)); + Assert.False(middle.CanCutStale(0x4000, 0x6000)); + + var front = CreateImage(1, out _, clean: false); + front.RefreshComplete(0, 0x4000); + Assert.Equal([(0x4000UL, Size)], Stale(front)); + + var back = CreateImage(1, out _, clean: false); + back.RefreshComplete(0xC000, Size + 0x1000); + Assert.Equal([(0UL, 0xC000UL)], Stale(back)); + } + + // The set is full: a middle cut would make a fifth run, so the run is kept whole. Exactly what the code does, + // and the invariant that matters: no byte that was stale and not refreshed stops being stale. + [Fact] + public void AMiddleCutOnAFullSetKeepsTheRunWholeAndLosesNoStaleByte() + { + var image = Clean(); + Dirty(image, 0x0000, 0x1000); + Dirty(image, 0x2000, 0x3000); + Dirty(image, 0x4000, 0x5000); + Dirty(image, 0x6000, 0xF000); + Assert.Equal(MetalCachedImage.MaxRuns, image.StaleRunCount); + Assert.False(image.CanCutStale(0x8000, 0x9000)); + Assert.True(image.CanCutStale(0x6000, 0x7000)); + var before = Stale(image); + + image.RefreshComplete(0x8000, 0x9000); + + Assert.Equal(before, Stale(image)); + Assert.True(image.IsStaleOver(0x8000, 0x9000)); + } + + [Theory] + [InlineData(0x0800UL, 0x0900UL)] + [InlineData(0x8000UL, 0x9000UL)] + [InlineData(0x0000UL, 0x0400UL)] + [InlineData(0x0C00UL, 0x2400UL)] + [InlineData(0x2800UL, 0x6800UL)] + [InlineData(0xE000UL, 0x10000UL)] + public void AnyCutOnAFullSetNeverMakesAnUnrefreshedStaleByteCurrent(ulong start, ulong end) + { + var image = Clean(); + Dirty(image, 0x0000, 0x1000); + Dirty(image, 0x2000, 0x3000); + Dirty(image, 0x4000, 0x5000); + Dirty(image, 0x6000, 0xF000); + var before = Stale(image); + + image.RefreshComplete(start, end); + + for (var at = 0UL; at < Size; at += 0x100) + { + var wasStale = before.Any(run => run.Start <= at && at < run.End); + var refreshed = start <= at && at < end; + if (wasStale && !refreshed) + { + Assert.True(image.StaleOverlaps(at, at + 1), $"byte 0x{at:X} was stale, not refreshed, and is current"); + } + + if (!wasStale) + { + Assert.False(image.StaleOverlaps(at, at + 1), $"byte 0x{at:X} was current and became stale"); + } + } + } + + [Fact] + public void ACutWithRoomMakesTwoRunsAndNoStaleByteBecomesCurrent() + { + var image = Clean(); + Dirty(image, 0x2000, 0x8000); + Dirty(image, 0xA000, 0xB000); + Assert.True(image.CanCutStale(0x4000, 0x5000)); + + image.RefreshComplete(0x4000, 0x5000); + + Assert.Equal([(0x2000UL, 0x4000UL), (0x5000UL, 0x8000UL), (0xA000UL, 0xB000UL)], Stale(image)); + } + + // ---- published runs ---- + + [Fact] + public void TouchingAndOverlappingPublishedRunsMergeAndDisjointOnesStayApartSorted() + { + var image = Clean(); + image.MarkGpuModified(); + image.MarkPublished(0x1000, 0x2000); + image.MarkPublished(0x2000, 0x3000); + Assert.Equal([(0x1000UL, 0x3000UL)], Published(image)); + image.MarkPublished(0x2800, 0x4000); + Assert.Equal([(0x1000UL, 0x4000UL)], Published(image)); + image.MarkPublished(0xA000, 0xB000); + image.MarkPublished(0x6000, 0x7000); + Assert.Equal([(0x1000UL, 0x4000UL), (0x6000UL, 0x7000UL), (0xA000UL, 0xB000UL)], Published(image)); + Assert.Equal(0x1000UL, image.PublishedStart); + Assert.Equal(0xB000UL, image.PublishedEnd); + Assert.False(image.IsPublished(0x1000, 0x7000)); + } + + // Four runs and a fifth: the shortest is forgotten, a tie dropping the later run. Forgetting a run only costs + // publishing it again. + [Fact] + public void AFifthPublishedRunOnAFullSetForgetsTheShortestAndTheLaterOnATie() + { + var image = Clean(); + image.MarkGpuModified(); + image.MarkPublished(0x0000, 0x0100); + image.MarkPublished(0x1000, 0x1200); + image.MarkPublished(0x2000, 0x2300); + image.MarkPublished(0x3000, 0x3400); + + image.MarkPublished(0x4000, 0x4100); + + Assert.Equal( + [(0x0000UL, 0x0100UL), (0x1000UL, 0x1200UL), (0x2000UL, 0x2300UL), (0x3000UL, 0x3400UL)], Published(image)); + + image.MarkPublished(0x5000, 0x5800); + + Assert.Equal( + [(0x1000UL, 0x1200UL), (0x2000UL, 0x2300UL), (0x3000UL, 0x3400UL), (0x5000UL, 0x5800UL)], Published(image)); + } + + [Fact] + public void WithRunSetsOffTwoDisjointPublishedRunsKeepTheLongerOne() + { + var image = Clean(capacity: 1); + image.MarkGpuModified(); + image.MarkPublished(0x1000, 0x1400); + image.MarkPublished(0x8000, 0x8100); + Assert.Equal([(0x1000UL, 0x1400UL)], Published(image)); + image.MarkPublished(0x8000, 0x9000); + Assert.Equal([(0x8000UL, 0x9000UL)], Published(image)); + } + + private static MetalCachedImage PublishedAt(int capacity, params (ulong Start, ulong End)[] runs) + { + var image = Clean(capacity); + image.MarkGpuModified(); + foreach (var (start, end) in runs) + { + image.MarkPublished(start, end); + } + + return image; + } + + [Fact] + public void ForgettingOverTheStartOfAPublishedRunKeepsTheRest() + { + var image = PublishedAt(4, (0x2000, 0x6000)); + image.ForgetPublished(0x1000, 0x3000); + Assert.Equal([(0x3000UL, 0x6000UL)], Published(image)); + Assert.False(image.IsPublished(0x2000, 0x3000)); + Assert.True(image.IsPublished(0x3000, 0x6000)); + } + + [Fact] + public void ForgettingOverTheEndOfAPublishedRunKeepsTheRest() + { + var image = PublishedAt(4, (0x2000, 0x6000)); + image.ForgetPublished(0x5000, 0x7000); + Assert.Equal([(0x2000UL, 0x5000UL)], Published(image)); + } + + [Fact] + public void ForgettingTheMiddleOfAPublishedRunMakesTwoRuns() + { + var image = PublishedAt(4, (0x2000, 0x6000)); + image.ForgetPublished(0x3000, 0x4000); + Assert.Equal([(0x2000UL, 0x3000UL), (0x4000UL, 0x6000UL)], Published(image)); + } + + [Fact] + public void ForgettingAllOfAPublishedRunOrMoreRemovesIt() + { + var image = PublishedAt(4, (0x2000, 0x6000), (0x8000, 0x9000)); + image.ForgetPublished(0x1000, 0x7000); + Assert.Equal([(0x8000UL, 0x9000UL)], Published(image)); + image.ForgetPublished(0, Size); + Assert.Equal(0, image.PublishedRuns.Length); + } + + [Theory] + [InlineData(0x0000UL, 0x2000UL)] + [InlineData(0x6000UL, 0x7000UL)] + [InlineData(0x7000UL, 0x8000UL)] + public void ForgettingARangeThatTouchesNothingChangesNothing(ulong start, ulong end) + { + var image = PublishedAt(4, (0x2000, 0x6000)); + var version = image.BindingVersion; + image.ForgetPublished(start, end); + Assert.Equal([(0x2000UL, 0x6000UL)], Published(image)); + Assert.Equal(version, image.BindingVersion); + } + + // Looks wrong: an empty range inside a run is not "nothing" - it splits the run in two touching runs, which + // the sorted-and-not-touching invariant of the set forbids. No caller passes an empty range today. + [Fact] + public void ForgettingAnEmptyRangeInsideARunSplitsItIntoTwoTouchingRuns() + { + var image = PublishedAt(4, (0x2000, 0x6000)); + image.ForgetPublished(0x3000, 0x3000); + Assert.Equal([(0x2000UL, 0x3000UL), (0x3000UL, 0x6000UL)], Published(image)); + } + + // A middle cut on a full set makes a fifth run: the shortest of the five is forgotten, a tie dropping the + // later one. Here the cut run's own two halves are the shortest. + [Fact] + public void ForgettingTheMiddleOfARunOnAFullSetForgetsTheShortestRun() + { + var image = PublishedAt( + 4, (0x0000, 0x1000), (0x2000, 0x3000), (0x4000, 0x5000), (0x6000, 0xA000)); + image.ForgetPublished(0x7000, 0x9000); + Assert.Equal( + [(0x0000UL, 0x1000UL), (0x2000UL, 0x3000UL), (0x4000UL, 0x5000UL), (0x6000UL, 0x7000UL)], Published(image)); + + // The half dropped is the later of two equal runs: (0x9000, 0xA000) not (0x6000, 0x7000). + Assert.False(image.IsPublished(0x9000, 0xA000)); + } + + [Fact] + public void WithRunSetsOffForgettingTheMiddleKeepsTheLongerSideAndATieTheEarlierOne() + { + var image = PublishedAt(1, (0x2000, 0x6000)); + image.ForgetPublished(0x2800, 0x3000); + Assert.Equal([(0x3000UL, 0x6000UL)], Published(image)); + + var longer = PublishedAt(1, (0x2000, 0x6000)); + longer.ForgetPublished(0x3000, 0x4000); + // Sides 0x1000 and 0x2000: the longer. + Assert.Equal([(0x4000UL, 0x6000UL)], Published(longer)); + + var equal = PublishedAt(1, (0x2000, 0x5000)); + equal.ForgetPublished(0x3000, 0x4000); + Assert.Equal([(0x2000UL, 0x3000UL)], Published(equal)); + } + + [Fact] + public void AGpuWriteDropsEveryStaleAndPublishedRun() + { + var image = Clean(); + image.MarkGpuModified(); + image.MarkPublished(0x1000, 0x2000); + Dirty(image, 0x4000, 0x5000); + Dirty(image, 0x8000, 0x9000); + image.MarkGpuModified(); + Assert.Equal(0, image.StaleRunCount); + Assert.False(image.IsCpuDirty); + Assert.Equal(0, image.PublishedRuns.Length); + } +} diff --git a/tests/SharpEmu.Gpu.Metal.Tests/MetalImageAliasTests.RunSetHardening.cs b/tests/SharpEmu.Gpu.Metal.Tests/MetalImageAliasTests.RunSetHardening.cs new file mode 100644 index 000000000..470989b9c --- /dev/null +++ b/tests/SharpEmu.Gpu.Metal.Tests/MetalImageAliasTests.RunSetHardening.cs @@ -0,0 +1,327 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using SharpEmu.Gpu.Metal.V2; +using SharpEmu.HLE.GpuMemory; +using SharpEmu.Libs.Gpu.Abstractions; +using SharpEmu.Libs.Gpu.Images; +using SharpEmu.Libs.Gpu.Rendering; +using Xunit; + +namespace SharpEmu.Gpu.Metal.Tests; + +// Run sets on the cache: the cases the run-set suite above leaves open - a full set under a CPU read, a whole and a +// partial writeback of an image that is stale over two runs, and a whole-range device alias copy into an image that +// owns a published run. Each runs with run sets (or device publishing) on and off and must end bit-identical. +public sealed unsafe partial class MetalImageAliasTests +{ + // What guest memory holds when every alias's run came from the alias and the rest from the large texture. + private static byte[] ExpectedAfterDraws((ulong Offset, uint Rows)[] draws) + { + var expected = MetalTileOracle.Pattern((int)LargeSize, 0x5A); + byte seed = 0x11; + foreach (var (offset, rows) in draws) + { + var size = (int)(rows * LargeSide * 4); + MetalTileOracle.Pattern(size, seed).CopyTo(expected, (int)offset); + seed += 0x22; + } + + return expected; + } + + // Five aliases apart from each other on a full set, then a CPU read: the fifth merges only by publishing the + // image first, so guest memory holds each alias's bytes over its run and the large texture's elsewhere, and + // nothing is merged over bytes only the texture held. + [Fact] + public void AFifthDisjointAliasOnAFullSetLeavesGuestMemoryAndTexturesExactlyAsWithRunSetsOff() + { + if (!RequireDevice()) return; + (ulong Offset, uint Rows)[] draws = [(0, 4), (0x800, 4), (0x1000, 4), (0x1800, 4), (0x2000, 4)]; + var outcomes = OnAndOff(draws, cpuReadFirst: true); + var expected = ExpectedAfterDraws(draws); + Assert.Equal(MetalCachedImage.MaxRuns, (int)outcomes[0].Runs.SetsMax); + Assert.True(outcomes[0].Runs.Merged >= 1); + Assert.Equal(0, outcomes[0].Runs.Unpublished); + foreach (var outcome in outcomes) + { + Assert.Equal(expected, outcome.GuestBeforeRead); + Assert.Equal(expected, outcome.Guest); + Assert.Equal(expected, outcome.Large); + } + } + + // A whole writeback (the host reads all of it) of a GPU-modified image that is stale over two runs: guest memory + // over each run is the alias's newer bytes, never the large texture's older ones. + [Fact] + public void AWholeWritebackOverTwoStaleRunsNeverReplacesThemWithOlderTexels() + { + if (!RequireDevice()) return; + (ulong Offset, uint Rows)[] draws = [(0x1000, AliasRows), (0x3000, AliasRows)]; + var outcomes = OnAndOff(draws, cpuReadFirst: true); + var expected = ExpectedAfterDraws(draws); + foreach (var outcome in outcomes) + { + Assert.Equal(expected, outcome.GuestBeforeRead); + Assert.Equal(expected, outcome.Guest); + Assert.Equal(expected, outcome.Large); + } + } + + // A run writeback: the host reads only a range over one stale run (and the bytes round it), and the range is + // flushed alone. Whatever the flushed range holds over a run is the alias's, with run sets on and off alike, and + // the whole of guest memory is identical between the two arms. + private sealed record PartialFlushOutcome(byte[] Guest, byte[] Large, byte[] GuestFinal, string Text); + + private static PartialFlushOutcome PartialFlushOverTwoRuns(bool runSets, ulong flushOffset, ulong flushSize) + { + using var rig = new Rig(Device.Value); + rig.Cache.AliasRunSetsEnabled = runSets; + var (image, _, _) = GpuWrittenLarge(rig); + var first = DrawAlias(rig, 0x1000, AliasRows, 0x11); + var second = DrawAlias(rig, 0x3000, AliasRows, 0x33); + var text = $"runs={image.StaleRunCount} gpu={image.IsGpuModified} first_gpu={first.IsGpuModified} " + + $"second_gpu={second.IsGpuModified}"; + rig.Cache.FlushGpuWrites(ImageAddress + flushOffset, flushSize, MetalWritebackCause.HostRead); + rig.Harness.Submit(); + rig.Harness.Begin(); + var guest = rig.ReadGuest(ImageAddress, LargeSize); + rig.Acquire(ImageAddress, LargeSide, ImageRole.Texture); + rig.Harness.Submit(); + rig.Harness.Begin(); + var large = ReadTexture(rig, image); + rig.Cache.FlushGpuWrites(ImageAddress, LargeSize, MetalWritebackCause.HostRead); + rig.Harness.Submit(); + rig.Harness.Begin(); + var final = rig.ReadGuest(ImageAddress, LargeSize); + Assert.Equal(0, rig.Cache.AliasRunRefreshRefused); + Assert.Equal(0, rig.Cache.AliasRunCounters.Unpublished); + return new PartialFlushOutcome(guest, large, final, text + " " + rig.Cache.TakeAliasTransitionText()); + } + + [Theory] + [InlineData(0x1000UL, 0x1000UL, "exactly the first run")] + [InlineData(0x0800UL, 0x2000UL, "the first run and the bytes round it")] + [InlineData(0x3000UL, 0x1000UL, "exactly the second run")] + [InlineData(0x1000UL, 0x3000UL, "both runs and the gap")] + public void ARunWritebackOverStaleRunsNeverReplacesThemWithOlderTexels(ulong flushOffset, ulong flushSize, string name) + { + if (!RequireDevice()) return; + var on = PartialFlushOverTwoRuns(runSets: true, flushOffset, flushSize); + var off = PartialFlushOverTwoRuns(runSets: false, flushOffset, flushSize); + output.WriteLine($"{name}: on: {on.Text}"); + output.WriteLine($"{name}: off: {off.Text}"); + // Only the flushed range is promised right away (run sets on leaves the rest of the image GPU-modified, + // off wrote it back whole at the hand-over); once everything is flushed the arms agree exactly. + var expected = ExpectedAfterDraws([(0x1000, AliasRows), (0x3000, AliasRows)]); + Assert.Equal(off.GuestFinal, on.GuestFinal); + Assert.Equal(expected, on.GuestFinal); + Assert.Equal(off.Large, on.Large); + Assert.Equal(expected, on.Large); + + // Over each run the flushed range covers, guest memory holds the alias's bytes. The alias's drawn pattern is + // the newest; the large texture's older pattern must not be there. + var older = MetalTileOracle.Pattern((int)LargeSize, 0x5A); + var runs = new[] { (Offset: 0x1000UL, Seed: (byte)0x11), (Offset: 0x3000UL, Seed: (byte)0x33) }; + foreach (var arm in new[] { on, off }) + { + foreach (var (runStart, seed) in runs) + { + var from = Math.Max(runStart, flushOffset); + var to = Math.Min(runStart + SmallSize, flushOffset + flushSize); + if (to <= from) + { + continue; + } + + var drawn = MetalTileOracle.Pattern((int)SmallSize, seed); + var guest = arm.Guest.AsSpan((int)from, (int)(to - from)).ToArray(); + var stale = MetalTileOracle.Pattern((int)LargeSize, 0xC3).AsSpan((int)from, (int)(to - from)).ToArray(); + output.WriteLine($"run 0x{runStart:X}: drawn={guest.SequenceEqual(drawn.AsSpan((int)(from - runStart), (int)(to - from)).ToArray())} " + + $"older={guest.SequenceEqual(older.AsSpan((int)from, (int)(to - from)).ToArray())} stale={guest.SequenceEqual(stale)}"); + Assert.Equal(drawn.AsSpan((int)(from - runStart), (int)(to - from)).ToArray(), guest); + Assert.NotEqual(older.AsSpan((int)from, (int)(to - from)).ToArray(), guest); + } + } + } + + // ---- a whole-range device alias copy into a GPU-modified target that owns a published run ---- + + // Depth values a 32-bit depth plane keeps bit for bit (floats in [0, 1)), as guest bytes. + private static byte[] DepthPattern(int size, int seed) + { + var bytes = new byte[size]; + for (var index = 0; index < size / 4; index++) + { + BitConverter.TryWriteBytes(bytes.AsSpan(index * 4), ((index * 31 + seed) % 1000) / 1000f); + } + + return bytes; + } + + private const uint DepthWidth = 128; + private const uint DepthHeight = 64; + + // A 32-bit depth plane (D32) or its single-channel R32 alias over the same bytes, Depth tile mode: the pair the + // device hands over (MetalImageTransfer.IsDepth32ToColorAlias), switched off by DeviceAliasPublishEnabled. + private static ImageRequest Depth32Request(ImageRole role) + { + var depthRole = role == ImageRole.DepthTarget; + Assert.True(TileGeometry.TryGetDepthSize(DepthWidth, DepthHeight, 0, GuestDepthFormat.Z32Float, + GuestStencilFormat.Invalid, false, out _, out _, out var depthSize)); + var pitch = TileGeometry.DepthPitch(DepthWidth, 4); + var description = ImageDescription.Create(); + description.Data = new GuestSpan(ImageAddress, depthSize.Size); + var format = depthRole ? GpuFormat.D32Sfloat : GpuFormat.R32Sfloat; + description.PixelFormat = format; + description.GuestFormat = GuestPixelFormat.Bits32Float; + description.Type = GuestImageType.Color2D; + description.Extent = new GpuExtent3D(DepthWidth, DepthHeight, 1); + description.Resources = new SubresourceCount(1, 1); + description.Pitch = pitch; + description.BytesPerBlock = 4; + description.Samples = 1; + description.TileMode = GuestTileMode.Depth; + description.MipLayout[0] = new MipLevelLayout + { + Offset = 0, Size = depthSize.Size, Pitch = pitch, Height = DepthHeight, + }; + var view = ImageViewDescription.Default with + { + Format = format, + Type = GpuImageViewType.Type2D, + Aspect = depthRole ? GpuImageAspect.DepthBit : GpuImageAspect.ColorBit, + LayerCount = 1, + Usage = depthRole ? GpuImageUsage.DepthStencilAttachmentBit : GpuImageUsage.SampledBit, + }; + return new ImageRequest(description, view, role); + } + + private sealed record DeviceAliasOutcome( + byte[] GuestBeforeFlush, byte[] GuestAfterFlush, byte[] Target, long DevicePublishes, bool TargetGpuModified, + int TargetPublishedRuns, bool PublishedOverCopy, byte[] Newer); + + // The D32 plane S is GPU-written; its R32 alias T (the target) is GPU-modified too and owns a published run (the + // first half of it, as a partial writeback would leave). S is then written again - its texture gets new bytes, + // guest memory still holds older ones - and T is sampled: the whole range is copied S -> T. + private static DeviceAliasOutcome RunDeviceAliasIntoPublishedTarget(bool deviceOn, bool targetOwns = true) + { + using var rig = new Rig(Device.Value); + rig.Cache.DepthTwins = false; + rig.Cache.DeviceAliasPublishEnabled = deviceOn; + var depthRequest = Depth32Request(ImageRole.DepthTarget); + var textureRequest = Depth32Request(ImageRole.Texture); + var size = depthRequest.Description.Data.Size; + + rig.WriteGuest(ImageAddress, DepthPattern((int)size, 0x5A)); + var depthId = rig.Cache.FindImage(ref depthRequest); + rig.Cache.AcquireDepthTargetView(depthId, in depthRequest); + var source = rig.Cache.GetImage(depthId); + Assert.True(source.IsGpuModified); + rig.Harness.Submit(); + rig.Harness.Begin(); + + var targetId = rig.Cache.FindImage(ref textureRequest); + Assert.NotEqual(depthId, targetId); + rig.Cache.AcquireTextureView(targetId, in textureRequest); + var target = rig.Cache.GetImage(targetId); + rig.Harness.Submit(); + rig.Harness.Begin(); + + // The target is GPU-modified and has published its first half. + if (targetOwns) + { + target.MarkGpuModified(); + target.MarkPublished(0, size / 2); + Assert.True(target.IsPublished(0, size / 2)); + } + + // The source's texture gets newer bytes than guest memory holds, and is the later writer. + var newer = DepthPattern((int)size, 0xC3); + rig.Harness.Transfer.EncodeGuestToTexture( + rig.Harness, source.Description, new SubresourceRange(0, 1, 0, 1), + new MetalGuestRange(rig.Harness.Buffer(newer), 0, size, 0), default, source.Texture, 0, size); + rig.Harness.Submit(); + rig.Harness.Begin(); + // The texture's own texels in guest layout: bytes of the 64 KiB tile block that carry no texel come back as + // zero, so the newer guest bytes cannot be compared whole. + var newerBack = ReadTexture(rig, source); + source.MarkGpuModified(); + rig.WriteGuest(ImageAddress, DepthPattern((int)size, 0x33)); + _ = rig.Cache.TakeDeviceAliasPublishes(); + + rig.Cache.AcquireTextureView(targetId, in textureRequest); + rig.Harness.Submit(); + rig.Harness.Begin(); + + var publishes = rig.Cache.TakeDeviceAliasPublishes(); + var before = rig.ReadGuest(ImageAddress, size); + var runs = target.PublishedRuns.Length; + var publishedOverCopy = target.IsPublished(0, 1) || target.IsPublished(size - 1, size); + var modified = target.IsGpuModified; + rig.Cache.FlushGpuWrites(ImageAddress, size, MetalWritebackCause.HostRead); + rig.Harness.Submit(); + rig.Harness.Begin(); + var after = rig.ReadGuest(ImageAddress, size); + var targetBytes = ReadTexture(rig, target); + return new DeviceAliasOutcome(before, after, targetBytes, publishes, modified, runs, publishedOverCopy, newerBack); + } + + // Texel bytes of the source's newer content (its non-zero bytes), the part of a 64 KiB tile block that is written + // back; the rest reads back as whatever the buffer held. + private static int[] TexelIndices(byte[] newer) => + Enumerable.Range(0, newer.Length).Where(index => newer[index] != 0).ToArray(); + + private static int Differing(int[] texels, byte[] expected, byte[] actual) => + texels.Count(index => actual[index] != expected[index]); + + // After the copy the target has no published run over the copied bytes, and guest memory after the flush holds + // the source's newer texels - the same as the path where the device copy is off and the target owns nothing + // (the baseline: with the copy off, a target that owns older texels is the next test). + [Fact] + public void ADeviceCopyIntoAGpuModifiedTargetLeavesNoPublishedRunOverTheCopiedBytes() + { + if (!RequireDevice()) return; + var on = RunDeviceAliasIntoPublishedTarget(deviceOn: true); + var baseline = RunDeviceAliasIntoPublishedTarget(deviceOn: false, targetOwns: false); + output.WriteLine($"on: publishes={on.DevicePublishes} gpu={on.TargetGpuModified} runs={on.TargetPublishedRuns} " + + $"| baseline: publishes={baseline.DevicePublishes} gpu={baseline.TargetGpuModified} runs={baseline.TargetPublishedRuns}"); + + Assert.Equal(1, on.DevicePublishes); + Assert.Equal(0, baseline.DevicePublishes); + Assert.Equal(0, on.TargetPublishedRuns); + Assert.False(on.PublishedOverCopy); + Assert.True(on.TargetGpuModified); + + // The copy did not touch guest memory (the source still owes it its bytes). + var size = on.GuestAfterFlush.Length; + Assert.Equal(DepthPattern(size, 0x33), on.GuestBeforeFlush); + var texels = TexelIndices(on.Newer); + Assert.True(texels.Length > size / 8); + foreach (var arm in new[] { on, baseline }) + { + Assert.Equal(0, Differing(texels, on.Newer, arm.Newer)); + Assert.Equal(0, Differing(texels, on.Newer, arm.GuestAfterFlush)); + Assert.Equal(0, Differing(texels, on.Newer, arm.Target)); + } + } + + // Looks wrong, pinned: with the device copy off, a target that is GPU-modified with older texels and a + // published first half, sampled over a source that is GPU-modified with newer ones (a state the cache's own + // transitions do not reach: taking GPU ownership clears the other image's), is not reloaded from the guest bytes + // the source was just published into, and its flush writes its older texels over them. The device copy leaves + // no such state (the test above). + [Fact] + public void WithTheDeviceCopyOffATargetOwningOlderTexelsOverwritesTheNewerGuestBytesAtTheFlush() + { + if (!RequireDevice()) return; + var off = RunDeviceAliasIntoPublishedTarget(deviceOn: false); + var texels = TexelIndices(off.Newer); + Assert.Equal(0, off.DevicePublishes); + // Published into guest memory by the sync, before the flush. + Assert.Equal(0, Differing(texels, off.Newer, off.GuestBeforeFlush)); + // Then the target's older texels replace them. + Assert.True(Differing(texels, off.Newer, off.GuestAfterFlush) > texels.Length / 2); + Assert.Equal(0, Differing(texels, off.Target, off.GuestAfterFlush)); + } +} From c8f15de970a74b7a4fc8a0c23e557707782aae45 Mon Sep 17 00:00:00 2001 From: kuba Date: Sun, 15 Nov 2026 07:57:21 +0000 Subject: [PATCH 040/178] [Tests] Pin the access stripes: double End, same-thread contract, busy drainer --- .../HostAccessStripesHardeningTests.cs | 265 ++++++++++++++++++ 1 file changed, 265 insertions(+) create mode 100644 tests/SharpEmu.Libs.Tests/Memory/GuestMemory/HostAccessStripesHardeningTests.cs diff --git a/tests/SharpEmu.Libs.Tests/Memory/GuestMemory/HostAccessStripesHardeningTests.cs b/tests/SharpEmu.Libs.Tests/Memory/GuestMemory/HostAccessStripesHardeningTests.cs new file mode 100644 index 000000000..ce6e92f3a --- /dev/null +++ b/tests/SharpEmu.Libs.Tests/Memory/GuestMemory/HostAccessStripesHardeningTests.cs @@ -0,0 +1,265 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using SharpEmu.HLE.Host; +using Xunit; + +namespace SharpEmu.Libs.Tests.Memory.GuestMemory; + +// What the per-thread access stripes do today at their edges: a token ended twice, an exit on another thread than +// its enter, and a drainer waiting while threads enter and exit without pause. Phantom backings: nothing touches +// the (fake) alias address. +// +// Production callers all enter and exit on one thread: the Metal resident-compare paths +// (MetalRenderHost.Pipelines / ConcurrentResolve) enter and exit around a try/finally in one method, +// SharedBackingViews enters and exits inside one call (its callers run on the calling thread, and every write +// receipt refuses another thread: OrdinaryBackingWriteReservation.RequireThread). No caller carries an enter to +// another thread, so only the same-thread contract is tested for them; the cross-thread balance of the signed sum +// itself is in HostAccessStripesTests.AnExitOnAnotherThreadStillBalancesTheSignedSum. +public sealed class HostAccessStripesHardeningTests +{ + private const int DormantLane = 1; + + private static HostBackingObject Phantom() => + new(0x10000, 4096, 4096, _ => new(HostBackingReleaseStatus.Released)); + + private static bool Applicable() => + HostBackingObject.AccessStripesEnabled && HostManagedWriteIntervals.DormantEnabled; + + // ---- a dormant-ledger token ended twice ---- + + // End does not notice: the second End of a dormant token decrements its cell again and reports success. The + // overdraft shows only as a negative sum, and only when something sums that lane - the first observer. + [Fact] + public void ADormantTokenEndedTwiceIsOnlyCaughtAsANegativeSumAtTheNextObserver() + { + if (!Applicable()) return; + var backing = Phantom(); + var messages = new List(); + backing.AliasStripes!.OnFatalForControl = messages.Add; + backing.EnrollManagedWrites(); + var writes = backing.ManagedWrites!; + var token = backing.BeginManagedWrite(0, 16); + Assert.Equal(HostManagedWriteIntervals.DormantSlot, token.Slot); + + Assert.True(writes.End(token, succeeded: true)); + Assert.True(writes.End(token, succeeded: true)); + Assert.Empty(messages); + + // The first observer sums the dormant lane: -1. + Assert.False(writes.TryCaptureRevision(out _)); + var message = Assert.Single(messages); + Assert.Contains("lane 1 sums to -1", message); + Assert.Equal(1, writes.ObservationRefusals); + } + + // The same overdraft with another dormant writer in flight sums to zero: the observer drains, and once it has + // (dormantDrained) nothing sums the lane again, so the overdraft is never reported by an observer - only a + // direct Sum sees it. + [Fact] + public void ADoubleEndMaskedByAnotherWriterIsNeverReportedOnceTheObserverHasDrained() + { + if (!Applicable()) return; + var backing = Phantom(); + var messages = new List(); + backing.AliasStripes!.OnFatalForControl = messages.Add; + backing.EnrollManagedWrites(); + var writes = backing.ManagedWrites!; + + var token = backing.BeginManagedWrite(0, 16); + HostManagedWriteIntervals.Token other = default; + using var begun = new ManualResetEventSlim(); + using var release = new ManualResetEventSlim(); + var thread = new Thread(() => + { + other = backing.BeginManagedWrite(16, 16); + begun.Set(); + release.Wait(); + Assert.True(writes.End(other, succeeded: true)); + }); + thread.Start(); + Assert.True(begun.Wait(TimeSpan.FromSeconds(10))); + Assert.Equal(HostManagedWriteIntervals.DormantSlot, other.Slot); + + Assert.True(writes.End(token, succeeded: true)); + Assert.True(writes.End(token, succeeded: true)); + + // -1 from the overdraft, +1 from the writer in flight. + Assert.True(writes.TryCaptureRevision(out _)); + Assert.Empty(messages); + + release.Set(); + Assert.True(thread.Join(TimeSpan.FromSeconds(10))); + + // The lane now sums to -1, and the observer never looks again. + Assert.True(writes.TryCaptureRevision(out _)); + Assert.Empty(messages); + Assert.Equal(-1, backing.AliasStripes.Sum(DormantLane)); + Assert.Single(messages); + } + + // A token ended once, on the thread that began it, leaves the dormant lane at zero and the observer unrefused. + [Fact] + public void ADormantTokenEndedOnceOnItsOwnThreadLeavesNoCount() + { + if (!Applicable()) return; + var backing = Phantom(); + backing.AliasStripes!.OnFatalForControl = message => throw new InvalidOperationException(message); + backing.EnrollManagedWrites(); + var writes = backing.ManagedWrites!; + var token = backing.BeginManagedWrite(0, 16); + Assert.Equal(backing.AliasStripes.CellForCurrentThread(DormantLane), token.DormantCell); + Assert.Equal(1, backing.AliasStripes.Sum(DormantLane)); + + Assert.True(writes.End(token, succeeded: true)); + + Assert.Equal(0, backing.AliasStripes.Sum(DormantLane)); + Assert.True(writes.TryCaptureRevision(out _)); + Assert.Equal(0, writes.ObservationRefusals); + } + + // ---- alias accesses: the same-thread contract ---- + + [Fact] + public void AnAliasAccessEntersAndExitsOnTheCallingThreadsStripe() + { + if (!HostBackingObject.AccessStripesEnabled) return; + var backing = Phantom(); + var stripes = backing.AliasStripes!; + stripes.OnFatalForControl = message => throw new InvalidOperationException(message); + + Assert.True(backing.TryEnterAliasAccess()); + Assert.Equal(1, backing.ActiveAccesses); + Assert.Equal(1, stripes.Sum(HostBackingObject.AliasLane)); + backing.ExitAliasAccess(); + + Assert.Equal(0, backing.ActiveAccesses); + Assert.Equal(0, stripes.Sum(HostBackingObject.AliasLane)); + } + + // A closing backing refuses the entry and backs its count out on the stripe it entered: balanced, no fatal. + [Fact] + public void AnEntryRefusedByCloseLeavesTheCountBalanced() + { + if (!HostBackingObject.AccessStripesEnabled) return; + var backing = Phantom(); + backing.AliasStripes!.OnFatalForControl = message => throw new InvalidOperationException(message); + backing.CloseAccess(); + + Assert.False(backing.TryEnterAliasAccess()); + + Assert.Equal(0, backing.ActiveAccesses); + Assert.Equal(0, backing.AliasStripes.Sum(HostBackingObject.AliasLane)); + } + + // ---- a drainer against ten threads entering and exiting continuously ---- + + // The stripes' own protocol: a drainer sets its flag with a full fence and sums; an entrant increments, re-reads + // the flag and backs out when it is set. The drainer's wait ends, and the sum it ends on is zero with no access + // left in flight and none admitted afterwards. + [Fact] + public void ADrainerOverTenBusyThreadsTerminatesAndSeesNoActiveAccess() + { + for (var round = 0; round < 10; round++) + { + var stripes = new HostAccessStripes(8); + stripes.OnFatalForControl = message => throw new InvalidOperationException(message); + var flag = 0; + var drained = 0; + var inFlight = 0; + var violations = 0; + var stop = 0; + using var started = new CountdownEvent(10); + var workers = Enumerable.Range(0, 10).Select(_ => new Thread(() => + { + started.Signal(); + while (Volatile.Read(ref stop) == 0) + { + var cell = stripes.Enter(0); + if (Volatile.Read(ref flag) != 0) + { + stripes.ExitCell(cell); + continue; + } + + Interlocked.Increment(ref inFlight); + if (Volatile.Read(ref drained) != 0) Interlocked.Increment(ref violations); + Thread.SpinWait(20); + Interlocked.Decrement(ref inFlight); + stripes.ExitCell(cell); + } + })).ToArray(); + foreach (var worker in workers) worker.Start(); + Assert.True(started.Wait(TimeSpan.FromSeconds(10))); + Thread.Sleep(5); + + Interlocked.Exchange(ref flag, 1); + var deadline = System.Diagnostics.Stopwatch.GetTimestamp() + 10 * System.Diagnostics.Stopwatch.Frequency; + while (stripes.Sum(0) != 0) + { + Assert.True(System.Diagnostics.Stopwatch.GetTimestamp() < deadline, "the drainer never saw zero"); + Thread.SpinWait(50); + } + + Assert.Equal(0, Volatile.Read(ref inFlight)); + Volatile.Write(ref drained, 1); + Thread.Sleep(5); + Volatile.Write(ref stop, 1); + foreach (var worker in workers) Assert.True(worker.Join(TimeSpan.FromSeconds(10))); + + Assert.Equal(0, violations); + Assert.Equal(0, stripes.Sum(0)); + Assert.Equal(0, stripes.Sum(1)); + } + } + + // The same through the backing: Close is the flag, ActiveAccesses the sum. + [Fact] + public void AClosedBackingOverTenBusyThreadsDrainsToZeroActiveAccesses() + { + if (!HostBackingObject.AccessStripesEnabled) return; + for (var round = 0; round < 10; round++) + { + var backing = Phantom(); + backing.AliasStripes!.OnFatalForControl = message => throw new InvalidOperationException(message); + var stop = 0; + var admittedAfterZero = 0; + var zeroSeen = 0; + long admitted = 0; + using var started = new CountdownEvent(10); + var workers = Enumerable.Range(0, 10).Select(_ => new Thread(() => + { + started.Signal(); + while (Volatile.Read(ref stop) == 0) + { + if (!backing.TryEnterAliasAccess()) continue; + Interlocked.Increment(ref admitted); + if (Volatile.Read(ref zeroSeen) != 0) Interlocked.Increment(ref admittedAfterZero); + Thread.SpinWait(20); + backing.ExitAliasAccess(); + } + })).ToArray(); + foreach (var worker in workers) worker.Start(); + Assert.True(started.Wait(TimeSpan.FromSeconds(10))); + while (Interlocked.Read(ref admitted) == 0) Thread.Yield(); + + backing.CloseAccess(); + var deadline = System.Diagnostics.Stopwatch.GetTimestamp() + 10 * System.Diagnostics.Stopwatch.Frequency; + while (backing.ActiveAccesses != 0) + { + Assert.True(System.Diagnostics.Stopwatch.GetTimestamp() < deadline, "the drain never saw zero"); + Thread.SpinWait(50); + } + + Volatile.Write(ref zeroSeen, 1); + Thread.Sleep(5); + Volatile.Write(ref stop, 1); + foreach (var worker in workers) Assert.True(worker.Join(TimeSpan.FromSeconds(10))); + + Assert.Equal(0, admittedAfterZero); + Assert.Equal(0, backing.ActiveAccesses); + Assert.False(backing.TryEnterAliasAccess()); + Assert.Equal(0, backing.ActiveAccesses); + } + } +} From 151638e4d958de0f646596ef4ab8410f24aca900 Mon Sep 17 00:00:00 2001 From: kuba Date: Sun, 15 Nov 2026 08:01:32 +0000 Subject: [PATCH 041/178] [Tests] Pin the meshlet cache at its budget: LRU eviction, pool overflow, pooled builds, version hits --- .../MetalMeshletCacheTests.Budget.cs | 323 ++++++++++++++++++ .../MetalMeshletCacheTests.cs | 2 +- 2 files changed, 324 insertions(+), 1 deletion(-) create mode 100644 tests/SharpEmu.Gpu.Metal.Tests/MetalMeshletCacheTests.Budget.cs diff --git a/tests/SharpEmu.Gpu.Metal.Tests/MetalMeshletCacheTests.Budget.cs b/tests/SharpEmu.Gpu.Metal.Tests/MetalMeshletCacheTests.Budget.cs new file mode 100644 index 000000000..352d08af9 --- /dev/null +++ b/tests/SharpEmu.Gpu.Metal.Tests/MetalMeshletCacheTests.Budget.cs @@ -0,0 +1,323 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using SharpEmu.Gpu.Metal.V2; +using Xunit; + +namespace SharpEmu.Gpu.Metal.Tests; + +// The meshlet cache at its byte budget (128 MiB: MetalMeshletCache.BudgetBytes) and its free-buffer pool (32 MiB: +// PoolBudgetBytes). Neither can be lowered, so these builds are real: a 900,000-index strip is a 5 MiB class of +// buffer, 25 of them fill the budget. Keys of one range differ by the primitive limit (32 + key), which does not +// change the words built, so every key's entry has the same size. +public sealed unsafe partial class MetalMeshletCacheTests +{ + private const ulong Mib = 1024 * 1024; + private const ulong CacheBudget = 128 * Mib; + private const ulong PoolBudget = 32 * Mib; + private const int BigIndices = 900_000; + private const int SmallIndices = 450_000; + private const ulong BudgetRange = MetalGuestWindowGranuleTests.GuestBase; + + private static uint[] Big(uint offset) => Strip(offset, BigIndices / 3); + + private static ulong ClassOf(uint[] indices, uint maxPrimitives = 32) => + MetalMeshletCache.SizeClass((ulong)MeshletBuilder.Build(indices, MaxVertices, maxPrimitives).Words.Length * sizeof(uint)); + + private static readonly Lazy BigBytes = new(() => ClassOf(Big(0))); + private static readonly Lazy SmallBytes = new(() => ClassOf(Strip(0, SmallIndices / 3))); + + // Entries that fill the budget exactly as far as another one would not fit. + private static int Fit() => (int)(CacheBudget / BigBytes.Value); + + private static bool TryGetBig(Rig rig, int key, ulong serial, ulong completed, out MetalMeshletCache.Meshlets meshlets) => + rig.Cache.TryGet(BudgetRange, BigIndices, true, MaxVertices, (uint)(32 + key), serial, completed, out meshlets); + + private static MetalMeshletCache.Meshlets GetBig(Rig rig, int key, ulong serial, ulong completed) + { + Assert.True(TryGetBig(rig, key, serial, completed, out var meshlets)); + return meshlets; + } + + private static long Builds(Rig rig) => + rig.Cache.Builds(MetalMeshletCache.BuildReason.New) + rig.Cache.Builds(MetalMeshletCache.BuildReason.Changed) + + rig.Cache.Builds(MetalMeshletCache.BuildReason.Recurring); + + private static long Counter(string counters, string name) + { + var start = counters.IndexOf(name + "=", StringComparison.Ordinal); + Assert.True(start >= 0, $"{name} is not in the counters line"); + start += name.Length + 1; + var end = counters.IndexOf(' ', start); + if (end < 0) end = counters.Length; + return long.Parse(counters.AsSpan(start, end - start)); + } + + // Distinct keys of one range, each in its own submission with the one before completed: the entries nothing can + // read any more are the least recently used first. The one that does not fit evicts the oldest, the cache reuses + // its buffer from the pool, the byte total follows every change, and a hit on an entry makes it the newest. + [Fact] + public void BudgetEvictionTakesTheLeastRecentlyUsedEntryFirstAndKeepsTheByteTotal() + { + if (!RequireDevice()) return; + using var rig = new Rig(maxVersions: 4, pool: true); + rig.Write(Big(0), BudgetRange); + var fit = Fit(); + Assert.True(fit >= 8, $"{fit} entries fit"); + for (var key = 0; key < fit; key++) + { + GetBig(rig, key, (ulong)key + 1, (ulong)key); + } + + Assert.Equal(0, rig.Cache.Evictions); + Assert.Equal(fit, rig.Cache.VersionCount); + var counters = rig.Cache.TakeCounters(); + output.WriteLine(counters); + Assert.Equal((long)((ulong)fit * BigBytes.Value / Mib), Counter(counters, "meshlet_mb")); + + // One more key: key 0, the oldest, makes room, and its buffer (its submission completed) is the new one's. + var next = GetBig(rig, fit, (ulong)fit + 1, (ulong)fit); + Assert.Equal(1, rig.Cache.Evictions); + Assert.Equal(fit, rig.Cache.VersionCount); + Assert.Equal(1, rig.Cache.PoolHits); + Assert.Equal(0, rig.Cache.RetiredCount); + Assert.NotEqual(0, next.Buffer); + counters = rig.Cache.TakeCounters(); + Assert.Equal((long)((ulong)fit * BigBytes.Value / Mib), Counter(counters, "meshlet_mb")); + Assert.Equal(1, Counter(counters, "meshlet_evictions")); + + // Key 1 is still there: a hit, no build, and it is the newest now. + var builds = Builds(rig); + GetBig(rig, 1, (ulong)fit + 2, (ulong)fit + 1); + Assert.Equal(builds, Builds(rig)); + Assert.Equal(0, rig.Cache.Evictions); + + // The next eviction takes key 2, not the key that was just used. + GetBig(rig, fit + 1, (ulong)fit + 3, (ulong)fit + 2); + Assert.Equal(1, rig.Cache.Evictions); + GetBig(rig, 1, (ulong)fit + 4, (ulong)fit + 3); + Assert.Equal(builds + 1, Builds(rig)); + // Key 2 is gone: it is built again (a hash its key had before). + Assert.Equal(0, rig.Cache.Builds(MetalMeshletCache.BuildReason.Recurring)); + GetBig(rig, 2, (ulong)fit + 5, (ulong)fit + 4); + Assert.Equal(builds + 2, Builds(rig)); + Assert.Equal(1, rig.Cache.Builds(MetalMeshletCache.BuildReason.Recurring)); + counters = rig.Cache.TakeCounters(); + var megabytes = Counter(counters, "meshlet_mb"); + Assert.InRange(megabytes, 0, (long)(CacheBudget / Mib)); + Assert.Equal((long)((ulong)rig.Cache.VersionCount * BigBytes.Value / Mib), megabytes); + } + + // Several versions of one key are separate entries for eviction: the least recently used of all of them goes, + // whichever key holds it, and a version that was just hit is safe. + [Fact] + public void BudgetEvictionTreatsEveryVersionOfAKeyAsItsOwnEntry() + { + if (!RequireDevice()) return; + using var rig = new Rig(maxVersions: 4, pool: true); + var contents = new[] { Big(0), Big(1_000_000), Big(2_000_000) }; + var fit = Fit(); + for (var version = 0; version < 3; version++) + { + rig.Write(contents[version], BudgetRange); + GetBig(rig, 0, (ulong)version + 1, (ulong)version); + } + + // Key 0 holds three versions; fillers take the rest of the budget. + for (var key = 1; key <= fit - 3; key++) + { + GetBig(rig, key, (ulong)key + 3, (ulong)key + 2); + } + + Assert.Equal(fit, rig.Cache.VersionCount); + Assert.Equal(0, rig.Cache.Evictions); + _ = rig.Cache.TakeCounters(); + + // Version 0 is used again: a version hit, and the newest entry of all. + var serial = (ulong)fit + 10; + rig.Write(contents[0], BudgetRange); + GetBig(rig, 0, serial, serial - 1); + Assert.Equal(1, rig.Cache.VersionHits); + + // A new key needs room: the oldest entry of all is version 1. + GetBig(rig, fit, serial + 1, serial); + Assert.Equal(1, rig.Cache.Evictions); + Assert.Equal(fit, rig.Cache.VersionCount); + + var builds = Builds(rig); + foreach (var version in new[] { 2, 0 }) + { + serial += 2; + rig.Write(contents[version], BudgetRange); + GetBig(rig, 0, serial, serial - 1); + Assert.Equal(builds, Builds(rig)); + } + + serial += 2; + rig.Write(contents[1], BudgetRange); + GetBig(rig, 0, serial, serial - 1); + Assert.Equal(builds + 1, Builds(rig)); + } + + // Every entry was used by a submission that has not completed: nothing may be evicted, so the build is refused, + // counted as an over-budget fallback, and the loop that looks for victims ends. + [Fact] + public void WhenEveryVersionIsInUseTheBuildIsRefusedAndCounted() + { + if (!RequireDevice()) return; + using var rig = new Rig(maxVersions: 4, pool: true); + rig.Write(Big(0), BudgetRange); + var fit = Fit(); + for (var key = 0; key < fit; key++) + { + GetBig(rig, key, (ulong)key + 1, 0); + } + + _ = rig.Cache.TakeCounters(); + Assert.False(TryGetBig(rig, fit, (ulong)fit + 1, 0, out var meshlets)); + + Assert.Equal(default, meshlets); + Assert.Equal(0, rig.Cache.Evictions); + Assert.Equal(fit, rig.Cache.VersionCount); + Assert.Equal(0, rig.Cache.RetiredCount); + var counters = rig.Cache.TakeCounters(); + output.WriteLine(counters); + Assert.Contains("meshlet_fallbacks=0/0/0/0/0/1 ", counters); + Assert.Equal((long)((ulong)fit * BigBytes.Value / Mib), Counter(counters, "meshlet_mb")); + Assert.Equal(0, Counter(counters, "meshlet_builds")); + + // Once the oldest submission completes, the same build goes through and evicts exactly it. + GetBig(rig, fit, (ulong)fit + 2, 1); + Assert.Equal(1, rig.Cache.Evictions); + } + + // Freed buffers of a size nothing asks for again pile up in the pool up to its budget; one past it is released + // (a resident-list change) instead. The pool's byte total is what is pooled, and a build of that size takes one. + [Fact] + public void ARetiredBufferPastThePoolBudgetIsReleasedAndTheFreeTotalStaysConsistent() + { + if (!RequireDevice()) return; + Assert.NotEqual(BigBytes.Value, SmallBytes.Value); + using var rig = new Rig(maxVersions: 4, pool: true); + rig.Write(Big(0), BudgetRange); + var fit = Fit(); + for (var key = 0; key < fit; key++) + { + GetBig(rig, key, (ulong)key + 1, (ulong)key); + } + + // Builds of the other size evict the big entries one by one; each freed buffer has no taker. + var pooledMax = (int)(PoolBudget / BigBytes.Value); + var smalls = 0; + var serial = (ulong)fit + 1; + _ = rig.Cache.TakeCounters(); + long evictions = 0; + while (evictions < pooledMax + 2 && smalls < 100) + { + rig.Write(Strip(0, SmallIndices / 3), BudgetRange); + Assert.True(rig.Cache.TryGet( + BudgetRange, SmallIndices, true, MaxVertices, (uint)(1000 + smalls), serial, serial - 1, out _)); + serial++; + smalls++; + evictions = rig.Cache.Evictions; + } + + Assert.True(evictions >= pooledMax + 2, $"only {evictions} evictions"); + Assert.True(evictions <= fit, "a small entry was evicted before every big one"); + var pooled = Math.Min(evictions, pooledMax); + var counters = rig.Cache.TakeCounters(); + output.WriteLine(counters); + Assert.Equal((long)((ulong)pooled * BigBytes.Value / Mib), Counter(counters, "meshlet_pool_mb")); + // Churn is the small buffers created plus the big ones released past the pool. + Assert.Equal(smalls + (evictions - pooled), Counter(counters, "meshlet_resident_churn")); + Assert.Equal(0, Counter(counters, "meshlet_pool_hits")); + + // A big build now takes a pooled buffer (after evicting what it must, whose buffers join the pool first). + rig.Write(Big(0), BudgetRange); + GetBig(rig, fit + 5, serial, serial - 1); + var evicted = rig.Cache.Evictions; + Assert.Equal(1, rig.Cache.PoolHits); + counters = rig.Cache.TakeCounters(); + var expectedPool = Math.Min(pooledMax, pooled + evicted) - 1; + Assert.Equal((long)((ulong)expectedPool * BigBytes.Value / Mib), Counter(counters, "meshlet_pool_mb")); + } + + // A pooled buffer is a whole size class, the words a build needs are fewer: the meshlets handed back (count, + // bases, every word up to the used length) are the builder's output for the bytes now at the range. + [Fact] + public void ABuildIntoALargerPooledBufferEqualsTheBuilderOutput() + { + if (!RequireDevice()) return; + uint[]? larger = null, smaller = null; + for (var seedA = 1; seedA <= 60 && smaller is null; seedA++) + { + for (var seedB = 1; seedB <= 60 && smaller is null; seedB++) + { + var a = Indices(seedA); + var b = Indices(seedB); + var wordsA = MeshletBuilder.Build(a, MaxVertices, MaxPrimitives).Words.Length; + var wordsB = MeshletBuilder.Build(b, MaxVertices, MaxPrimitives).Words.Length; + if (wordsB < wordsA && ClassOf(a, MaxPrimitives) == ClassOf(b, MaxPrimitives)) + { + larger = a; + smaller = b; + } + } + } + + Assert.NotNull(larger); + Assert.NotNull(smaller); + using var rig = new Rig(maxVersions: 1, pool: true); + rig.Write(larger); + var first = rig.Get((uint)larger.Length, 1, 0); + AssertBuiltFrom(larger, first); + rig.Write(smaller); + var second = rig.Get((uint)smaller.Length, 2, 1); + + Assert.Equal(first.Buffer, second.Buffer); + Assert.Equal(1, rig.Cache.PoolHits); + AssertBuiltFrom(smaller, second); + } + + // The validated version of a key is the one last built or hit, so it is the key's newest: it goes first only + // when a later submission serial is passed for an earlier use (an entry still in use cannot be evicted, and the + // validated one is not). Then a hit on the version that survived counts as a version hit, as a hit on any + // version other than the validated one does, validated or not. + [Fact] + public void AHitOnASurvivingVersionAfterTheValidatedOneWasEvictedCountsAsAVersionHit() + { + if (!RequireDevice()) return; + using var rig = new Rig(maxVersions: 4, pool: true); + var x = Big(0); + var y = Big(1_000_000); + var fit = Fit(); + + rig.Write(x, BudgetRange); + var survivor = GetBig(rig, 0, 7, 0); + rig.Write(y, BudgetRange); + GetBig(rig, 0, 4, 0); + for (var key = 1; key <= fit - 2; key++) + { + GetBig(rig, key, 1, 0); + } + + Assert.Equal(fit, rig.Cache.VersionCount); + Assert.Equal(0, rig.Cache.Evictions); + _ = rig.Cache.TakeCounters(); + + // Room for one: submissions up to 5 are complete, so X (used at 7) stays and Y (used at 4, validated, older + // than every filler) is the victim. + GetBig(rig, fit - 1, 8, 5); + Assert.Equal(1, rig.Cache.Evictions); + Assert.Equal(0, rig.Cache.VersionHits); + + var builds = Builds(rig); + rig.Write(x, BudgetRange); + var again = GetBig(rig, 0, 9, 5); + + Assert.Equal(survivor, again); + Assert.Equal(1, rig.Cache.VersionHits); + Assert.Equal(builds, Builds(rig)); + Assert.Contains("meshlet_version_hits=1 ", rig.Cache.TakeCounters()); + } +} diff --git a/tests/SharpEmu.Gpu.Metal.Tests/MetalMeshletCacheTests.cs b/tests/SharpEmu.Gpu.Metal.Tests/MetalMeshletCacheTests.cs index d921969b8..5ebc40941 100644 --- a/tests/SharpEmu.Gpu.Metal.Tests/MetalMeshletCacheTests.cs +++ b/tests/SharpEmu.Gpu.Metal.Tests/MetalMeshletCacheTests.cs @@ -12,7 +12,7 @@ namespace SharpEmu.Gpu.Metal.Tests; /// back for the bytes at a range, and when a buffer it no longer needs can be written again. /// Buffers come from the device, so every test is behind the exclusive device gate. /// -public sealed unsafe class MetalMeshletCacheTests(ITestOutputHelper output) +public sealed unsafe partial class MetalMeshletCacheTests(ITestOutputHelper output) { private const ulong RangeAddress = MetalGuestWindowGranuleTests.GuestBase + 0x10000; private const uint MaxVertices = 64; From d3b2d3f59a73716ad05bc273dfd09926f26e09e9 Mon Sep 17 00:00:00 2001 From: kuba Date: Sun, 15 Nov 2026 08:19:26 +0000 Subject: [PATCH 042/178] [Metal] Count uploads that end an open render pass, by cause and by upload-prelude condition Every image upload that meets an open render pass is counted on the TBDR line: pass_end_upload=[cpu,invalidated,created,gpu,alias] by the image's DirtyCause, and prelude=[eligible,refused,=n...] by each condition of an upload prelude it fails (alias/GPU cause in the stale-cause mask, texture used or named by a transfer in the open buffer, pending clear, GPU write over the source recorded in the open buffer, staged gather, held label copy or held fill over the source, device copy since the last refresh, sparse, depth/stencil, pieces, transient budget, encoder ordering). No behaviour change: sizes the prelude from a game run before it is built. MetalCachedImage gains StaleCauses (every cause since clean; DirtyCause keeps only the first) and DeviceCopiedSinceRefresh (set at the four device-copy sites, cleared by a whole refresh). --- .../SharpEmu.Gpu.Metal/V2/MetalCachedImage.cs | 17 ++ .../V2/MetalImageCache.AliasSubset.cs | 1 + .../V2/MetalImageCache.UploadPrelude.cs | 74 +++++++ .../SharpEmu.Gpu.Metal/V2/MetalImageCache.cs | 27 +++ .../V2/MetalRenderHost.UploadPrelude.cs | 187 ++++++++++++++++++ .../SharpEmu.Gpu.Metal/V2/MetalRenderHost.cs | 4 +- 6 files changed, 309 insertions(+), 1 deletion(-) create mode 100644 src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.UploadPrelude.cs create mode 100644 src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.UploadPrelude.cs diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalCachedImage.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalCachedImage.cs index 244705ed5..ba392381e 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalCachedImage.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalCachedImage.cs @@ -170,6 +170,7 @@ public MetalCachedImage(in ImageDescription description, in MetalTextureShape sh { _stale[0] = (0, description.Data.Size); _staleCount = 1; + StaleCauses = 1 << (int)MetalImageDirtyCause.Created; } NoteContentChanged(); @@ -611,6 +612,20 @@ private bool IsSrgbTwin(ulong viewFormat) => // Why the next upload will happen; purely diagnostic. public MetalImageDirtyCause DirtyCause { get; private set; } = MetalImageDirtyCause.Created; + /// + /// Every cause that marked the image stale since it was last clean, as bits of 1 << cause. + /// keeps only the first, so a CPU-written image an alias hand-over + /// later marks over another run still says CpuWrite there; the upload prelude reads this. + /// + public byte StaleCauses { get; private set; } + + /// + /// A device copy (an alias or stencil copy from another texture) wrote this texture since its + /// last whole refresh: the texture holds bytes guest memory may not, so the upload prelude never + /// moves a whole upload of it. + /// + public bool DeviceCopiedSinceRefresh; + /// The most stale runs, and the most published runs, an image holds apart with run sets on. public const int MaxRuns = 4; @@ -836,6 +851,7 @@ public void MarkCpuDirty(MetalImageDirtyCause cause, ulong start, ulong end) // Guest memory got newer bytes; the texture itself is unchanged until the upload, so // released chunks stay restorable from it (the upload's read restores what it covers). BumpContentVersion(); + StaleCauses = (byte)((_cpuDirty ? StaleCauses : 0) | (1 << (int)cause)); if (!_cpuDirty) { DirtyCause = cause; @@ -912,6 +928,7 @@ public void RefreshComplete() var wasDirty = _cpuDirty; _cpuDirty = false; _staleCount = 0; + DeviceCopiedSinceRefresh = false; if (wasDirty) { BindingVersion++; diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.AliasSubset.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.AliasSubset.cs index 5458ebb29..4e933d9a7 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.AliasSubset.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.AliasSubset.cs @@ -113,6 +113,7 @@ private bool TryPublishAliasLayerSubset( EnsureSparseBacked(image); var context = _owner.BeginTransfer(MetalTransferCause.Writeback, other.Texture, image.Texture); + image.DeviceCopiedSinceRefresh = true; if (!_transfer.TryEncodeLayerSubsetCopy( context, other.Texture, sourceFirst, image.Texture, targetFirst, layers, image.Shape.Width, image.Shape.Height)) { diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.UploadPrelude.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.UploadPrelude.cs new file mode 100644 index 000000000..289194fa9 --- /dev/null +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.UploadPrelude.cs @@ -0,0 +1,74 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +namespace SharpEmu.Gpu.Metal.V2; + +// The image's share of the upload prelude's conditions (MetalRenderHost.UploadPrelude.cs): an +// upload needed while a render pass is open may run ahead of the open command buffer only when +// nothing recorded in that buffer touches the texture or writes the bytes it reads. +internal sealed partial class MetalImageCache +{ + private const byte AliasOrGpuCauses = + (1 << (int)MetalImageDirtyCause.AliasWrite) | (1 << (int)MetalImageDirtyCause.GpuWrite); + + // The conditions an upload of [start, end) of the image fails, the host's included. whole: the + // upload replaces the whole resident range rather than a stale run. + private MetalPreludeBlock PreludeBlocks(MetalCachedImage image, ulong start, ulong end, bool whole) + { + var blocks = MetalPreludeBlock.None; + var causes = image.StaleCauses; + if ((causes & AliasOrGpuCauses) != 0) + { + blocks |= (causes & (1 << (int)MetalImageDirtyCause.AliasWrite)) != 0 ? MetalPreludeBlock.CauseAlias : 0; + blocks |= (causes & (1 << (int)MetalImageDirtyCause.GpuWrite)) != 0 ? MetalPreludeBlock.CauseGpu : 0; + } + + // Bound (sampled, attached, stored) in the open buffer: the bindings note the open serial + // after the refresh, so a use before this upload has already left it there. + var serial = _owner.CurrentSerial; + if (image.LastUseSerial >= serial || image.GpuWriteSerial >= serial) + { + blocks |= MetalPreludeBlock.UsedInBuffer; + } + + if (whole && image.DeviceCopiedSinceRefresh) + { + blocks |= MetalPreludeBlock.DeviceCopy; + } + + if (image.Sparse is not null) + { + blocks |= MetalPreludeBlock.Sparse; + } + + ref readonly var description = ref image.Description; + if (description.IsDepth || description.HasStencil) + { + blocks |= MetalPreludeBlock.DepthStencil; + } + + if (end - start > TransferPieceBytes) + { + blocks |= MetalPreludeBlock.Pieces; + } + + return blocks | _owner.PreludeBlocks(image.Texture, description.Data.Address + start, end - start); + } + + // Counts an upload that met an open render pass (null when none was open), with a staged + // gather the source needed added to what it failed. + private void NotePassEndingUpload(MetalImageDirtyCause cause, MetalPreludeBlock? blocks, long gathersBefore) + { + if (blocks is not { } failed) + { + return; + } + + if (_uploadGathers != gathersBefore) + { + failed |= MetalPreludeBlock.StagedGather; + } + + _owner.NotePassEndingUpload(cause, failed); + } +} diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.cs index 013c7b1db..147434875 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.cs @@ -44,6 +44,18 @@ IMetalSubmissionContext BeginTransfer(MetalTransferCause cause, nint texture, ni // are not settled yet. bool HasPendingGpuWrite(ulong address, ulong size); + // A transfer begun now would end an open render pass (MetalRenderHost.UploadPrelude.cs). + bool UploadWouldEndRenderPass => false; + + // The host's share of the conditions for uploading this texture from these guest bytes ahead + // of the open command buffer: what the open buffer has recorded over either. + MetalPreludeBlock PreludeBlocks(nint texture, ulong address, ulong size) => MetalPreludeBlock.None; + + // An upload met an open render pass and ended it; blocks are the prelude conditions it failed. + void NotePassEndingUpload(MetalImageDirtyCause cause, MetalPreludeBlock blocks) + { + } + // Copies the guest bytes of a range into its staged (ring) copy on the GPU, behind the work still // writing them, so a transfer reading the staged copy next sees what that work leaves there. void GatherStagedRange(ulong address, in MetalGuestRange staging) @@ -1087,6 +1099,7 @@ private bool TryCopyStencilOnDevice(MetalCachedImage depth, MetalCachedImage oth EnsureSparseBacked(depth); var context = _owner.BeginTransfer(MetalTransferCause.Writeback, other.Texture, depth.Texture); + depth.DeviceCopiedSinceRefresh = true; if (!_transfer.TryEncodeStencilFromColor( context, in other.Description, other.Texture, in depth.Description, depth.Texture)) { @@ -1168,6 +1181,7 @@ private bool TryCopyStencilToColorOnDevice(MetalCachedImage depth, MetalCachedIm EnsureSparseBacked(image); var context = _owner.BeginTransfer(MetalTransferCause.Writeback, depth.Texture, image.Texture); + image.DeviceCopiedSinceRefresh = true; if (!_transfer.TryEncodeColorFromStencil( context, in depth.Description, depth.Texture, in image.Description, image.Texture)) { @@ -2125,6 +2139,7 @@ private bool TryPublishAliasOnDevice(MetalCachedImage image, MetalCachedImage ot EnsureSparseBacked(image); var context = _owner.BeginTransfer(MetalTransferCause.Writeback, other.Texture, image.Texture); + image.DeviceCopiedSinceRefresh = true; var refusal = "disabled"; var fused = AliasTransitionsEnabled && _transfer.TryEncodeFusedAlias( context, in other.Description, other.Texture, in image.Description, image.Texture, out refusal); @@ -2831,6 +2846,12 @@ private void RefreshFromGuestCore(MetalCachedImage image) return; } + // Sized before anything below lands or ends: whether this upload meets an open render pass, + // and which of the prelude's conditions it fails (MetalImageCache.UploadPrelude.cs). + MetalPreludeBlock? prelude = _owner.UploadWouldEndRenderPass + ? PreludeBlocks(image, residentStart, residentEnd, whole: true) + : null; + var gathersBefore = _uploadGathers; PrepareSparseUpload(image, residentStart, residentEnd); _owner.LandHeldCopies(description.Data.Address + residentStart, residentEnd - residentStart); var context = _owner.BeginTransfer(MetalTransferCause.Upload, image.Texture); @@ -2862,6 +2883,7 @@ private void RefreshFromGuestCore(MetalCachedImage image) } _uploadCauses[(int)image.DirtyCause]++; + NotePassEndingUpload(image.DirtyCause, prelude, gathersBefore); NoteUploadForTrace(image, image.DirtyCause, residentEnd - residentStart, run: false); if (context.WantsEncodedLabels) { @@ -2941,6 +2963,10 @@ private bool TryRefreshDirtyRun(MetalCachedImage image) var cause = image.DirtyCause; foreach (var (start, end) in runs[..count]) { + MetalPreludeBlock? prelude = _owner.UploadWouldEndRenderPass + ? PreludeBlocks(image, start, end, whole: false) + : null; + var gathersBefore = _uploadGathers; var source = ResolveUploadSource(description.Data.Address + start, end - start); if (!source.IsValid || source.Size < end - start) { @@ -2959,6 +2985,7 @@ private bool TryRefreshDirtyRun(MetalCachedImage image) } _uploadCauses[(int)cause]++; + NotePassEndingUpload(cause, prelude, gathersBefore); NoteUploadForTrace(image, cause, end - start, run: true); _partialUploads++; _partialUploadBytesSaved += (long)(residentEnd - residentStart - (end - start)); diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.UploadPrelude.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.UploadPrelude.cs new file mode 100644 index 000000000..a8b4b278e --- /dev/null +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.UploadPrelude.cs @@ -0,0 +1,187 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using System.Numerics; +using System.Text; + +namespace SharpEmu.Gpu.Metal.V2; + +/// +/// Why an image upload needed while a render pass is open could not be encoded ahead of the open +/// command buffer (the upload prelude). An upload is counted under every condition it fails. +/// +[Flags] +internal enum MetalPreludeBlock : uint +{ + None = 0, + // The image went stale through an alias hand-over: its source bytes are normally written back + // by a writeback earlier in the same command buffer. + CauseAlias = 1 << 0, + // Guest memory under the image was written by the GPU (a store, fill or copy the cache saw). + CauseGpu = 1 << 1, + // The texture is bound, written or named by a transfer in the open command buffer: work + // recorded before the upload would see the new texels if the upload ran first. + UsedInBuffer = 1 << 2, + // A clear of the texture waits for its pass in the open command buffer. + PendingClear = 1 << 3, + // A GPU store over the source bytes is recorded in the open command buffer (a dispatch, a + // writeback, a fill, a GuestCopy, or a staged store that lands at the encoder's end). + PendingGpuWrite = 1 << 4, + // The source is a ring copy the GPU must gather behind pending writes, in the open buffer. + StagedGather = 1 << 5, + // A command-processor copy held for the commit lands in the source bytes. + HeldCopy = 1 << 6, + // A guest fill held by the open pass lands in the source bytes. + HeldFill = 1 << 7, + // A whole upload of an image a device copy wrote since its last refresh. + DeviceCopy = 1 << 8, + // A sparse texture maps its tiles in the open command buffer first. + Sparse = 1 << 9, + // Depth and stencil uploads are left in place (they encode render passes of their own). + DepthStencil = 1 << 10, + // The upload is cut into pieces (larger than one transfer piece). + Pieces = 1 << 11, + // The open buffer's transient staging is past its budget: the normal path commits it. + Budget = 1 << 12, + // The encoders are not chained by the encoder fence, which is what orders the prelude. + Ordering = 1 << 13, + // The source range resolves to no window and no ring copy. + Unmapped = 1 << 14, +} + +// The upload prelude counters: every image upload that met an open render pass, by cause, and by +// each condition of the prelude it passes or fails. Printed on the TBDR line as +// prelude=[eligible,refused,=n...] pass_end_upload=[cpu,invalidated,created,gpu,alias]. +internal sealed partial class MetalRenderHost +{ + private static readonly string[] PreludeBlockNames = + [ + "cause_alias", "cause_gpu", "used", "clear", "gpu_write", "gather", "held_copy", "held_fill", + "device_copy", "sparse", "depth", "pieces", "budget", "ordering", "unmapped", + ]; + + private readonly long[] _preludeBlocked = new long[PreludeBlockNames.Length]; + private readonly long[] _passEndUploads = new long[Enum.GetValues().Length]; + private long _preludeEligible; + private long _preludeRefused; + + // The textures a transfer of the open command buffer named, read or written. A bound texture is + // known by its image's last-use serial; a transfer names the texture itself (a device alias + // copy, a usage promotion, a sparse remap, a clear). + private readonly HashSet _transferTexturesInBuffer = []; + + private void NoteTransferTextures(nint texture, nint otherTexture) + { + if (texture != 0) + { + _transferTexturesInBuffer.Add(texture); + } + + if (otherTexture != 0) + { + _transferTexturesInBuffer.Add(otherTexture); + } + } + + // A transfer begun now ends an open render pass. + bool IMetalImageCacheOwner.UploadWouldEndRenderPass => _commandBuffer != 0 && _renderEncoder != 0; + + // What the host knows of the conditions for encoding an upload of this texture from these guest + // bytes ahead of the open command buffer. + MetalPreludeBlock IMetalImageCacheOwner.PreludeBlocks(nint texture, ulong address, ulong size) + { + var blocks = MetalPreludeBlock.None; + if (_transferTexturesInBuffer.Contains(texture)) + { + blocks |= MetalPreludeBlock.UsedInBuffer; + } + + if (PendingClearTouches(texture)) + { + blocks |= MetalPreludeBlock.PendingClear; + } + + if ((_gpuWrites.MayCover(address, size) && _gpuWrites.PendingSerial(address, size, CompletedSerial) >= _submissionSerial) || + (_stagedStorageCopies is { Count: > 0 } staged && staged.HasRecordedStoresOver(address, size))) + { + blocks |= MetalPreludeBlock.PendingGpuWrite; + } + + if (DeferredLabelCopiesTouch(address, size)) + { + blocks |= MetalPreludeBlock.HeldCopy; + } + + if (_deferredFills.Count != 0 && DeferredFillsTouch(address, size)) + { + blocks |= MetalPreludeBlock.HeldFill; + } + + if (RecordingTransientBytes >= TransientCommitBytes) + { + blocks |= MetalPreludeBlock.Budget; + } + + if (EncoderOrdering != EncoderOrderingMode.Fence) + { + blocks |= MetalPreludeBlock.Ordering; + } + + return blocks; + } + + void IMetalImageCacheOwner.NotePassEndingUpload(MetalImageDirtyCause cause, MetalPreludeBlock blocks) + { + _passEndUploads[(int)cause]++; + if (blocks == MetalPreludeBlock.None) + { + _preludeEligible++; + return; + } + + _preludeRefused++; + for (var bits = (uint)blocks; bits != 0; bits &= bits - 1) + { + _preludeBlocked[BitOperations.TrailingZeroCount(bits)]++; + } + } + + /// The prelude counters as the TBDR line prints them, reset. + internal string TakePreludeText() + { + var builder = new StringBuilder("prelude=[eligible="); + builder.Append(_preludeEligible).Append(" refused=").Append(_preludeRefused); + for (var index = 0; index < _preludeBlocked.Length; index++) + { + if (_preludeBlocked[index] != 0) + { + builder.Append(' ').Append(PreludeBlockNames[index]).Append('=').Append(_preludeBlocked[index]); + } + } + + builder.Append("] pass_end_upload=[cpu=").Append(_passEndUploads[(int)MetalImageDirtyCause.CpuWrite]) + .Append(" invalidated=").Append(_passEndUploads[(int)MetalImageDirtyCause.Invalidated]) + .Append(" created=").Append(_passEndUploads[(int)MetalImageDirtyCause.Created]) + .Append(" gpu=").Append(_passEndUploads[(int)MetalImageDirtyCause.GpuWrite]) + .Append(" alias=").Append(_passEndUploads[(int)MetalImageDirtyCause.AliasWrite]).Append(']'); + _preludeEligible = 0; + _preludeRefused = 0; + Array.Clear(_preludeBlocked); + Array.Clear(_passEndUploads); + return builder.ToString(); + } + + /// The prelude counters since the last call, for tests: (eligible, refused, refusals by reason name). + internal (long Eligible, long Refused, Dictionary Blocked) TakePreludeCounters() + { + var blocked = new Dictionary(); + for (var index = 0; index < _preludeBlocked.Length; index++) + { + blocked[PreludeBlockNames[index]] = _preludeBlocked[index]; + } + + var counters = (_preludeEligible, _preludeRefused, blocked); + _ = TakePreludeText(); + return counters; + } +} diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.cs index 6c98eec7f..66dff78ce 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.cs @@ -356,6 +356,7 @@ private nint OpenCommandBuffer() // Released once, when the in-flight ring is done with it (or in Dispose). MetalNative.Send(_commandBuffer, MetalNative.Selector("retain")); _submissionSerial = ++_nextSerial; + _transferTexturesInBuffer.Clear(); var completed = CompletedSerial; _guestMemory.BeginSubmission(_submissionSerial, completed); // Staging slabs idle for a while are released or made purgeable here too, not only @@ -402,6 +403,7 @@ private IMetalSubmissionContext BeginTransferTouching(MetalTransferCause cause, _ = EnsureCommandBuffer(); NoteRecordedWork(); + NoteTransferTextures(texture, otherTexture); _transferInSharedEncoder = false; if (TransfersShareCompute && _computeEncoder != 0 && texture != 0 && otherTexture == 0 && cause is (MetalTransferCause.Upload or MetalTransferCause.Writeback) && !PendingClearTouches(texture)) @@ -2953,7 +2955,7 @@ public void ReportCounters() $"subset_joins={subsetJoins} subset_join_sampled={subsetJoinsSampled}{TakeSubsetRefusals()} " + $"join_device_ranges=[{FormatDeviceRangeJoinChecks()}] " + $"{TakeUnionPassText()} flush_hold=[{FormatHeldCommits()}] {FormatDeferredFills()} " + - $"transfers=[{TakeTransferCauses()}]" + + $"transfers=[{TakeTransferCauses()}] {TakePreludeText()}" + (CopiesShareCompute ? $" copies_in_encoder={_copiesInEncoder}" : "") + $" alias_writes_discarded={_imageCache.TakeAliasWritesDiscarded()} " + SharpEmu.Libs.Gpu.Rendering.RenderRecorderStatistics.TakeInPlaceReport()); From 015b6bf1f83e9694bac23f97a0abe36915077408 Mon Sep 17 00:00:00 2001 From: kuba Date: Sun, 15 Nov 2026 08:32:20 +0000 Subject: [PATCH 043/178] [Metal] Upload prelude: a CPU-caused upload in an open render pass runs ahead of the open command buffer An image upload whose stale causes are only CpuWrite, Invalidated or Created, needed while a render pass is open, is encoded into a command buffer of its own committed at once, ahead of the open one, instead of ending the pass (Demon's Souls' 7-attachment G-buffer pass stores and reloads 22-26 MB for each such break). SHARPEMU_METAL_V2_UPLOAD_PRELUDE=0 ends the pass as before. Order: commit enqueues; nothing calls enqueue and the open buffer is committed only by FlushCommandBuffer, so the prelude sits after every earlier buffer and before the open one however long the stream holds it. Its encoders take the shared encoder fence, which Metal resolves across a queue's command buffers in commit order, so the open buffer's first encoder (and through the chain the open pass) waits for it; the texture is tracked too. Refused and counted when the texture is used, cleared or named by a transfer in the open buffer, a GPU write, held label copy or held fill over the source is recorded in it, the source needs a staged gather, or the image is alias/GPU-caused, sparse, depth/stencil, in pieces, device-copied (whole uploads), over the transient budget, or not fence-ordered. Lifetime: the prelude borrows under the open buffer's serial, whose signal follows the prelude through the fence chain; the image notes the open serial as a use after its hoisted uploads; each prelude buffer's status is read once that serial completes (failed= counter). Tests: MetalUploadPreludeTests (11 device cases, switch on vs off bit-identical texture and target, counters per refusal reason, per-run hoisting, staging lifetime). --- .../V2/MetalImageCache.UploadPrelude.cs | 67 +++ .../SharpEmu.Gpu.Metal/V2/MetalImageCache.cs | 133 +++-- .../V2/MetalRenderHost.UploadPrelude.cs | 163 +++++- .../SharpEmu.Gpu.Metal/V2/MetalRenderHost.cs | 3 + .../SharpEmu.Gpu.Metal.Tests/MetalPassRig.cs | 3 + .../MetalUploadPreludeTests.cs | 539 ++++++++++++++++++ 6 files changed, 862 insertions(+), 46 deletions(-) create mode 100644 tests/SharpEmu.Gpu.Metal.Tests/MetalUploadPreludeTests.cs diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.UploadPrelude.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.UploadPrelude.cs index 289194fa9..966ded929 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.UploadPrelude.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.UploadPrelude.cs @@ -55,6 +55,73 @@ private MetalPreludeBlock PreludeBlocks(MetalCachedImage image, ulong start, ulo return blocks | _owner.PreludeBlocks(image.Texture, description.Data.Address + start, end - start); } + // Encodes the upload of [start, end) into a prelude command buffer committed ahead of the open + // one (MetalRenderHost.UploadPrelude.cs), when it fails no condition and the switch is on. False + // leaves it to the open buffer, with blocks saying what it failed (None: the switch is off). + // True with moved false: the transfer refused it, as it would have in the open buffer. + private bool TryUploadInPrelude( + MetalCachedImage image, ulong start, ulong end, ref MetalPreludeBlock blocks, out bool moved) + { + moved = false; + if (blocks != MetalPreludeBlock.None || !_owner.UploadPreludeEnabled) + { + return false; + } + + ref readonly var description = ref image.Description; + var address = description.Data.Address + start; + var size = end - start; + // The source as ResolveUploadSource gives it, without the gather it would encode into the open + // buffer: a window is read in place when the prelude runs, behind every buffer committed before + // it; a ring copy is what guest memory holds now, which misses writes still in flight. + if (!_guestMemory.TryResolveInPlace(address, size, out var source)) + { + if (UploadGatherEnabled && _owner.HasPendingGpuWrite(address, size)) + { + blocks |= MetalPreludeBlock.StagedGather; + return false; + } + + source = _guestMemory.Resolve(address, size); + } + + if (!source.IsValid || source.Size < size) + { + blocks |= MetalPreludeBlock.Unmapped; + return false; + } + + if (_owner.BeginUploadPrelude() is not { } prelude) + { + return false; + } + + try + { + moved = EncodeUpload( + prelude, in description, ResidentRange(image), source, default, image.Texture, start, size, + image.FirstLevel); + } + finally + { + _owner.EndUploadPrelude(prelude); + } + + return true; + } + + // After an image's hoisted uploads, its texture is the open buffer's: it has to outlive the preludes, + // and an upload of it after a later CPU write, before that buffer is committed, would run ahead of a + // use these serve. Noted once the refresh is done, so the image's other runs still go ahead on their + // own conditions. + private void NoteHoistedUse(MetalCachedImage image, bool hoisted) + { + if (hoisted) + { + image.NoteUse(_owner.CurrentSerial); + } + } + // Counts an upload that met an open render pass (null when none was open), with a staged // gather the source needed added to what it failed. private void NotePassEndingUpload(MetalImageDirtyCause cause, MetalPreludeBlock? blocks, long gathersBefore) diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.cs index 147434875..b0f0684a2 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.cs @@ -56,6 +56,18 @@ void NotePassEndingUpload(MetalImageDirtyCause cause, MetalPreludeBlock blocks) { } + // SHARPEMU_METAL_V2_UPLOAD_PRELUDE: an upload that fails no prelude condition is encoded ahead + // of the open command buffer, through BeginUploadPrelude and EndUploadPrelude. + bool UploadPreludeEnabled => false; + + // A command buffer committed ahead of the open one when EndUploadPrelude is called, or null when + // none can be had (the switch off, no render pass open). + IMetalSubmissionContext? BeginUploadPrelude() => null; + + void EndUploadPrelude(IMetalSubmissionContext prelude) + { + } + // Copies the guest bytes of a range into its staged (ring) copy on the GPU, behind the work still // writing them, so a transfer reading the staged copy next sees what that work leaves there. void GatherStagedRange(ulong address, in MetalGuestRange staging) @@ -2847,31 +2859,42 @@ private void RefreshFromGuestCore(MetalCachedImage image) } // Sized before anything below lands or ends: whether this upload meets an open render pass, - // and which of the prelude's conditions it fails (MetalImageCache.UploadPrelude.cs). - MetalPreludeBlock? prelude = _owner.UploadWouldEndRenderPass - ? PreludeBlocks(image, residentStart, residentEnd, whole: true) - : null; - var gathersBefore = _uploadGathers; - PrepareSparseUpload(image, residentStart, residentEnd); - _owner.LandHeldCopies(description.Data.Address + residentStart, residentEnd - residentStart); - var context = _owner.BeginTransfer(MetalTransferCause.Upload, image.Texture); - var residentSize = residentEnd - residentStart; - var whole = residentSize <= TransferPieceBytes - ? ResolveUploadSource(description.Data.Address + residentStart, residentSize) - : default; - bool moved; - if (whole.IsValid && whole.Size >= residentSize) + // and which of the prelude's conditions it fails (MetalImageCache.UploadPrelude.cs). One that + // fails none runs ahead of the open command buffer instead of ending its pass. + MetalPreludeBlock? prelude = null; + var hoisted = false; + var moved = false; + if (_owner.UploadWouldEndRenderPass) { - var stencil = description.HasStencil - ? ResolveUploadSource(description.Stencil.Address, description.Stencil.Size) - : default; - moved = EncodeUpload( - context, in description, ResidentRange(image), whole, stencil, image.Texture, - residentStart, residentSize, image.FirstLevel); + var blocks = PreludeBlocks(image, residentStart, residentEnd, whole: true); + hoisted = TryUploadInPrelude(image, residentStart, residentEnd, ref blocks, out moved); + prelude = blocks; } - else - { - moved = UploadInPieces(context, image); + + var gathersBefore = _uploadGathers; + IMetalSubmissionContext? context = null; + if (!hoisted) + { + PrepareSparseUpload(image, residentStart, residentEnd); + _owner.LandHeldCopies(description.Data.Address + residentStart, residentEnd - residentStart); + context = _owner.BeginTransfer(MetalTransferCause.Upload, image.Texture); + var residentSize = residentEnd - residentStart; + var whole = residentSize <= TransferPieceBytes + ? ResolveUploadSource(description.Data.Address + residentStart, residentSize) + : default; + if (whole.IsValid && whole.Size >= residentSize) + { + var stencil = description.HasStencil + ? ResolveUploadSource(description.Stencil.Address, description.Stencil.Size) + : default; + moved = EncodeUpload( + context, in description, ResidentRange(image), whole, stencil, image.Texture, + residentStart, residentSize, image.FirstLevel); + } + else + { + moved = UploadInPieces(context, image); + } } if (!moved) @@ -2883,9 +2906,17 @@ private void RefreshFromGuestCore(MetalCachedImage image) } _uploadCauses[(int)image.DirtyCause]++; - NotePassEndingUpload(image.DirtyCause, prelude, gathersBefore); + if (hoisted) + { + NoteHoistedUse(image, true); + } + else + { + NotePassEndingUpload(image.DirtyCause, prelude, gathersBefore); + } + NoteUploadForTrace(image, image.DirtyCause, residentEnd - residentStart, run: false); - if (context.WantsEncodedLabels) + if (context is { WantsEncodedLabels: true }) { context.ProfileEncoded(ProfileLabel("upload", in description)); } @@ -2961,35 +2992,58 @@ private bool TryRefreshDirtyRun(MetalCachedImage image) } var cause = image.DirtyCause; + var anyHoisted = false; foreach (var (start, end) in runs[..count]) { - MetalPreludeBlock? prelude = _owner.UploadWouldEndRenderPass - ? PreludeBlocks(image, start, end, whole: false) - : null; - var gathersBefore = _uploadGathers; - var source = ResolveUploadSource(description.Data.Address + start, end - start); - if (!source.IsValid || source.Size < end - start) + // Each run goes ahead of the open buffer on its own conditions; one that stays in it names the + // texture there, so no later run of this image moves ahead of it. + MetalPreludeBlock? prelude = null; + var hoisted = false; + var moved = false; + if (_owner.UploadWouldEndRenderPass) { - return false; + var blocks = PreludeBlocks(image, start, end, whole: false); + hoisted = TryUploadInPrelude(image, start, end, ref blocks, out moved); + anyHoisted |= hoisted; + prelude = blocks; } - PrepareSparseUpload(image, start, end); - _owner.LandHeldCopies(description.Data.Address + start, end - start); - var context = _owner.BeginTransfer(MetalTransferCause.Upload, image.Texture); - if (!EncodeUpload( + var gathersBefore = _uploadGathers; + IMetalSubmissionContext? context = null; + if (!hoisted) + { + var source = ResolveUploadSource(description.Data.Address + start, end - start); + if (!source.IsValid || source.Size < end - start) + { + NoteHoistedUse(image, anyHoisted); + return false; + } + + PrepareSparseUpload(image, start, end); + _owner.LandHeldCopies(description.Data.Address + start, end - start); + context = _owner.BeginTransfer(MetalTransferCause.Upload, image.Texture); + moved = EncodeUpload( context, in description, ResidentRange(image), source, default, image.Texture, start, end - start, - image.FirstLevel)) + image.FirstLevel); + } + + if (!moved) { // Nothing of this run reached the texture; the whole refresh decides what becomes of the image. + NoteHoistedUse(image, anyHoisted); return false; } _uploadCauses[(int)cause]++; - NotePassEndingUpload(cause, prelude, gathersBefore); + if (!hoisted) + { + NotePassEndingUpload(cause, prelude, gathersBefore); + } + NoteUploadForTrace(image, cause, end - start, run: true); _partialUploads++; _partialUploadBytesSaved += (long)(residentEnd - residentStart - (end - start)); - if (context.WantsEncodedLabels) + if (context is { WantsEncodedLabels: true }) { context.ProfileEncoded(ProfileLabel("upload-run", in description)); } @@ -3002,6 +3056,7 @@ private bool TryRefreshDirtyRun(MetalCachedImage image) Interlocked.Increment(ref _uploads); } + NoteHoistedUse(image, anyHoisted); if (image.FirstLevel != 0) { // What is still dirty lies outside the levels the texture holds. diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.UploadPrelude.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.UploadPrelude.cs index a8b4b278e..82e90ca80 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.UploadPrelude.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.UploadPrelude.cs @@ -49,11 +49,157 @@ internal enum MetalPreludeBlock : uint Unmapped = 1 << 14, } -// The upload prelude counters: every image upload that met an open render pass, by cause, and by -// each condition of the prelude it passes or fails. Printed on the TBDR line as -// prelude=[eligible,refused,=n...] pass_end_upload=[cpu,invalidated,created,gpu,alias]. +// The upload prelude. An image upload the CPU caused (stale causes CpuWrite, Invalidated or +// Created only), needed while a render pass is open, is encoded into a command buffer of its own +// that is committed at once, ahead of the open one, instead of ending the pass: on a tile-based +// GPU ending and resuming Demon's Souls' 7-attachment G-buffer pass stores and reloads 22-26 MB. +// SHARPEMU_METAL_V2_UPLOAD_PRELUDE=0 ends the pass for every upload, as before. +// +// Order. Metal runs a queue's command buffers in the order they are enqueued, and commit enqueues +// a buffer not enqueued yet; nothing in this backend calls enqueue, and the open buffer is +// committed only by FlushCommandBuffer. So the prelude's commit (EndUploadPrelude) puts it after +// every buffer committed before it and before the open buffer, whenever that one is committed and +// however long the stream holds it (MetalCommandStream HoldForOpenPass): nothing committed after +// the prelude can run ahead of it. Its encoders take the same encoder fence as every other +// encoder (EncoderOrdering = Fence; any other mode refuses, counted as ordering): Metal resolves a +// fence across command buffers of one queue in commit order, so the prelude's first encoder waits +// for the last encoder of the buffer committed before it, and the open buffer's first encoder - +// and through the chain the open render pass - waits for the prelude's last. The texture is +// hazard-tracked as well (private textures are created tracked), so a draw of the open pass that +// samples it after the upload waits for the prelude's write either way. +// +// What moves. The upload now runs before everything the open buffer recorded ahead of it, so it +// may move only when none of that touches the texture or writes the bytes it reads: the texture +// has no use in the open buffer (its image's last-use and GPU-write serials, the textures the open +// buffer's transfers named, a clear waiting for its pass), and no GPU write over the source is +// recorded in it (MetalGpuWriteRanges at the open serial: dispatch stores, image writebacks, fills +// and copies; staged stores landing at an encoder end; a held label copy or a held fill over the +// bytes). An alias-caused or GPU-caused upload never moves: its source is normally produced by a +// writeback earlier in the same buffer. A staged source that needs a GPU gather, a sparse texture, +// a depth/stencil image, an upload in pieces, and a whole upload of an image a device copy wrote +// since its last refresh are refused too. Each refusal is counted and the upload ends the pass as +// before. Work recorded after the upload (draws sampling the texture, later writes over the +// source, other committed buffers) runs after the prelude, as it ran after the upload before. +// +// Lifetime. The prelude borrows staging, ring copies and window pins under the open buffer's +// serial (its context's SubmissionSerial), so they return to their pools only when the open buffer +// completes. Its signal is encoded after all of its encoders, whose fence chain starts behind the +// prelude's last encoder, so that serial completes only after the prelude has. The image notes the +// open serial as a use, as the binding after the upload would, so its texture outlives the prelude +// and a second upload of it in the same open buffer stays in that buffer. A prelude buffer is kept +// until the open serial completes, then its status is read: one that failed is counted and reported. +// +// Residency. A residency set (other titles) is attached to the queue, so the prelude has it as the +// open buffer does; without one (Demon's Souls) the transfer binds its window, ring and staging +// buffers directly to its encoders, which makes them resident for the prelude buffer. +// +// The counters: every image upload that met an open render pass, by cause, and by each condition +// of the prelude it passes or fails, printed on the TBDR line as +// prelude=[eligible,hoisted,refused,failed,=n...] pass_end_upload=[cpu,invalidated,created,gpu,alias]; +// eligible counts uploads that passed every condition with the switch off. internal sealed partial class MetalRenderHost { + /// Whether an upload the CPU caused may run ahead of an open render pass (SHARPEMU_METAL_V2_UPLOAD_PRELUDE). + internal bool UploadPreludeEnabled { get; set; } = + Environment.GetEnvironmentVariable("SHARPEMU_METAL_V2_UPLOAD_PRELUDE") != "0"; + + bool IMetalImageCacheOwner.UploadPreludeEnabled => UploadPreludeEnabled; + + private long _preludeHoisted; + private long _preludeFailed; + + // Committed prelude buffers, with the serial whose completion implies theirs. + private readonly List<(nint Buffer, ulong Serial)> _preludeBuffers = []; + private UploadPreludeContext? _preludeContext; + + IMetalSubmissionContext? IMetalImageCacheOwner.BeginUploadPrelude() + { + if (!UploadPreludeEnabled || _commandBuffer == 0 || _renderEncoder == 0 || + EncoderOrdering != EncoderOrderingMode.Fence) + { + return null; + } + + var buffer = NewCommandBuffer(); + if (buffer == 0) + { + throw Fatal("A Metal command buffer could not be created for an upload prelude."); + } + + // Kept until its status is read; the queue hands it back autoreleased. + MetalNative.SendVoid(buffer, SelRetain); + MetalMemoryTelemetry.CommandBuffers.Add(); + // An end-of-pipe completion of the open serial waits for the GPU: the prelude is its work too. + NoteRecordedWork(); + var context = _preludeContext ??= new UploadPreludeContext(this); + context.CommandBuffer = buffer; + return context; + } + + void IMetalImageCacheOwner.EndUploadPrelude(IMetalSubmissionContext prelude) + { + var context = (UploadPreludeContext)prelude; + var buffer = context.CommandBuffer; + context.CommandBuffer = 0; + MetalNative.SendVoid(buffer, SelCommit); + MetalMemoryTelemetry.Commits.Add(); + _preludeBuffers.Add((buffer, _submissionSerial)); + _preludeHoisted++; + } + + // Reads the status of each prelude whose open serial has completed, and lets it go. + private void RetireUploadPreludes(ulong completed, bool all = false) + { + if (_preludeBuffers.Count == 0) + { + return; + } + + var kept = 0; + for (var index = 0; index < _preludeBuffers.Count; index++) + { + var (buffer, serial) = _preludeBuffers[index]; + if (!all && serial > completed) + { + _preludeBuffers[kept++] = _preludeBuffers[index]; + continue; + } + + if (MetalV2Native.SendValue(buffer, MetalNative.Selector("status")) == CommandBufferStatusError) + { + _preludeFailed++; + var error = MetalNative.Send(buffer, MetalNative.Selector("error")); + Console.Error.WriteLine( + $"[METAL-V2][WARN] An upload prelude failed, so a texture it uploaded does not hold the guest's " + + $"bytes: serial={serial} {MetalNative.DescribeError(error)}"); + } + + MetalNative.SendVoid(buffer, SelRelease); + } + + _preludeBuffers.RemoveRange(kept, _preludeBuffers.Count - kept); + } + + /// Prelude buffers whose status has not been read yet. + internal int PendingUploadPreludes => _preludeBuffers.Count; + + // The submission context of a prelude buffer. It borrows under the open buffer's serial and + // orders its encoders with the host's encoder fence; it shares no encoder of the open buffer. + private sealed class UploadPreludeContext(MetalRenderHost host) : IMetalSubmissionContext + { + public nint CommandBuffer { get; set; } + + public nint Device => host._device; + + public ulong SubmissionSerial => host._submissionSerial; + + public ulong CompletedSerial => host.CompletedSerial; + + public void EncoderStarted(nint encoder, bool render) => host.WaitForPreviousEncoder(encoder, render); + + public void EncoderEnding(nint encoder, bool render) => host.UpdateEncoderFence(encoder, render); + } + private static readonly string[] PreludeBlockNames = [ "cause_alias", "cause_gpu", "used", "clear", "gpu_write", "gather", "held_copy", "held_fill", @@ -150,7 +296,8 @@ void IMetalImageCacheOwner.NotePassEndingUpload(MetalImageDirtyCause cause, Meta internal string TakePreludeText() { var builder = new StringBuilder("prelude=[eligible="); - builder.Append(_preludeEligible).Append(" refused=").Append(_preludeRefused); + builder.Append(_preludeEligible).Append(" hoisted=").Append(_preludeHoisted) + .Append(" refused=").Append(_preludeRefused).Append(" failed=").Append(_preludeFailed); for (var index = 0; index < _preludeBlocked.Length; index++) { if (_preludeBlocked[index] != 0) @@ -165,14 +312,16 @@ internal string TakePreludeText() .Append(" gpu=").Append(_passEndUploads[(int)MetalImageDirtyCause.GpuWrite]) .Append(" alias=").Append(_passEndUploads[(int)MetalImageDirtyCause.AliasWrite]).Append(']'); _preludeEligible = 0; + _preludeHoisted = 0; _preludeRefused = 0; + _preludeFailed = 0; Array.Clear(_preludeBlocked); Array.Clear(_passEndUploads); return builder.ToString(); } - /// The prelude counters since the last call, for tests: (eligible, refused, refusals by reason name). - internal (long Eligible, long Refused, Dictionary Blocked) TakePreludeCounters() + /// The prelude counters since the last call, for tests. + internal (long Eligible, long Hoisted, long Refused, long Failed, Dictionary Blocked) TakePreludeCounters() { var blocked = new Dictionary(); for (var index = 0; index < _preludeBlocked.Length; index++) @@ -180,7 +329,7 @@ internal string TakePreludeText() blocked[PreludeBlockNames[index]] = _preludeBlocked[index]; } - var counters = (_preludeEligible, _preludeRefused, blocked); + var counters = (_preludeEligible, _preludeHoisted, _preludeRefused, _preludeFailed, blocked); _ = TakePreludeText(); return counters; } diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.cs index 66dff78ce..7dfbcfd02 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.cs @@ -364,6 +364,7 @@ private nint OpenCommandBuffer() StagingTiler?.TrimStaging(completed); // So are the shader modules and pipeline states past their bound (ShaderCache). MaybeTrimShaderCache(completed); + RetireUploadPreludes(completed); // Every watch whose submission the GPU has finished is checked here, on the one // thread that records them, rather than from the completion handler. _guard?.Verify(completed); @@ -3084,6 +3085,8 @@ public void Dispose() } _scheduleNudge?.Dispose(); + // Committed ahead of the buffer just waited for, so finished with it. + RetireUploadPreludes(CompletedSerial, all: true); ReleaseInFlightSubmissions(); ReportStepCaps(); DisposeStepReport(); diff --git a/tests/SharpEmu.Gpu.Metal.Tests/MetalPassRig.cs b/tests/SharpEmu.Gpu.Metal.Tests/MetalPassRig.cs index f549bd818..542660046 100644 --- a/tests/SharpEmu.Gpu.Metal.Tests/MetalPassRig.cs +++ b/tests/SharpEmu.Gpu.Metal.Tests/MetalPassRig.cs @@ -336,6 +336,9 @@ public byte[] Read(ulong address, ulong bytes) return data; } + // Writes guest memory directly, as a guest CPU store does; nothing the cache watches is told. + public void WriteRaw(ulong address, ReadOnlySpan bytes) => Assert.True(_backing.TryWrite(address, bytes)); + public byte[] ReadRaw(ulong address, ulong bytes) { var data = new byte[bytes]; diff --git a/tests/SharpEmu.Gpu.Metal.Tests/MetalUploadPreludeTests.cs b/tests/SharpEmu.Gpu.Metal.Tests/MetalUploadPreludeTests.cs new file mode 100644 index 000000000..45879d4db --- /dev/null +++ b/tests/SharpEmu.Gpu.Metal.Tests/MetalUploadPreludeTests.cs @@ -0,0 +1,539 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using SharpEmu.Gpu.Metal.V2; +using SharpEmu.HLE; +using SharpEmu.HLE.GpuMemory; +using SharpEmu.Libs.Gpu.Abstractions; +using SharpEmu.Libs.Gpu.Buffers; +using SharpEmu.Libs.Gpu.GpuCommands; +using SharpEmu.Libs.Gpu.Images; +using SharpEmu.Libs.Gpu.Rendering; +using Xunit; +using Xunit.Abstractions; + +namespace SharpEmu.Gpu.Metal.Tests; + +/// +/// SHARPEMU_METAL_V2_UPLOAD_PRELUDE: an upload the CPU caused, needed while a render pass is open, +/// runs in a command buffer committed ahead of the open one instead of ending the pass. Every case +/// runs with the switch on and off and compares the sampled texture (read back on a queue of its +/// own) and the render target's pixels bit for bit; the counters say which arm moved what and why +/// the rest stayed. Device work is behind the exclusive device gate. +/// +public sealed class MetalUploadPreludeTests(ITestOutputHelper output) +{ + // The render target: RGBA8 64x8. + private const uint Width = 64; + private const uint Height = 8; + private const ulong TargetBytes = Width * Height * 4; + + // The sampled textures: linear BC3 64x32 (a block-compressed texture is never a window view, so it + // is uploaded, as Demon's Souls' BC1/BC4/BC7 textures are), 16 bytes a 4x4 block. + private const uint TextureHeight = 32; + private const ulong BlockRowBytes = Width / 4 * 16; + private const ulong ImageBytes = BlockRowBytes * (TextureHeight / 4); + private const uint TallHeight = 256; + private const ulong TallBytes = BlockRowBytes * (TallHeight / 4); + private const ulong TargetAddress = MetalPassRig.GuestBase + 0x10000; + private const ulong FirstAddress = MetalPassRig.GuestBase + 0x20000; + private const ulong SecondAddress = MetalPassRig.GuestBase + 0x30000; + + public enum Scene + { + // A CPU rewrite, the upload with the pass open, a second draw. + Rewrite, + // The same, then a GPU fill over the uploaded bytes recorded after the upload in the open buffer: + // the prelude must have read them before it lands. + RewriteThenGpuFill, + // The texture is sampled in the open buffer before the CPU rewrites it. + SampledEarlier, + // A dispatch store over the source is recorded in the open buffer before the upload. + StoreRecorded, + // A GPU fill over part of the source is recorded in the open buffer before the upload. + FillRecorded, + // An alias drawn and written back over the source in the open buffer before the upload. + AliasWrittenBack, + // A command-processor label held over the source bytes. + HeldLabel, + // Two textures uploaded in one open pass, then the first rewritten and uploaded again. + TwoTexturesThenSecondRewrite, + } + + private sealed record Outcome( + byte[] First, byte[] Second, byte[] Target, long Passes, long Eligible, long Hoisted, long Refused, long Failed, + Dictionary Blocked); + + [Fact] + public void ACpuWrittenTextureUploadedInAnOpenPassDoesNotEndItAndHoldsTheNewBytes() + { + if (!RequireDevice()) return; + var (on, off) = OnAndOff(Scene.Rewrite); + Assert.Equal(1, on.Hoisted); + Assert.Equal(0, on.Refused); + Assert.Equal(1, on.Passes); + Assert.Equal(1, off.Eligible); + Assert.Equal(0, off.Hoisted); + Assert.Equal(2, off.Passes); + Assert.Equal(Pattern(ImageBytes, 0x40), on.First); + AssertSame(on, off); + AssertTargetHalves(on.Target); + } + + [Fact] + public void AGpuFillRecordedAfterTheHoistedUploadDoesNotReachIt() + { + if (!RequireDevice()) return; + var (on, off) = OnAndOff(Scene.RewriteThenGpuFill); + Assert.Equal(1, on.Hoisted); + // The upload read the CPU's bytes, not the fill the open buffer recorded after it. + Assert.Equal(Pattern(ImageBytes, 0x40), on.First); + AssertSame(on, off); + } + + [Fact] + public void ATextureSampledEarlierInTheOpenBufferIsNotHoisted() + { + if (!RequireDevice()) return; + var (on, off) = OnAndOff(Scene.SampledEarlier); + Assert.Equal(0, on.Hoisted); + Assert.Equal(1, on.Refused); + Assert.Equal(1, on.Blocked["used"]); + Assert.Equal(on.Passes, off.Passes); + Assert.Equal(Pattern(ImageBytes, 0x40), on.First); + AssertSame(on, off); + } + + [Theory] + [InlineData(Scene.StoreRecorded)] + [InlineData(Scene.FillRecorded)] + public void AGpuWriteOverTheSourceRecordedInTheOpenBufferIsNotHoisted(Scene scene) + { + if (!RequireDevice()) return; + var (on, off) = OnAndOff(scene); + Assert.Equal(0, on.Hoisted); + Assert.Equal(1, on.Refused); + Assert.Equal(1, on.Blocked["gpu_write"]); + Assert.Equal(on.Passes, off.Passes); + AssertSame(on, off); + } + + [Fact] + public void AnAliasWrittenBackOverTheSourceInTheOpenBufferIsNeverHoisted() + { + if (!RequireDevice()) return; + var (on, off) = OnAndOff(Scene.AliasWrittenBack); + Assert.Equal(0, on.Hoisted); + Assert.Equal(1, on.Refused); + Assert.Equal(1, on.Blocked["cause_alias"]); + Assert.Equal(1, on.Blocked["gpu_write"]); + Assert.Equal(on.Passes, off.Passes); + AssertSame(on, off); + } + + [Fact] + public void AHeldLabelOverTheSourceLandsBeforeTheUploadReadsIt() + { + if (!RequireDevice()) return; + var (on, off) = OnAndOff(Scene.HeldLabel); + Assert.Equal(0, on.Hoisted); + Assert.Equal(on.Passes, off.Passes); + // The label landed before the upload read the bytes, in both arms. + Assert.Equal(LabelValue, BitConverter.ToUInt64(on.First, (int)LabelOffset)); + AssertSame(on, off); + } + + [Fact] + public void TwoTexturesGoAheadOfOnePassAndASecondUploadOfOneStaysInTheBuffer() + { + if (!RequireDevice()) return; + var (on, off) = OnAndOff(Scene.TwoTexturesThenSecondRewrite); + Assert.Equal(2, on.Hoisted); + Assert.Equal(1, on.Refused); + Assert.Equal(1, on.Blocked["used"]); + Assert.True(on.Passes < off.Passes, $"on={on.Passes} off={off.Passes}"); + Assert.Equal(Pattern(ImageBytes, 0x60), on.First); + Assert.Equal(Pattern(ImageBytes, 0x50), on.Second); + AssertSame(on, off); + } + + private (Outcome On, Outcome Off) OnAndOff(Scene scene) + { + var on = Run(scene, prelude: true); + var off = Run(scene, prelude: false); + foreach (var (arm, outcome) in new[] { ("on", on), ("off", off) }) + { + output.WriteLine( + $"{scene} {arm}: passes={outcome.Passes} eligible={outcome.Eligible} hoisted={outcome.Hoisted} " + + $"refused={outcome.Refused} failed={outcome.Failed} " + + string.Join(' ', outcome.Blocked.Where(entry => entry.Value != 0).Select(entry => $"{entry.Key}={entry.Value}"))); + } + + Assert.Equal(0, on.Failed); + return (on, off); + } + + private static void AssertSame(Outcome on, Outcome off) + { + Assert.Equal(off.First, on.First); + Assert.Equal(off.Second, on.Second); + Assert.Equal(off.Target, on.Target); + } + + // Red over the left half, green over the right. + private static void AssertTargetHalves(byte[] pixels) + { + for (var x = 0u; x < Width; x++) + { + var texel = (int)(x * 4); + Assert.Equal(x < Width / 2 ? (byte)0xFF : (byte)0x00, pixels[texel]); + Assert.Equal(x < Width / 2 ? (byte)0x00 : (byte)0xFF, pixels[texel + 1]); + } + } + + private const ulong LabelOffset = 16; + private const ulong LabelValue = 0x1122334455667788; + + private Outcome Run(Scene scene, bool prelude) + { + using var rig = new MetalPassRig(Device.Value, 1024 * 1024); + var host = rig.Host; + host.UploadPreludeEnabled = prelude; + var cache = host.ImageCache; + var store = (IGuestImageStore)cache; + var formats = new[] { GpuFormat.R8G8B8A8Unorm }; + var red = rig.Pipeline(formats, ["1.0f, 0.0f, 0.0f, 1.0f"], -1f, 0f); + var green = rig.Pipeline(formats, ["0.0f, 1.0f, 0.0f, 1.0f"], 0f, 1f); + var target = rig.MakeTarget(TargetAddress, GpuFormat.R8G8B8A8Unorm, Width, Height); + + // Both textures cached and clean, their first uploads finished. + rig.WriteRaw(FirstAddress, Pattern(ImageBytes, 0x10)); + rig.WriteRaw(SecondAddress, Pattern(ImageBytes, 0x20)); + var first = SampledRequest(FirstAddress, TextureHeight); + var second = SampledRequest(SecondAddress, TextureHeight); + var firstId = cache.FindImage(ref first); + var secondId = cache.FindImage(ref second); + Sample(host, firstId, first); + Sample(host, secondId, second); + host.FlushAndWaitForGpu(); + _ = host.TakePreludeCounters(); + var passes = host.RenderPassSerial; + + using (host.BeginPreparation()) + { + if (scene == Scene.AliasWrittenBack) + { + // An R32Uint target over the texture's bytes: drawn, then written back for a host read, all + // in the open buffer. The sampled texture is stale over it as an alias run. + var integer = rig.Pipeline([GpuFormat.R32Uint], ["0x7u, 0u, 0u, 0u"]); + var alias = rig.MakeTarget(FirstAddress, GpuFormat.R32Uint, Width, (uint)(ImageBytes / (Width * 4))); + rig.Draw(integer, [alias]); + cache.FlushGpuWrites(FirstAddress, ImageBytes, MetalWritebackCause.HostRead); + } + + rig.Draw(red, [target]); + } + + if (scene == Scene.SampledEarlier) + { + Sample(host, firstId, first); + } + + if (scene != Scene.AliasWrittenBack) + { + CpuWrite(rig, store, FirstAddress, Pattern(ImageBytes, 0x40)); + } + + if (scene == Scene.HeldLabel) + { + // A label recorded over the source while the pass is open is held for the boundary; recording it + // ends the pass, so the upload meets none, and the copy lands before the upload reads the bytes. + // The prelude's own guard against a held copy over the source is read directly. + host.RecordEndOfPipe(new EndOfPipeWrite(EndOfPipeWriteKind.Write64, 1, FirstAddress + LabelOffset, LabelValue)); + Assert.Equal(1, host.DeferredLabelCopyCount); + var owner = (IMetalImageCacheOwner)host; + Assert.True(owner.PreludeBlocks(0, FirstAddress, ImageBytes).HasFlag(MetalPreludeBlock.HeldCopy)); + Assert.False(owner.PreludeBlocks(0, SecondAddress, ImageBytes).HasFlag(MetalPreludeBlock.HeldCopy)); + } + + if (scene == Scene.StoreRecorded) + { + // A compute store into the source, as a dispatch of the open buffer records it. + host.NoteGuestMemoryWrite(FirstAddress + 0x100, 0x40, MetalGpuWriteOrigin.StorageBuffer); + } + + if (scene == Scene.FillRecorded) + { + host.FillGuestMemory(FirstAddress + 0x100, 0x100, 0xA5A5A5A5, allowHost: false); + using (host.BeginPreparation()) + { + rig.Draw(red, [target]); + } + } + + if (scene == Scene.TwoTexturesThenSecondRewrite) + { + CpuWrite(rig, store, SecondAddress, Pattern(ImageBytes, 0x50)); + } + + Sample(host, firstId, first); + if (scene == Scene.TwoTexturesThenSecondRewrite) + { + Sample(host, secondId, second); + } + + if (scene == Scene.RewriteThenGpuFill) + { + host.FillGuestMemory(FirstAddress + 0x100, 0x100, 0xA5A5A5A5, allowHost: false); + } + + using (host.BeginPreparation()) + { + rig.Draw(green, [target]); + } + + if (scene == Scene.TwoTexturesThenSecondRewrite) + { + CpuWrite(rig, store, FirstAddress, Pattern(ImageBytes, 0x60)); + Sample(host, firstId, first); + using (host.BeginPreparation()) + { + rig.Draw(green, [target]); + } + } + + host.EndRendering(); + var drawnPasses = host.RenderPassSerial - passes; + host.FlushAndWaitForGpu(); + var (eligible, hoisted, refused, failed, blocked) = host.TakePreludeCounters(); + var firstTexels = ReadTexture(cache.GetImage(firstId).Texture, TextureHeight); + var secondTexels = ReadTexture(cache.GetImage(secondId).Texture, TextureHeight); + var pixels = rig.Read(TargetAddress, TargetBytes); + Assert.Equal(0, host.PendingUploadPreludes); + return new Outcome(firstTexels, secondTexels, pixels, drawnPasses, eligible, hoisted, refused, failed, blocked); + } + + // ---- Run sets: an image stale over several runs ------------------------------------------------------------- + + private sealed record RunsOutcome(byte[] Texels, long Passes, long Hoisted, long Refused, Dictionary Blocked); + + // Two CPU-written block rows of a 64-block-row texture are two stale runs: each goes ahead of the pass on its own. + // With a third run an alias hand-over marked, nothing of the image goes ahead: its stale causes include + // the alias, whatever run each cause marked. + [Theory] + [InlineData(false)] + [InlineData(true)] + public void AnImageStaleOverSeveralRunsIsHoistedPerRunOnlyWhenNoRunIsAnAliasRun(bool aliasRun) + { + if (!RequireDevice()) return; + var on = RunSets(aliasRun, prelude: true); + var off = RunSets(aliasRun, prelude: false); + output.WriteLine($"alias_run={aliasRun} on: passes={on.Passes} hoisted={on.Hoisted} refused={on.Refused}"); + output.WriteLine($"alias_run={aliasRun} off: passes={off.Passes} hoisted={off.Hoisted} refused={off.Refused}"); + if (aliasRun) + { + Assert.Equal(0, on.Hoisted); + Assert.Equal(1, on.Blocked["cause_alias"]); + } + else + { + Assert.Equal(2, on.Hoisted); + Assert.Equal(0, on.Refused); + Assert.Equal(1, on.Passes); + } + + Assert.Equal(off.Texels, on.Texels); + } + + private RunsOutcome RunSets(bool aliasRun, bool prelude) + { + using var rig = new MetalPassRig(Device.Value, 1024 * 1024); + var host = rig.Host; + host.UploadPreludeEnabled = prelude; + var cache = host.ImageCache; + var store = (IGuestImageStore)cache; + var red = rig.Pipeline([GpuFormat.R8G8B8A8Unorm], ["1.0f, 0.0f, 0.0f, 1.0f"]); + var target = rig.MakeTarget(TargetAddress, GpuFormat.R8G8B8A8Unorm, Width, Height); + rig.WriteRaw(FirstAddress, Pattern(TallBytes, 0x10)); + var request = SampledRequest(FirstAddress, TallHeight); + var id = cache.FindImage(ref request); + Sample(host, id, request); + host.FlushAndWaitForGpu(); + _ = host.TakePreludeCounters(); + var passes = host.RenderPassSerial; + using (host.BeginPreparation()) + { + rig.Draw(red, [target]); + } + + const ulong row = BlockRowBytes; + CpuWrite(rig, store, FirstAddress + (2 * row), Pattern(row, 0x70)); + CpuWrite(rig, store, FirstAddress + (40 * row), Pattern(row, 0x80)); + var image = cache.GetImage(id); + if (aliasRun) + { + // Model only: guest memory is unchanged there, so the reload carries the same bytes. + image.MarkCpuDirty(MetalImageDirtyCause.AliasWrite, 20 * row, 21 * row); + } + + Assert.Equal(aliasRun ? 3 : 2, image.StaleRunCount); + Sample(host, id, request); + Assert.False(image.IsCpuDirty); + host.EndRendering(); + var drawn = host.RenderPassSerial - passes; + host.FlushAndWaitForGpu(); + var (_, hoisted, refused, _, blocked) = host.TakePreludeCounters(); + return new RunsOutcome(ReadTexture(image.Texture, TallHeight), drawn, hoisted, refused, blocked); + } + + // ---- Lifetime -------------------------------------------------------------------------------------------------- + + // What a prelude borrows is the open buffer's: staging lent to it is counted against that buffer and is + // not lent again until the open buffer has completed, which is after the prelude. + [Fact] + public void APreludesStagingIsNotLentAgainBeforeTheOpenBufferCompletes() + { + if (!RequireDevice()) return; + using var rig = new MetalPassRig(Device.Value, 1024 * 1024); + var host = rig.Host; + host.UploadPreludeEnabled = true; + var owner = (IMetalImageCacheOwner)host; + var red = rig.Pipeline([GpuFormat.R8G8B8A8Unorm], ["1.0f, 0.0f, 0.0f, 1.0f"]); + var target = rig.MakeTarget(TargetAddress, GpuFormat.R8G8B8A8Unorm, Width, Height); + using (host.BeginPreparation()) + { + rig.Draw(red, [target]); + } + + var passes = host.RenderPassSerial; + var open = host.SubmissionSerial; + var transient = host.RecordingTransientBytes; + const ulong size = 64 * 1024; + var spans = new List(); + for (var index = 0; index < 2; index++) + { + var prelude = owner.BeginUploadPrelude(); + Assert.NotNull(prelude); + Assert.Equal(open, prelude!.SubmissionSerial); + Assert.NotEqual(host.CommandBuffer, prelude.CommandBuffer); + spans.Add(host.StagingTiler!.Acquire(prelude, size)); + owner.EndUploadPrelude(prelude); + } + + // The pass is still open and the buffer still the same; both spans are the open buffer's. + Assert.Equal(passes, host.RenderPassSerial); + Assert.Equal(open, host.SubmissionSerial); + Assert.True(host.RecordingTransientBytes >= transient + (2 * size), $"transient={host.RecordingTransientBytes}"); + Assert.False(Overlap(spans[0], spans[1])); + Assert.Equal(2, host.PendingUploadPreludes); + + // Trimming at what has completed so far frees neither: the open buffer has not even been committed. + host.StagingTiler!.TrimStaging(host.CompletedSerial); + var third = owner.BeginUploadPrelude()!; + var again = host.StagingTiler.Acquire(third, size); + owner.EndUploadPrelude(third); + Assert.False(Overlap(again, spans[0])); + Assert.False(Overlap(again, spans[1])); + + host.EndRendering(); + host.FlushAndWaitForGpu(); + Assert.True(host.CompletedSerial >= open); + // The next buffer reads each prelude's status once the open serial has completed. + _ = host.SubmissionSerial; + Assert.Equal(0, host.PendingUploadPreludes); + var (_, hoisted, _, failed, _) = host.TakePreludeCounters(); + Assert.Equal(3, hoisted); + Assert.Equal(0, failed); + } + + private static bool Overlap(MetalBufferSpan a, MetalBufferSpan b) => + a.Buffer == b.Buffer && a.Offset < b.Offset + b.Size && b.Offset < a.Offset + a.Size; + + // ---- Helpers --------------------------------------------------------------------------------------------------- + + private static void CpuWrite(MetalPassRig rig, IGuestImageStore store, ulong address, byte[] bytes) + { + rig.WriteRaw(address, bytes); + Assert.True(store.MarkPreciseCpuWrite(address, (ulong)bytes.Length)); + } + + private static void Sample(MetalRenderHost host, ResourceSlotIdentifier id, ImageRequest request) + { + using (host.BeginPreparation()) + { + Assert.NotEqual(0, host.ImageCache.AcquireTextureView(id, in request)); + } + } + + private static byte[] Pattern(ulong size, byte seed) + { + var bytes = new byte[size]; + for (var index = 0; index < bytes.Length; index++) + { + bytes[index] = (byte)(seed + (index * 7) + (index >> 8)); + } + + return bytes; + } + + private static ImageRequest SampledRequest(ulong address, uint height) + { + var bytes = BlockRowBytes * (height / 4); + var description = ImageDescription.Create(); + description.Data = new GuestSpan(address, bytes); + description.PixelFormat = GpuFormat.BC3UnormBlock; + description.GuestFormat = GuestPixelFormat.Bc3UNorm; + description.Type = GuestImageType.Color2D; + description.Extent = new GpuExtent3D(Width, height, 1); + description.Resources = new SubresourceCount(1, 1); + description.Pitch = Width; + description.BytesPerBlock = 16; + description.Samples = 1; + description.TileMode = GuestTileMode.Linear; + description.MipLayout[0] = new MipLevelLayout { Offset = 0, Size = bytes, Pitch = Width, Height = height }; + var view = ImageViewDescription.Default with + { + Format = GpuFormat.BC3UnormBlock, + Type = GpuImageViewType.Type2D, + Aspect = GpuImageAspect.ColorBit, + LayerCount = 1, + Usage = GpuImageUsage.SampledBit, + }; + return new ImageRequest(description, view, ImageRole.Texture); + } + + // The texture's texels through a blit on a queue of its own, after the host's work has finished. + private static byte[] ReadTexture(nint texture, uint height) + { + using var harness = new MetalTransferHarness(Device.Value); + var size = BlockRowBytes * (height / 4); + var buffer = harness.Buffer(size); + harness.Begin(); + var blit = MetalNative.Send(harness.CommandBuffer, MetalNative.Selector("blitCommandEncoder")); + MetalNative.SendCopyTextureToBufferOptions( + blit, + MetalNative.Selector( + "copyFromTexture:sourceSlice:sourceLevel:sourceOrigin:sourceSize:" + + "toBuffer:destinationOffset:destinationBytesPerRow:destinationBytesPerImage:options:"), + texture, 0, 0, default, new MtlSize { Width = Width, Height = height, Depth = 1 }, + buffer, 0, (nuint)BlockRowBytes, (nuint)size, 0); + MetalNative.SendVoid(blit, MetalNative.Selector("endEncoding")); + harness.Submit(); + return harness.Read(buffer, 0, size); + } + + private bool RequireDevice() + { + if (Environment.GetEnvironmentVariable("SHARPEMU_TEST_REQUIRE_DEVICE") != "1") + { + output.WriteLine("Upload preludes are encoded on the device only behind the exclusive device gate."); + return false; + } + + Assert.True(OperatingSystem.IsMacOS()); + Assert.NotEqual(0, Device.Value); + return true; + } + + private static readonly Lazy Device = new(MetalNative.MTLCreateSystemDefaultDevice); +} From e4fa880c4f01e565e2a4f704e918d1da0c274ff2 Mon Sep 17 00:00:00 2001 From: kuba Date: Sun, 15 Nov 2026 08:43:18 +0000 Subject: [PATCH 044/178] [Metal] Upload prelude: an upload that encoded nothing is not counted as hoisted --- .../V2/MetalImageCache.UploadPrelude.cs | 5 +++++ .../SharpEmu.Gpu.Metal/V2/MetalImageCache.cs | 5 +++++ .../V2/MetalRenderHost.UploadPrelude.cs | 13 ++++++++++++- 3 files changed, 22 insertions(+), 1 deletion(-) diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.UploadPrelude.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.UploadPrelude.cs index 966ded929..a2697fe9d 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.UploadPrelude.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.UploadPrelude.cs @@ -107,6 +107,11 @@ private bool TryUploadInPrelude( _owner.EndUploadPrelude(prelude); } + if (!moved) + { + _owner.NoteUploadPreludeUnencoded(); + } + return true; } diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.cs index b0f0684a2..740fc7471 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.cs @@ -68,6 +68,11 @@ void EndUploadPrelude(IMetalSubmissionContext prelude) { } + // The upload a prelude was begun for encoded nothing. + void NoteUploadPreludeUnencoded() + { + } + // Copies the guest bytes of a range into its staged (ring) copy on the GPU, behind the work still // writing them, so a transfer reading the staged copy next sees what that work leaves there. void GatherStagedRange(ulong address, in MetalGuestRange staging) diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.UploadPrelude.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.UploadPrelude.cs index 82e90ca80..124d49abc 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.UploadPrelude.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.UploadPrelude.cs @@ -107,6 +107,7 @@ internal sealed partial class MetalRenderHost private long _preludeHoisted; private long _preludeFailed; + private long _preludeUnencoded; // Committed prelude buffers, with the serial whose completion implies theirs. private readonly List<(nint Buffer, ulong Serial)> _preludeBuffers = []; @@ -147,6 +148,14 @@ void IMetalImageCacheOwner.EndUploadPrelude(IMetalSubmissionContext prelude) _preludeHoisted++; } + // The upload refused to encode after its prelude was begun: the buffer went out with nothing of the image in + // it and the image stays stale, so it is not a hoist. + void IMetalImageCacheOwner.NoteUploadPreludeUnencoded() + { + _preludeHoisted--; + _preludeUnencoded++; + } + // Reads the status of each prelude whose open serial has completed, and lets it go. private void RetireUploadPreludes(ulong completed, bool all = false) { @@ -297,7 +306,8 @@ internal string TakePreludeText() { var builder = new StringBuilder("prelude=[eligible="); builder.Append(_preludeEligible).Append(" hoisted=").Append(_preludeHoisted) - .Append(" refused=").Append(_preludeRefused).Append(" failed=").Append(_preludeFailed); + .Append(" refused=").Append(_preludeRefused).Append(" failed=").Append(_preludeFailed) + .Append(" unencoded=").Append(_preludeUnencoded); for (var index = 0; index < _preludeBlocked.Length; index++) { if (_preludeBlocked[index] != 0) @@ -315,6 +325,7 @@ internal string TakePreludeText() _preludeHoisted = 0; _preludeRefused = 0; _preludeFailed = 0; + _preludeUnencoded = 0; Array.Clear(_preludeBlocked); Array.Clear(_passEndUploads); return builder.ToString(); From 4ebaf440d39aac9f8b6901902d044f2c5d9f0934 Mon Sep 17 00:00:00 2001 From: kuba Date: Sun, 15 Nov 2026 09:22:37 +0000 Subject: [PATCH 045/178] [Metal] Read-binding memo: 16384x4 table with move-to-front, refusals split by cause on the PERF line The v1 table held 4096 entries (2048 sets x 2 ways) against some 20k distinct read-only ranges a Demon's Souls frame binds, so most lookups missed on capacity. It now holds 65536 (16384 sets x 4 ways, least recently used evicted; SHARPEMU_METAL_V2_READ_BINDING_MEMO_SETS= for A/B). The single refused counter is split into refused_by=(trace,unmapped,window,fill,label,staged), one per refused lookup, plus store_after_refusal. A test binds 20k distinct ranges twice and needs 99% hits on the second pass. --- .../V2/MetalReadBindingMemo.cs | 141 +++++++++++++----- .../V2/MetalRenderHost.ReadBindingMemo.cs | 57 ++++++- .../MetalClearFoldingTests.ReadBindingMemo.cs | 26 ++++ 3 files changed, 180 insertions(+), 44 deletions(-) diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalReadBindingMemo.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalReadBindingMemo.cs index ebb15a19c..f94b78079 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalReadBindingMemo.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalReadBindingMemo.cs @@ -35,10 +35,44 @@ private struct Entry public MetalGuestRange Range; } - // Two ways per set, the more recently used first: a frame's command buffer binds a few thousand ranges, which - // direct-mapped slots lost to collisions (most of the DsDrawCostBench draws' misses before). - private const int Sets = 2048; - private readonly Entry[] _entries = new Entry[Sets * 2]; + /// Ways per set, the most recently used first (move-to-front); the last one is evicted. + internal const int Ways = 4; + + /// + /// Sets in the table. A Demon's Souls frame binds some 20k distinct read-only ranges, which come back a frame later; + /// 2048 sets of two ways lost nearly all of them to evictions. 16384 sets of four hold 65536 entries (about 0.3-0.5 + /// of them in use), so few sets overflow. SHARPEMU_METAL_V2_READ_BINDING_MEMO_SETS=<power of two> (diagnostic). + /// + internal static readonly int DefaultSets = ResolveSets(Environment.GetEnvironmentVariable("SHARPEMU_METAL_V2_READ_BINDING_MEMO_SETS")); + + internal static int ResolveSets(string? configured) + { + const int sets = 16384; + if (configured is null) + { + return sets; + } + + if (int.TryParse(configured, out var value) && value >= 1 && value <= (1 << 22) && System.Numerics.BitOperations.IsPow2(value)) + { + return value; + } + + MetalV2Diagnostics.WarnOnce( + "read-binding-memo-sets", + $"SHARPEMU_METAL_V2_READ_BINDING_MEMO_SETS={configured} is not a power of two from 1 to 4194304; using {sets}."); + return sets; + } + + private readonly int _setMask; + private readonly Entry[] _entries; + + public MetalReadBindingMemo(int sets = 0) + { + sets = sets == 0 ? DefaultSets : sets; + _setMask = sets - 1; + _entries = new Entry[sets * Ways]; + } public long Hits; public long Misses; @@ -46,48 +80,77 @@ private struct Entry public long Verified; // Why lookups missed: an empty set, other ranges' entries in it (collisions or evictions), or this range's - // entry with another alias or stamp (each field that moved counts, so they can add up past the misses); refused - // are the caller's live refusals and windows that no longer stand. Evictions are stores over another range's entry. + // entry with another alias or stamp (each field that moved counts, so they can add up past the misses). + // Evictions are stores over another range's entry. public long MissEmpty, MissOtherKey, MissAlias, MissSerial, MissPartition, MissTrap, MissImageSet, MissGpuModified; - public long MissRefused, Evictions; + public long Evictions; + + // The caller's live refusals, one per refused lookup, the first that applied: a trace on, the range not mapped + // whole, a deferred fill, a held label copy or a staged copy at all, or a matched entry whose window no longer + // stands. StoreAfterRefusal: stores after a lookup refused for pending work. + public long RefusedTrace, RefusedUnmapped, RefusedFill, RefusedLabel, RefusedStaged, RefusedWindow; + public long StoreAfterRefusal; - private static int SetOf(ulong address, ulong size, bool compute) + internal int SetOf(ulong address, ulong size, bool compute) => SetIndex(address, size, compute, _setMask); + + internal static int SetIndex(ulong address, ulong size, bool compute, int setMask) { var hash = ((address >> 4) * 0x9E3779B97F4A7C15UL) ^ (size * 0xC2B2AE3D27D4EB4FUL) ^ (compute ? 0x165667B19E3779F9UL : 0UL); - return (int)((hash ^ (hash >> 29)) >> 40) & (Sets - 1); + return (int)((hash ^ (hash >> 29)) >> 40) & setMask; } private static bool Holds(in Entry entry, ulong address, ulong size, bool compute) => entry.Valid && entry.Address == address && entry.Size == size && entry.Compute == compute; - /// The range kept for this binding at this stamp and alias, if one is. - public bool TryGet(ulong address, ulong size, bool compute, ulong alias, in Stamp stamp, out MetalGuestRange range) + // The way holding the range moved to the front of its set; false when no way does. + private bool TryFront(int first, ulong address, ulong size, bool compute) { - var way = SetOf(address, size, compute) * 2; - ref var first = ref _entries[way]; - if (!Holds(in first, address, size, compute)) + var set = _entries.AsSpan(first, Ways); + if (Holds(in set[0], address, size, compute)) + { + return true; + } + + for (var way = 1; way < Ways; way++) { - ref var second = ref _entries[way + 1]; - if (Holds(in second, address, size, compute)) + if (Holds(in set[way], address, size, compute)) { - (first, second) = (second, first); + var found = set[way]; + set[..way].CopyTo(set[1..]); + set[0] = found; + return true; } - else + } + + return false; + } + + /// The range kept for this binding at this stamp and alias, if one is. + public bool TryGet(ulong address, ulong size, bool compute, ulong alias, in Stamp stamp, out MetalGuestRange range) + { + var first = SetOf(address, size, compute) * Ways; + if (!TryFront(first, address, size, compute)) + { + var any = false; + for (var way = 0; way < Ways; way++) { - MissEmpty += !first.Valid && !second.Valid ? 1 : 0; - MissOtherKey += first.Valid || second.Valid ? 1 : 0; - range = default; - return false; + any |= _entries[first + way].Valid; } + + MissEmpty += any ? 0 : 1; + MissOtherKey += any ? 1 : 0; + range = default; + return false; } - if (first.Alias == alias && first.Stamp == stamp) + ref var front = ref _entries[first]; + if (front.Alias == alias && front.Stamp == stamp) { - range = first.Range; + range = front.Range; return true; } - NoteStale(in first, alias, in stamp); + NoteStale(in front, alias, in stamp); range = default; return false; } @@ -104,19 +167,16 @@ private void NoteStale(in Entry entry, ulong alias, in Stamp stamp) public void Store(ulong address, ulong size, bool compute, ulong alias, in Stamp stamp, in MetalGuestRange range) { - var way = SetOf(address, size, compute) * 2; - if (!Holds(in _entries[way], address, size, compute)) + var first = SetOf(address, size, compute) * Ways; + if (!TryFront(first, address, size, compute)) { - if (!Holds(in _entries[way + 1], address, size, compute)) - { - // The less recently used way goes; the new entry takes the front. - Evictions += _entries[way + 1].Valid ? 1 : 0; - } - - _entries[way + 1] = _entries[way]; + // The least recently used way goes; the new entry takes the front. + var set = _entries.AsSpan(first, Ways); + Evictions += set[Ways - 1].Valid ? 1 : 0; + set[..(Ways - 1)].CopyTo(set[1..]); } - ref var entry = ref _entries[way]; + ref var entry = ref _entries[first]; entry.Address = address; entry.Size = size; entry.Alias = alias; @@ -130,13 +190,14 @@ public void Store(ulong address, ulong size, bool compute, ulong alias, in Stamp /// hits, misses (and why), stores, evictions and verified hits since the last call; resets them. public string TakeCounters() { - var text = $"hits={Hits} misses={Misses} stores={Stores} verified={Verified} " + + var text = $"hits={Hits} misses={Misses} stores={Stores} verified={Verified} evictions={Evictions} " + $"miss_by=(empty={MissEmpty},other_key={MissOtherKey},alias={MissAlias},serial={MissSerial}," + - $"partition={MissPartition},trap={MissTrap},image_set={MissImageSet},gpu_modified={MissGpuModified}," + - $"refused={MissRefused}) evictions={Evictions}"; - Hits = Misses = Stores = Verified = 0; + $"partition={MissPartition},trap={MissTrap},image_set={MissImageSet},gpu_modified={MissGpuModified}) " + + $"refused_by=(trace={RefusedTrace},unmapped={RefusedUnmapped},window={RefusedWindow},fill={RefusedFill}," + + $"label={RefusedLabel},staged={RefusedStaged}) store_after_refusal={StoreAfterRefusal}"; + Hits = Misses = Stores = Verified = Evictions = 0; MissEmpty = MissOtherKey = MissAlias = MissSerial = MissPartition = MissTrap = MissImageSet = MissGpuModified = 0; - MissRefused = Evictions = 0; + RefusedTrace = RefusedUnmapped = RefusedFill = RefusedLabel = RefusedStaged = RefusedWindow = StoreAfterRefusal = 0; return text; } } diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.ReadBindingMemo.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.ReadBindingMemo.cs index d847582cb..d29bd84ac 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.ReadBindingMemo.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.ReadBindingMemo.cs @@ -60,6 +60,43 @@ internal sealed partial class MetalRenderHost ReadBindingMemoEnabled && _deferredFills.Count == 0 && _deferredLabelCopies.Count == 0 && _stagedStorageCopies is not { Count: > 0 } && ReadBindingTracesOff; + // A lookup refused for pending work (a fill, a label copy or a staged copy): the store after its chain is counted. + private bool _readBindingRefusedPending; + + // Counts the first reason ReadBindingMemoApplies (or the range's mapping) refused a lookup. + private void NoteReadBindingRefusal(bool unmapped) + { + var memo = _readBindingMemo; + memo.Misses++; + if (!ReadBindingTracesOff) + { + memo.RefusedTrace++; + } + else if (_deferredFills.Count != 0) + { + memo.RefusedFill++; + _readBindingRefusedPending = true; + } + else if (_deferredLabelCopies.Count != 0) + { + memo.RefusedLabel++; + _readBindingRefusedPending = true; + } + else if (_stagedStorageCopies is { Count: > 0 }) + { + memo.RefusedStaged++; + _readBindingRefusedPending = true; + } + else if (unmapped) + { + memo.RefusedUnmapped++; + } + else + { + throw Fatal("A read-only binding memo lookup was refused with nothing to refuse it."); + } + } + private MetalReadBindingMemo.Stamp ReadBindingStamp() { var (serial, partition, trap) = _guestMemory.InPlaceStamp; @@ -75,10 +112,16 @@ private bool TryReadBindingMemo(ulong address, ulong size, bool computeStage, ou return false; } - if (!ReadBindingMemoApplies || !_backing.TryResolveBackingAliasSpan(address, size, out var alias)) + _readBindingRefusedPending = false; + if (!ReadBindingMemoApplies) { - _readBindingMemo.Misses++; - _readBindingMemo.MissRefused++; + NoteReadBindingRefusal(unmapped: false); + return false; + } + + if (!_backing.TryResolveBackingAliasSpan(address, size, out var alias)) + { + NoteReadBindingRefusal(unmapped: true); return false; } @@ -88,7 +131,7 @@ private bool TryReadBindingMemo(ulong address, ulong size, bool computeStage, ou if (range.IsValid) { // The entry matched; the window under it no longer stands. - _readBindingMemo.MissRefused++; + _readBindingMemo.RefusedWindow++; } _readBindingMemo.Misses++; @@ -113,6 +156,12 @@ private void StoreReadBinding( return; } + if (_readBindingRefusedPending) + { + _readBindingMemo.StoreAfterRefusal++; + _readBindingRefusedPending = false; + } + _readBindingMemo.Store(address, size, computeStage, inPlaceAlias, before, range); } diff --git a/tests/SharpEmu.Gpu.Metal.Tests/MetalClearFoldingTests.ReadBindingMemo.cs b/tests/SharpEmu.Gpu.Metal.Tests/MetalClearFoldingTests.ReadBindingMemo.cs index cc67a1bed..923f03fed 100644 --- a/tests/SharpEmu.Gpu.Metal.Tests/MetalClearFoldingTests.ReadBindingMemo.cs +++ b/tests/SharpEmu.Gpu.Metal.Tests/MetalClearFoldingTests.ReadBindingMemo.cs @@ -154,4 +154,30 @@ public void AReadOnlyBindingMissesInANewCommandBuffer() AssertMisses(host, () => BindRead(host), before); host.FlushAndWaitForGpu(); } + + // C1: a frame's worth of distinct read-only ranges (Demon's Souls binds some 20k a frame) is held whole: binding + // them all a second time hits nearly every one. + [Fact] + public void TwentyThousandDistinctReadOnlyRangesBoundTwiceHitOnTheSecondPass() + { + if (!RequireDevice()) return; + using var rig = MemoRig(); + var host = rig.Host; + // Verifying each hit runs the whole chain again; this test is about capacity, the others about soundness. + host.ReadBindingMemoVerify = false; + const int ranges = 20000; + for (var index = 0; index < ranges; index++) + { + BindRead(host, MemoBuffer + ((ulong)index * 0x80), 0x40); + } + + var hits = host.ReadBindingMemoCounts.Hits; + for (var index = 0; index < ranges; index++) + { + BindRead(host, MemoBuffer + ((ulong)index * 0x80), 0x40); + } + + var secondPassHits = host.ReadBindingMemoCounts.Hits - hits; + Assert.True(secondPassHits >= ranges * 99 / 100, $"second pass hits {secondPassHits} of {ranges}"); + } } From d481950e7dcaadda89035d5366ba889a759bc87a Mon Sep 17 00:00:00 2001 From: kuba Date: Sun, 15 Nov 2026 09:28:07 +0000 Subject: [PATCH 046/178] [Metal] Read-binding memo v2: entries keyed to their window object, valid across command buffers and unrelated cuts MetalReadBindingMemoV2 (default on; SHARPEMU_METAL_V2_READ_BINDING_MEMO_RANGES=0 keeps the v1 class and gating) drops the submission serial and the partition version from what an entry depends on. A window now carries a Retired flag set when MetalWindowPartition.Replace takes it out (a cut move, a cut back to granules, a renewal), and the resolve hands out the window it placed the range in. A hit needs that window not retired with the same buffer, and does what the resolve did once per command buffer (MetalGuestMemory.UseWindowForHit: pin, last use, touch/residency; the same UseWindowLocked/NoteTouched the full path now calls), free once the window is pinned and touched in this command buffer. The global pending-work refusal and the trap/image stamps stay as in v1 for now. Placement runs on the worker only (BeginSubmission, the worker's resolves, ApplySingleCopyFills from device-address preparation), and the first use per command buffer re-checks Retired under the window lock. Verify mode also checks, behind every v2 hit, that the hit pinned and touched its window and that the full chain landed nothing (label copies, fills, pass ends, encoders, window moves and renewals, image writebacks). Tests: W1 (new command buffer hits, window pinned: a crossing range conflicts), W2 (own window re-cut misses, another cut hits), W3 (idle cut-back misses), W4 (remap elsewhere hits), the v1 new-command-buffer miss, and the binding-reuse scene in both modes. --- .../SharpEmu.Gpu.Metal/V2/MetalGuestMemory.cs | 127 ++++++++--- .../V2/MetalReadBindingMemoV2.cs | 205 +++++++++++++++++ .../V2/MetalRenderHost.Descriptors.cs | 4 +- .../V2/MetalRenderHost.ReadBindingMemo.cs | 63 +++++- .../MetalRenderHost.ReadBindingMemoRanges.cs | 211 ++++++++++++++++++ .../V2/MetalRenderHost.StagedStorage.cs | 12 +- .../SharpEmu.Gpu.Metal/V2/MetalRenderHost.cs | 5 +- .../V2/MetalWindowPartition.cs | 6 + .../MetalClearFoldingTests.ReadBindingMemo.cs | 134 ++++++++++- .../MetalClearFoldingTests.cs | 20 +- .../Scenes/BindingReuseSceneTests.cs | 27 ++- 11 files changed, 762 insertions(+), 52 deletions(-) create mode 100644 src/graphics/SharpEmu.Gpu.Metal/V2/MetalReadBindingMemoV2.cs create mode 100644 src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.ReadBindingMemoRanges.cs diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalGuestMemory.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalGuestMemory.cs index d84c614b8..7351610f1 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalGuestMemory.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalGuestMemory.cs @@ -732,12 +732,22 @@ public bool TryResolveInPlace(ulong gpuVa, ulong size, out MetalGuestRange range TryResolveInPlace(gpuVa, size, out range, out _); /// , with the backing alias the range was placed by. - public bool TryResolveInPlace(ulong gpuVa, ulong size, out MetalGuestRange range, out ulong alias) + public bool TryResolveInPlace(ulong gpuVa, ulong size, out MetalGuestRange range, out ulong alias) => + TryResolveInPlace(gpuVa, size, out range, out alias, out _); + + /// + /// , with the window the range was + /// placed in (MetalReadBindingMemoV2 checks it is still in the partition). + /// + internal bool TryResolveInPlace( + ulong gpuVa, ulong size, out MetalGuestRange range, out ulong alias, out MetalWindowPartition.Window? window) { range = default; alias = 0; - if (StageEverything || !TryResolveWindow(gpuVa, size, out range, out alias)) + window = null; + if (StageEverything || !TryResolveWindow(gpuVa, size, out range, out alias, out window)) { + window = null; return false; } @@ -755,6 +765,9 @@ public bool TryResolveInPlace(ulong gpuVa, ulong size, out MetalGuestRange range internal (ulong Serial, long Partition, long Trap) InPlaceStamp => (Volatile.Read(ref _submissionSerial), _partition.Version, Volatile.Read(ref _trapVersion)); + /// The single-copy trap version (holes and stale windows), read without the window lock on the worker. + internal long TrapVersionNow => Volatile.Read(ref _trapVersion); + /// /// Whether of a range that translates to , resolved in /// place earlier at the current , would give the same window range now and do nothing @@ -1112,9 +1125,10 @@ private sealed class WindowMemoEntry( internal (long Hits, long Misses) WindowMemoCounts => (Volatile.Read(ref _windowMemoHits), Volatile.Read(ref _windowMemoMisses)); - private bool TryResolveWindowFromMemo(ulong offset, ulong size, out MetalGuestRange resolved) + private bool TryResolveWindowFromMemo(ulong offset, ulong size, out MetalGuestRange resolved, out MetalWindowPartition.Window? used) { resolved = default; + used = null; if (Trap is not null || (_singleCopy is { } singleCopy && singleCopy.AnyReleased(offset, size))) { return false; @@ -1136,6 +1150,7 @@ private bool TryResolveWindowFromMemo(ulong offset, ulong size, out MetalGuestRa var windowOffset = offset - entry.Window.Start; resolved = new MetalGuestRange(entry.Buffer, windowOffset, size, entry.Window.GpuAddress + windowOffset); + used = entry.Window; Interlocked.Increment(ref _windowMemoHits); return true; } @@ -1174,12 +1189,16 @@ private void PublishWindowMemoLocked(MetalWindowPartition.Window window, ulong o private bool TryResolveWindow(ulong gpuVa, ulong size, out MetalGuestRange resolved, bool warn = true) => TryResolveWindow(gpuVa, size, out resolved, out _, warn); - private bool TryResolveWindow(ulong gpuVa, ulong size, out MetalGuestRange resolved, out ulong alias, bool warn = true) + private bool TryResolveWindow(ulong gpuVa, ulong size, out MetalGuestRange resolved, out ulong alias, bool warn = true) => + TryResolveWindow(gpuVa, size, out resolved, out alias, out _, warn); + + private bool TryResolveWindow( + ulong gpuVa, ulong size, out MetalGuestRange resolved, out ulong alias, out MetalWindowPartition.Window? used, bool warn = true) { - var ok = TryResolveWindowCore(gpuVa, size, out resolved, out alias, warn, WindowMemoEnabled); + var ok = TryResolveWindowCore(gpuVa, size, out resolved, out alias, out used, warn, WindowMemoEnabled); if (WindowMemoVerify && WindowMemoEnabled) { - var fullOk = TryResolveWindowCore(gpuVa, size, out var full, out _, warn: false, useMemo: false); + var fullOk = TryResolveWindowCore(gpuVa, size, out var full, out _, out _, warn: false, useMemo: false); if (ok != fullOk || (ok && resolved != full)) { throw GpuFatal.Fatal( @@ -1191,11 +1210,82 @@ private bool TryResolveWindow(ulong gpuVa, ulong size, out MetalGuestRange resol return ok; } - private bool TryResolveWindowCore(ulong gpuVa, ulong size, out MetalGuestRange resolved, out ulong alias, bool warn, bool useMemo) + // Caller holds _windowLock: the window is used by the submission being recorded. Its buffer exists, it counts as + // used now (idle cut-back), and it is pinned: no cut that would replace it moves before the next submission. + private void UseWindowLocked(MetalWindowPartition.Window window) + { + EnsureBuffer(window); + window.LastUsedSerial = _submissionSerial; + _pinnedWindows.Add(window.Id); + } + + // On the worker, after UseWindowLocked: the window is resident for this submission. + private void NoteTouched(MetalWindowPartition.Window window) + { + if (_touchedWindows.Add(window.Id)) + { + if (ResidentAppendEnabled && !_residentDirty && _residencySet == 0 && window.Buffer != 0) + { + // A first touch adds one buffer to a list that is otherwise current: put it on the end + // (ResidentVersion holds, ResidentBuffers grows) instead of rebuilding every window's + // entry, which a submission touching a few hundred windows did a few hundred times. + Append(ref _submissionResidentBuffers, ref _submissionResidentCount, window.Buffer); + } + else + { + _residentDirty = true; + } + } + } + + /// + /// What resolving a range in place did per submission, for a range a read-only binding memo answers from this + /// window (MetalReadBindingMemoV2): the window is pinned, counts as used and is touched (resident). Free when this + /// submission already pinned and touched it - a pinned window is never replaced before the next submission, so + /// its id is still its own - otherwise once under the window lock. False when the window has left the partition; + /// says the lock was taken. On the worker. + /// + internal bool UseWindowForHit(MetalWindowPartition.Window window, out bool touched) + { + touched = false; + if (_touchedWindows.Contains(window.Id) && _pinnedWindows.Contains(window.Id)) + { + return true; + } + + lock (_windowLock) + { + if (window.Retired) + { + return false; + } + + UseWindowLocked(window); + } + + NoteTouched(window); + touched = true; + return true; + } + + /// Whether the window is in the partition, pinned and touched by the submission being recorded. + internal bool WindowUsedThisSubmission(MetalWindowPartition.Window window) + { + lock (_windowLock) + { + return !window.Retired && _touchedWindows.Contains(window.Id) && _pinnedWindows.Contains(window.Id) && + ReferenceEquals(_partition.ById(window.Id), window); + } + } + + private bool TryResolveWindowCore( + ulong gpuVa, ulong size, out MetalGuestRange resolved, out ulong alias, out MetalWindowPartition.Window? used, bool warn, + bool useMemo) { using var phaseScope = SharpEmu.Libs.VideoOut.RenderPhaseProfile.MeasureDetail(SharpEmu.Libs.VideoOut.RenderPhaseProfile.Phase.GuestWindowResolve); resolved = default; alias = 0; + used = null; if (size == 0 || gpuVa == 0 || size > ulong.MaxValue - gpuVa) { return false; @@ -1217,7 +1307,7 @@ private bool TryResolveWindowCore(ulong gpuVa, ulong size, out MetalGuestRange r var offset = alias - _aliasBase; if (useMemo) { - if (TryResolveWindowFromMemo(offset, size, out resolved)) + if (TryResolveWindowFromMemo(offset, size, out resolved, out used)) { return true; } @@ -1270,30 +1360,15 @@ private bool TryResolveWindowCore(ulong gpuVa, ulong size, out MetalGuestRange r return false; } - EnsureBuffer(window); - window.LastUsedSerial = _submissionSerial; - _pinnedWindows.Add(window.Id); + UseWindowLocked(window); if (useMemo) { PublishWindowMemoLocked(window, offset, size); } } - if (_touchedWindows.Add(window.Id)) - { - if (ResidentAppendEnabled && !_residentDirty && _residencySet == 0 && window.Buffer != 0) - { - // A first touch adds one buffer to a list that is otherwise current: put it on the end - // (ResidentVersion holds, ResidentBuffers grows) instead of rebuilding every window's - // entry, which a submission touching a few hundred windows did a few hundred times. - Append(ref _submissionResidentBuffers, ref _submissionResidentCount, window.Buffer); - } - else - { - _residentDirty = true; - } - } - + NoteTouched(window); + used = window; var windowOffset = offset - window.Start; resolved = new MetalGuestRange(window.Buffer, windowOffset, size, window.GpuAddress + windowOffset); // Mappings are page-granular on both sides, so a page-aligned guest address has to diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalReadBindingMemoV2.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalReadBindingMemoV2.cs new file mode 100644 index 000000000..ba96b138d --- /dev/null +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalReadBindingMemoV2.cs @@ -0,0 +1,205 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +namespace SharpEmu.Gpu.Metal.V2; + +/// +/// The window range a read-only guest-range binding resolved to, kept per range with what makes it stand +/// (MetalRenderHost.ReadBindingMemo.cs, SHARPEMU_METAL_V2_READ_BINDING_MEMO_RANGES). Unlike +/// , whose entries answer only while nothing anywhere moved (the submission, the window +/// cuts, the image set, any image going GPU-modified), an entry here is checked against its own range: the window +/// object it was placed in is still in the partition with the same buffer, and the caller checks the rest per range. +/// The worker's alone: no locks. +/// +internal sealed class MetalReadBindingMemoV2 +{ + internal const int Ways = MetalReadBindingMemo.Ways; + + private const byte FlagValid = 1; + private const byte FlagCompute = 2; + + /// What the image flush over the range was answered by when the entry was stored. + internal enum ImageTier : byte + { + /// No image owns a page of the range: the flush returns at its page test. Checked live. + NoOwnerPages, + + /// Owner pages, but no image overlaps the bytes, at image-set version . + NoImage, + + /// One or two images overlap the bytes, none GPU-modified, at . + Held, + } + + internal struct Entry + { + public ulong Address; + public uint Size; + public byte Flags; + public ImageTier Tier; + public byte HeldImages; + public ulong Alias; + public MetalWindowPartition.Window? Window; + public nint Buffer; + public ulong Offset; + public ulong GpuAddress; + public long ImageSet; + } + + // Beside each entry: what is read only on some lookups. + internal struct Side + { + // The single-copy trap version the window was checked at. + public long Trap; + + // The submission the entry last answered in (hits_new_cb). + public ulong Serial; + + // The image cache's GPU-modified epoch the entry was stored at. + public long GpuModified; + + // Tier Held: the images over the range. + public MetalCachedImage? Image0; + public MetalCachedImage? Image1; + } + + private readonly int _setMask; + private readonly Entry[] _entries; + private readonly Side[] _sides; + + public MetalReadBindingMemoV2(int sets = 0) + { + sets = sets == 0 ? MetalReadBindingMemo.DefaultSets : sets; + _setMask = sets - 1; + _entries = new Entry[sets * Ways]; + _sides = new Side[sets * Ways]; + } + + public long Hits, Misses, Stores, Verified, Evictions; + + // One per miss, the first check that failed (they add up to Misses). + public long MissEmpty, MissOtherKey, MissAlias, MissWindowRetired, MissWindowBuffer, MissTrap; + public long MissImagePages, MissImageSet, MissImageGpuModified; + public long RefusedTrace, RefusedUnmapped, RefusedWindow, RefusedFill, RefusedLabel, RefusedStaged; + + // What hits did: re-checked a moved trap or image-set version for the range, took the window lock to pin and + // touch the window in this submission, answered in another submission than the last, answered while fills, + // label copies or staged copies were pending (all of which the v1 memo refused). + public long RevalidatedTrap, RevalidatedImageSet, WindowTouches, HitsNewCommandBuffer, HitsWithPending; + + // Chains whose answer was not kept: an image flushed, not a window, the window left the partition while the + // chain ran, a range of 4 GiB or more, more than two images over the range. + public long StoreSkipFlushed, StoreSkipNotInPlace, StoreSkipRetiredAfter, StoreSkipLarge, StoreSkipImageMany; + + private static byte FlagsOf(bool compute) => (byte)(FlagValid | (compute ? FlagCompute : 0)); + + /// The entry at an index or returned. + public ref Entry At(int index) => ref _entries[index]; + + public ref Side SideAt(int index) => ref _sides[index]; + + /// + /// The index of the range's entry, moved to the front of its set; -1 when the set holds none (the miss is + /// counted as empty or other_key). + /// + public int Find(ulong address, ulong size, bool compute) + { + var first = MetalReadBindingMemo.SetIndex(address, size, compute, _setMask) * Ways; + var flags = FlagsOf(compute); + var any = false; + for (var way = 0; way < Ways; way++) + { + ref var entry = ref _entries[first + way]; + if (entry.Flags == flags && entry.Address == address && entry.Size == size) + { + if (way != 0) + { + MoveToFront(first, way); + } + + return first; + } + + any |= entry.Flags != 0; + } + + Misses++; + if (any) + { + MissOtherKey++; + } + else + { + MissEmpty++; + } + + return -1; + } + + /// + /// The index of a front entry for the range, cleared but for its key: the range's entry if it had one, otherwise + /// a new one, the set's least recently used entry evicted. + /// + public int Insert(ulong address, uint size, bool compute) + { + var first = MetalReadBindingMemo.SetIndex(address, size, compute, _setMask) * Ways; + var flags = FlagsOf(compute); + var found = -1; + for (var way = 0; way < Ways && found < 0; way++) + { + ref var entry = ref _entries[first + way]; + if (entry.Flags == flags && entry.Address == address && entry.Size == size) + { + found = way; + } + } + + if (found < 0) + { + Evictions += _entries[first + Ways - 1].Flags != 0 ? 1 : 0; + found = Ways - 1; + } + + if (found != 0) + { + MoveToFront(first, found); + } + + _entries[first] = new Entry { Address = address, Size = size, Flags = flags }; + _sides[first] = default; + Stores++; + return first; + } + + private void MoveToFront(int first, int way) + { + var entry = _entries[first + way]; + var side = _sides[first + way]; + _entries.AsSpan(first, way).CopyTo(_entries.AsSpan(first + 1, way)); + _sides.AsSpan(first, way).CopyTo(_sides.AsSpan(first + 1, way)); + _entries[first] = entry; + _sides[first] = side; + } + + /// The counters since the last call (the PERF line's read_binding_memo); resets them. + public string TakeCounters() + { + var text = $"ranges=1 hits={Hits} misses={Misses} stores={Stores} verified={Verified} evictions={Evictions} " + + $"miss_by=(empty={MissEmpty},other_key={MissOtherKey},alias={MissAlias},window_retired={MissWindowRetired}," + + $"window_buffer={MissWindowBuffer},trap={MissTrap},image_pages={MissImagePages},image_set={MissImageSet}," + + $"image_gpu_modified={MissImageGpuModified}) " + + $"refused_by=(trace={RefusedTrace},unmapped={RefusedUnmapped},window={RefusedWindow},fill={RefusedFill}," + + $"label={RefusedLabel},staged={RefusedStaged}) " + + $"revalidated=(trap={RevalidatedTrap},image_set={RevalidatedImageSet}) window_touches={WindowTouches} " + + $"hits_new_cb={HitsNewCommandBuffer} hits_with_pending={HitsWithPending} " + + $"store_skip=(flushed={StoreSkipFlushed},image_many={StoreSkipImageMany},not_in_place={StoreSkipNotInPlace}," + + $"retired_after={StoreSkipRetiredAfter},large={StoreSkipLarge})"; + Hits = Misses = Stores = Verified = Evictions = 0; + MissEmpty = MissOtherKey = MissAlias = MissWindowRetired = MissWindowBuffer = MissTrap = 0; + MissImagePages = MissImageSet = MissImageGpuModified = 0; + RefusedTrace = RefusedUnmapped = RefusedWindow = RefusedFill = RefusedLabel = RefusedStaged = 0; + RevalidatedTrap = RevalidatedImageSet = WindowTouches = HitsNewCommandBuffer = HitsWithPending = 0; + StoreSkipFlushed = StoreSkipNotInPlace = StoreSkipRetiredAfter = StoreSkipLarge = StoreSkipImageMany = 0; + return text; + } +} diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Descriptors.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Descriptors.cs index a6c5bd935..318480642 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Descriptors.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Descriptors.cs @@ -1074,10 +1074,10 @@ public void BindResources(IPreparedBindings prepared) var size = mappedWhole ? requested : ClampMappedSize(descriptor.Address, requested); var memoStamp = !written && mappedWhole && ReadBindingMemoEnabled ? ReadBindingStamp() : default; var flushFoundImage = _imageCache.FlushGpuWrites(descriptor.Address, size, MetalWritebackCause.StorageDescriptor, written); - var range = ResolveStorageBuffer(descriptor.Address, size, written, computeStage, out var inPlaceAlias); + var range = ResolveStorageBuffer(descriptor.Address, size, written, computeStage, out var inPlaceAlias, out var inPlaceWindow); if (!written && mappedWhole && ReadBindingMemoEnabled) { - StoreReadBinding(descriptor.Address, size, computeStage, memoStamp, flushFoundImage, inPlaceAlias, range); + StoreReadBinding(descriptor.Address, size, computeStage, memoStamp, flushFoundImage, inPlaceAlias, inPlaceWindow, range); } // The text is built only when the trace is on: this runs per storage buffer per draw. diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.ReadBindingMemo.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.ReadBindingMemo.cs index d29bd84ac..b87cc84e9 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.ReadBindingMemo.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.ReadBindingMemo.cs @@ -45,10 +45,25 @@ internal sealed partial class MetalRenderHost internal bool ReadBindingMemoVerify { get; set; } = ReadBindingMemoSetting == "verify" || Environment.GetEnvironmentVariable("SHARPEMU_PERF_VERIFY") == "1"; + /// + /// Entries checked per range (MetalReadBindingMemoV2), the default; SHARPEMU_METAL_V2_READ_BINDING_MEMO_RANGES=0 + /// keeps the stamp of everything (MetalReadBindingMemo), as before. + /// + internal bool ReadBindingMemoRanges { get; set; } = + Environment.GetEnvironmentVariable("SHARPEMU_METAL_V2_READ_BINDING_MEMO_RANGES") != "0"; + private readonly MetalReadBindingMemo _readBindingMemo = new(); + private readonly MetalReadBindingMemoV2 _readBindingMemoV2 = new(); + + /// The v2 memo and its counters (tests). + internal MetalReadBindingMemoV2 ReadBindingMemoV2 => _readBindingMemoV2; + + // The entry the last v2 hit answered from (the verify mode reads its claims). + private int _readBindingHitIndex = -1; internal (long Hits, long Misses, long Stores, long Verified) ReadBindingMemoCounts => - (_readBindingMemo.Hits, _readBindingMemo.Misses, _readBindingMemo.Stores, _readBindingMemo.Verified); + (_readBindingMemo.Hits + _readBindingMemoV2.Hits, _readBindingMemo.Misses + _readBindingMemoV2.Misses, + _readBindingMemo.Stores + _readBindingMemoV2.Stores, _readBindingMemo.Verified + _readBindingMemoV2.Verified); // Nothing that reports bindings is on. private bool ReadBindingTracesOff => @@ -112,6 +127,11 @@ private bool TryReadBindingMemo(ulong address, ulong size, bool computeStage, ou return false; } + if (ReadBindingMemoRanges) + { + return TryReadBindingMemoRanges(address, size, computeStage, out range); + } + _readBindingRefusedPending = false; if (!ReadBindingMemoApplies) { @@ -148,8 +168,18 @@ private bool TryReadBindingMemo(ulong address, ulong size, bool computeStage, ou // resolved in place, and nothing the stamp holds moved while the chain ran. private void StoreReadBinding( ulong address, ulong size, bool computeStage, in MetalReadBindingMemo.Stamp before, bool flushFoundImage, - ulong inPlaceAlias, in MetalGuestRange range) + ulong inPlaceAlias, MetalWindowPartition.Window? inPlaceWindow, in MetalGuestRange range) { + if (ReadBindingMemoRanges) + { + if (ReadBindingMemoEnabled) + { + StoreReadBindingRanges(address, size, computeStage, in before, flushFoundImage, inPlaceAlias, inPlaceWindow, in range); + } + + return; + } + if (flushFoundImage || inPlaceAlias == 0 || !range.IsValid || !ReadBindingMemoEnabled || !ReadBindingTracesOff || ReadBindingStamp() != before || !_guestMemory.InPlaceAnswerStands(inPlaceAlias, size)) { @@ -165,11 +195,19 @@ private void StoreReadBinding( _readBindingMemo.Store(address, size, computeStage, inPlaceAlias, before, range); } - // =verify: the full chain behind a hit, which must give the same range and find no image to flush. + // =verify: the full chain behind a hit, which must give the same range and find no image to flush; behind a v2 + // hit (MetalRenderHost.ReadBindingMemoRanges.cs) also do nothing, and find the window the hit pinned and touched. private void VerifyReadBinding(ulong address, ulong size, bool computeStage, MetalWritebackCause cause, in MetalGuestRange memo) { + var ranges = ReadBindingMemoRanges; + var before = ranges ? ReadBindingChainSnapshot.Take(this, address, size) : default; + if (ranges) + { + VerifyReadBindingHitClaims(address, size, computeStage, in memo); + } + var flushed = _imageCache.FlushGpuWrites(address, size, cause, written: false); - var full = ResolveStorageBuffer(address, size, written: false, computeStage, out var alias); + var full = ResolveStorageBuffer(address, size, written: false, computeStage, out var alias, out _); if (flushed || alias == 0 || full != memo) { throw Fatal( @@ -177,6 +215,20 @@ private void VerifyReadBinding(ulong address, ulong size, bool computeStage, Met $"compute={computeStage} memo={memo} full={full} in_place={alias != 0} flushed_image={flushed}."); } + if (ranges) + { + var after = ReadBindingChainSnapshot.Take(this, address, size); + if (before.StoresOver || after != before) + { + throw Fatal( + $"The full path behind a memoised read-only binding did something the hit skipped: address=0x{address:X16} " + + $"size=0x{size:X} compute={computeStage} before={before} after={after}."); + } + + _readBindingMemoV2.Verified++; + return; + } + _readBindingMemo.Verified++; } @@ -252,7 +304,8 @@ private void NoteSnapshotRef(int kind, int array, object reference) private string TakeReadBindingCounters() { - var text = $"read_binding_memo=({_readBindingMemo.TakeCounters()}) bind_shape=(binds={_bindCalls} " + + var memo = ReadBindingMemoRanges ? _readBindingMemoV2.TakeCounters() : _readBindingMemo.TakeCounters(); + var text = $"read_binding_memo=({memo}) bind_shape=(binds={_bindCalls} " + $"image_set_moves={_bindImageSetMoves} binding_epoch_moves={_bindBindingEpochMoves} " + $"snapshot_repeats=[images={_snapshotRefRepeats[0]},samplers={_snapshotRefRepeats[1]},buffers={_snapshotRefRepeats[2]}]/{_snapshotRefChecks} " + $"buffers_read_only={_readOnlyBufferBinds} buffers_written={_writtenBufferBinds} storage_images={_storageImageBinds} tiny_pass_dummies={_tinyPassDummies}) {TakeStagePlanCounters()}"; diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.ReadBindingMemoRanges.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.ReadBindingMemoRanges.cs new file mode 100644 index 000000000..519664cf5 --- /dev/null +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.ReadBindingMemoRanges.cs @@ -0,0 +1,211 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +namespace SharpEmu.Gpu.Metal.V2; + +/// +/// The read-only binding memo checked per range (MetalReadBindingMemoV2, SHARPEMU_METAL_V2_READ_BINDING_MEMO_RANGES, +/// on by default). The v1 memo's stamp made every entry miss whenever anything anywhere moved: the next command buffer, +/// a window cut elsewhere, any image added, dropped or GPU-written. Demon's Souls moves one of those between nearly +/// every two bindings of a range, so most lookups paid the full chain. Here each condition is checked for the range: +/// +/// The command buffer: what resolving a range in place did per command buffer (pin the window, mark it used, make +/// it resident) the hit does too (MetalGuestMemory.UseWindowForHit), once per window per command buffer. +/// The window cuts: the window object the range was placed in is still in the partition (a cut move, a cut back +/// to granules and a renewal all retire the windows they replace) and still has the buffer the entry holds; a window's +/// bounds never change, so the range still fits it. +/// +/// The single-copy trap version and the image stamps are still read whole, as in v1, and so is the v1 refusal while any +/// fill, label copy or staged copy is pending. +/// +internal sealed partial class MetalRenderHost +{ + private bool MissReadBinding(ref long cause) + { + _readBindingMemoV2.Misses++; + cause++; + return false; + } + + private bool TryReadBindingMemoRanges(ulong address, ulong size, bool computeStage, out MetalGuestRange range) + { + var memo = _readBindingMemoV2; + range = default; + if (!ReadBindingTracesOff) + { + return MissReadBinding(ref memo.RefusedTrace); + } + + if (_deferredFills.Count != 0) + { + return MissReadBinding(ref memo.RefusedFill); + } + + if (_deferredLabelCopies.Count != 0) + { + return MissReadBinding(ref memo.RefusedLabel); + } + + if (_stagedStorageCopies is { Count: > 0 }) + { + return MissReadBinding(ref memo.RefusedStaged); + } + + if (!_backing.TryResolveBackingAliasSpan(address, size, out var alias)) + { + return MissReadBinding(ref memo.RefusedUnmapped); + } + + var index = memo.Find(address, size, computeStage); + if (index < 0) + { + return false; + } + + ref var entry = ref memo.At(index); + if (entry.Alias != alias) + { + return MissReadBinding(ref memo.MissAlias); + } + + var window = entry.Window!; + if (Volatile.Read(ref window.Retired)) + { + return MissReadBinding(ref memo.MissWindowRetired); + } + + if (window.Buffer != entry.Buffer) + { + return MissReadBinding(ref memo.MissWindowBuffer); + } + + if (!_guestMemory.InPlaceAnswerStands(alias, size)) + { + return MissReadBinding(ref memo.RefusedWindow); + } + + ref var side = ref memo.SideAt(index); + if (side.Trap != _guestMemory.TrapVersionNow) + { + return MissReadBinding(ref memo.MissTrap); + } + + if (entry.ImageSet != _imageCache.ImageSetVersion) + { + return MissReadBinding(ref memo.MissImageSet); + } + + if (side.GpuModified != _imageCache.Epochs.GpuModified) + { + return MissReadBinding(ref memo.MissImageGpuModified); + } + + if (!_guestMemory.UseWindowForHit(window, out var touched)) + { + return MissReadBinding(ref memo.MissWindowRetired); + } + + memo.WindowTouches += touched ? 1 : 0; + MetalGpuReferenceCensus.Mark(address, size); + memo.Hits++; + if (side.Serial != _submissionSerial) + { + memo.HitsNewCommandBuffer++; + side.Serial = _submissionSerial; + } + + _readBindingHitIndex = index; + range = new MetalGuestRange(entry.Buffer, entry.Offset, size, entry.GpuAddress); + return true; + } + + // After the full chain of a read-only binding: kept when the flush found no image over the range and the range + // resolved in place to a window that is still in the partition. The stamps are those read before the chain, so + // anything that moved while it ran makes the entry miss. + private void StoreReadBindingRanges( + ulong address, ulong size, bool computeStage, in MetalReadBindingMemo.Stamp before, bool flushFoundImage, + ulong inPlaceAlias, MetalWindowPartition.Window? window, in MetalGuestRange range) + { + var memo = _readBindingMemoV2; + if (!ReadBindingTracesOff) + { + return; + } + + if (flushFoundImage) + { + memo.StoreSkipFlushed++; + return; + } + + if (inPlaceAlias == 0 || window is null || !range.IsValid || range.Buffer != window.Buffer || range.Size != size) + { + memo.StoreSkipNotInPlace++; + return; + } + + if (size > uint.MaxValue) + { + memo.StoreSkipLarge++; + return; + } + + if (Volatile.Read(ref window.Retired) || !_guestMemory.InPlaceAnswerStands(inPlaceAlias, size)) + { + memo.StoreSkipRetiredAfter++; + return; + } + + var index = memo.Insert(address, (uint)size, computeStage); + ref var entry = ref memo.At(index); + entry.Alias = inPlaceAlias; + entry.Window = window; + entry.Buffer = range.Buffer; + entry.Offset = range.Offset; + entry.GpuAddress = range.GpuAddress; + entry.ImageSet = before.ImageSet; + ref var side = ref memo.SideAt(index); + side.Trap = before.Trap; + side.GpuModified = before.GpuModified; + side.Serial = _submissionSerial; + } + + // =verify, before the full chain runs behind a v2 hit: the hit pinned and touched its window (the chain would + // do it too, so this is checked first). + private void VerifyReadBindingHitClaims(ulong address, ulong size, bool computeStage, in MetalGuestRange memo) + { + var index = _readBindingHitIndex; + var entry = index >= 0 ? _readBindingMemoV2.At(index) : default; + if (entry.Window is not { } window || entry.Address != address || entry.Size != size) + { + throw Fatal( + $"A memoised read-only binding has no entry behind it: address=0x{address:X16} size=0x{size:X} compute={computeStage}."); + } + + if (!_guestMemory.WindowUsedThisSubmission(window)) + { + throw Fatal( + $"A memoised read-only binding did not pin and touch its window for this command buffer: address=0x{address:X16} " + + $"size=0x{size:X} window={window.Id} retired={window.Retired} memo={memo}."); + } + } + + /// What the chain behind a read-only binding can do, read on both sides of it in the verify mode. + private readonly record struct ReadBindingChainSnapshot( + int LabelCopies, bool LandLabels, int Fills, long FillsLandedEarly, nint RenderEncoder, nint ComputeEncoder, + long PassEndsOther, bool StoresOver, long WindowMoves, long WindowRenewals, long ImageWritebacks) + { + public static ReadBindingChainSnapshot Take(MetalRenderHost host, ulong address, ulong size) => new( + host._deferredLabelCopies.Count, + host._landDeferredLabels, + host._deferredFills.Count, + host._deferredFillsLandedEarly, + host._renderEncoder, + host._computeEncoder, + host._passEndOther, + host._stagedStorageCopies is { Count: > 0 } staged && staged.HasRecordedStoresOver(address, size), + host._guestMemory.WindowLayoutCounts.Moves, + host._guestMemory.SingleCopyWindowCounts.Renewals, + host._imageCache.Counters.Writebacks); + } +} diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.StagedStorage.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.StagedStorage.cs index 4e7fbb77e..ccb341141 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.StagedStorage.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.StagedStorage.cs @@ -29,13 +29,16 @@ internal void StageRecordedStoresForTest(ulong address, ulong size) /// reach guest memory (). /// internal MetalGuestRange ResolveStorageBuffer(ulong address, ulong size, bool written, bool computeStage = false) => - ResolveStorageBuffer(address, size, written, computeStage, out _); + ResolveStorageBuffer(address, size, written, computeStage, out _, out _); // inPlaceAlias: the backing alias MetalGuestMemory.TryResolveInPlace placed the range by when the range is its - // window, else 0 (MetalReadBindingMemo). - private MetalGuestRange ResolveStorageBuffer(ulong address, ulong size, bool written, bool computeStage, out ulong inPlaceAlias) + // window, else 0; inPlaceWindow: that window, else null (MetalReadBindingMemo, MetalReadBindingMemoV2). + private MetalGuestRange ResolveStorageBuffer( + ulong address, ulong size, bool written, bool computeStage, out ulong inPlaceAlias, + out MetalWindowPartition.Window? inPlaceWindow) { inPlaceAlias = 0; + inPlaceWindow = null; using var phaseScope = SharpEmu.Libs.VideoOut.RenderPhaseProfile.MeasureDetail(SharpEmu.Libs.VideoOut.RenderPhaseProfile.Phase.StorageDeferredLabels); OrderAfterDeferredCopies(address, size, written ? LabelLandCause.BindWritten : LabelLandCause.BindRead); phaseScope.SwitchPhase(SharpEmu.Libs.VideoOut.RenderPhaseProfile.Phase.StorageSharedLookup); @@ -48,9 +51,10 @@ private MetalGuestRange ResolveStorageBuffer(ulong address, ulong size, bool wri phaseScope.SwitchPhase(SharpEmu.Libs.VideoOut.RenderPhaseProfile.Phase.StorageStoreOrder); OrderAfterStagedStores(address, size); phaseScope.SwitchPhase(SharpEmu.Libs.VideoOut.RenderPhaseProfile.Phase.StorageBufferResolve); - if (_guestMemory.TryResolveInPlace(address, size, out var window, out var alias)) + if (_guestMemory.TryResolveInPlace(address, size, out var window, out var alias, out var placedIn)) { inPlaceAlias = alias; + inPlaceWindow = placedIn; return window; } diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.cs index 7dfbcfd02..11a7ea866 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.cs @@ -2581,9 +2581,10 @@ public BufferBinding ObtainBuffer(ulong address, ulong size, bool isWritten) // holds the GPU's writes still in flight in this command buffer - whole, however // large, up to the largest window. var inPlaceAlias = 0UL; + MetalWindowPartition.Window? inPlaceWindow = null; var range = isWritten ? _guestMemory.Resolve(address, size, whole: true) - : ResolveStorageBuffer(address, size, written: false, computeStage: false, out inPlaceAlias); + : ResolveStorageBuffer(address, size, written: false, computeStage: false, out inPlaceAlias, out inPlaceWindow); if (!range.IsValid) { @@ -2592,7 +2593,7 @@ public BufferBinding ObtainBuffer(ulong address, ulong size, bool isWritten) if (!isWritten && ReadBindingMemoEnabled) { - StoreReadBinding(address, size, computeStage: false, memoStamp, flushFoundImage, inPlaceAlias, range); + StoreReadBinding(address, size, computeStage: false, memoStamp, flushFoundImage, inPlaceAlias, inPlaceWindow, range); } TraceRingBinding(address, size, isWritten, range); diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalWindowPartition.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalWindowPartition.cs index 54aeab714..f4693f179 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalWindowPartition.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalWindowPartition.cs @@ -69,6 +69,11 @@ public Window(int id, ulong start, ulong end) public nint Buffer; public ulong GpuAddress; + + // Set once the window leaves the partition (Replace: a move, a cut back to granules, a renewal); it never + // comes back. Written under the owner's window lock, read without it by the read-binding memo on the worker, + // where every placement runs. + public bool Retired; } internal enum Placement @@ -336,6 +341,7 @@ private void Replace(int first, int last, List retired) for (var index = first; index <= last; index++) { var old = _windows[index]; + Volatile.Write(ref old.Retired, true); retired.Add(old); _byId[old.Id] = null; _freeIds.Push(old.Id); diff --git a/tests/SharpEmu.Gpu.Metal.Tests/MetalClearFoldingTests.ReadBindingMemo.cs b/tests/SharpEmu.Gpu.Metal.Tests/MetalClearFoldingTests.ReadBindingMemo.cs index 923f03fed..e6cf07548 100644 --- a/tests/SharpEmu.Gpu.Metal.Tests/MetalClearFoldingTests.ReadBindingMemo.cs +++ b/tests/SharpEmu.Gpu.Metal.Tests/MetalClearFoldingTests.ReadBindingMemo.cs @@ -77,6 +77,10 @@ public void AReadOnlyBindingMissesOnceItsRangeIsRemapped() var host = rig.Host; var before = BindTwiceAndHit(host); + // W4: a remap elsewhere leaves it. + rig.Remap = (MemoBuffer + 0x10000, MemoBuffer + 0x11000, 0x1000); + AssertHits(host, () => BindRead(host), before); + rig.Remap = (MemoBuffer, MemoBuffer + 0x1000, 0x1000); AssertMisses(host, () => BindRead(host), before with { Offset = before.Offset + 0x1000 }); } @@ -138,12 +142,14 @@ public void AReadOnlyBindingMissesWhileADeferredLabelCopyIsHeld() host.FlushAndWaitForGpu(); } + // R1: the v1 memo (SHARPEMU_METAL_V2_READ_BINDING_MEMO_RANGES=0) stamps the submission: a new command buffer misses. [Fact] - public void AReadOnlyBindingMissesInANewCommandBuffer() + public void AV1ReadOnlyBindingMissesInANewCommandBuffer() { if (!RequireDevice()) return; using var rig = MemoRig(); var host = rig.Host; + host.ReadBindingMemoRanges = false; Assert.NotEqual(0, host.EnsureComputeEncoder()); var before = BindTwiceAndHit(host); var serial = host.SubmissionSerial; @@ -155,14 +161,136 @@ public void AReadOnlyBindingMissesInANewCommandBuffer() host.FlushAndWaitForGpu(); } + // Binds the range, which must miss for the reason the counter counts. + private static BufferBinding AssertMissesBy(MetalRenderHost host, Func cause, Func bind) + { + var memo = host.ReadBindingMemoV2; + var (hits, misses, _, _) = host.ReadBindingMemoCounts; + var counted = cause(memo); + var binding = bind(); + Assert.Equal(hits, host.ReadBindingMemoCounts.Hits); + Assert.Equal(misses + 1, host.ReadBindingMemoCounts.Misses); + Assert.Equal(counted + 1, cause(memo)); + return binding; + } + + private static BufferBinding AssertHits(MetalRenderHost host, Func bind, BufferBinding expected) + { + var hits = host.ReadBindingMemoCounts.Hits; + var binding = bind(); + Assert.Equal(hits + 1, host.ReadBindingMemoCounts.Hits); + Assert.Equal(expected, binding); + return binding; + } + + private static void NewCommandBuffer(MetalRenderHost host) + { + var serial = host.SubmissionSerial; + host.FlushAndWaitForGpu(); + Assert.NotEqual(0, host.EnsureComputeEncoder()); + Assert.NotEqual(serial, host.SubmissionSerial); + } + + // 1 MiB windows: MemoBuffer is the start of the second; a range across its end crosses into the third. + private const ulong SecondWindowEnd = GuestBase + 0x200000; + private const ulong ThirdWindowEnd = GuestBase + 0x300000; + + // W1: a new command buffer keeps the entry; the hit pins and touches its window for that command buffer (the + // verify mode checks both on every hit), so a range crossing its edge cannot move the cut under it. + [Fact] + public void AReadOnlyBindingHitsInANewCommandBufferAndPinsItsWindowThere() + { + if (!RequireDevice()) return; + using var rig = new Rig(Device.Value, granuleMegabytes: 1); + rig.Host.ReadBindingMemoEnabled = true; + rig.Host.ReadBindingMemoVerify = true; + var host = rig.Host; + Assert.NotEqual(0, host.EnsureComputeEncoder()); + var before = BindTwiceAndHit(host); + + NewCommandBuffer(host); + Assert.Equal(0, host.GuestMemory.TouchedWindows.Count); + var newCommandBuffer = host.ReadBindingMemoV2.HitsNewCommandBuffer; + AssertHits(host, () => BindRead(host), before); + Assert.Equal(newCommandBuffer + 1, host.ReadBindingMemoV2.HitsNewCommandBuffer); + Assert.Equal(1, host.GuestMemory.TouchedWindows.Count); + + var (moves, conflicts, _) = host.GuestMemory.WindowLayoutCounts; + BindRead(host, SecondWindowEnd - 0x100, 0x200); + Assert.Equal((moves, conflicts + 1), (host.GuestMemory.WindowLayoutCounts.Moves, host.GuestMemory.WindowLayoutCounts.Conflicts)); + AssertHits(host, () => BindRead(host), before); + host.FlushAndWaitForGpu(); + } + + // W2: a range across the window's edge, bound in a command buffer that has not used the window, moves the cut and + // retires the window: the entry misses. A cut moved between two other windows leaves it. + [Fact] + public void AReadOnlyBindingMissesOnceItsWindowIsRecutAndHitsWhenAnotherIs() + { + if (!RequireDevice()) return; + using var rig = new Rig(Device.Value, granuleMegabytes: 1); + rig.Host.ReadBindingMemoEnabled = true; + rig.Host.ReadBindingMemoVerify = true; + var host = rig.Host; + Assert.NotEqual(0, host.EnsureComputeEncoder()); + var before = BindTwiceAndHit(host); + + NewCommandBuffer(host); + var partition = host.GuestMemory.PartitionVersion; + var moves = host.GuestMemory.WindowLayoutCounts.Moves; + BindRead(host, ThirdWindowEnd - 0x100, 0x200); + Assert.Equal(moves + 1, host.GuestMemory.WindowLayoutCounts.Moves); + Assert.NotEqual(partition, host.GuestMemory.PartitionVersion); + AssertHits(host, () => BindRead(host), before); + + NewCommandBuffer(host); + BindRead(host, SecondWindowEnd - 0x100, 0x200); + Assert.Equal(moves + 2, host.GuestMemory.WindowLayoutCounts.Moves); + var after = AssertMissesBy(host, static memo => memo.MissWindowRetired, () => BindRead(host)); + Assert.NotEqual(before.Handle, after.Handle); + AssertHits(host, () => BindRead(host), after); + host.FlushAndWaitForGpu(); + } + + // W3: a window idle for MetalGuestMemory.IdleWindowSerials submissions is cut back to granules: retired, so the + // entry misses. + [Fact] + public void AReadOnlyBindingMissesOnceItsIdleWindowIsCutBack() + { + if (!RequireDevice()) return; + using var rig = new Rig(Device.Value, granuleMegabytes: 1); + rig.Host.ReadBindingMemoEnabled = true; + rig.Host.ReadBindingMemoVerify = true; + var host = rig.Host; + Assert.NotEqual(0, host.EnsureComputeEncoder()); + // Off the granule cut, so the cut back has something to do. + BindRead(host, SecondWindowEnd - 0x100, 0x200); + var before = BindTwiceAndHit(host); + var partition = host.GuestMemory.PartitionVersion; + + for (var submission = 0; submission < (int)MetalGuestMemory.IdleWindowSerials + 160; submission++) + { + host.FlushAndWaitForGpu(); + Assert.NotEqual(0, host.EnsureComputeEncoder()); + } + + Assert.NotEqual(partition, host.GuestMemory.PartitionVersion); + var after = AssertMissesBy(host, static memo => memo.MissWindowRetired, () => BindRead(host)); + AssertHits(host, () => BindRead(host), after); + host.FlushAndWaitForGpu(); + } + // C1: a frame's worth of distinct read-only ranges (Demon's Souls binds some 20k a frame) is held whole: binding // them all a second time hits nearly every one. - [Fact] - public void TwentyThousandDistinctReadOnlyRangesBoundTwiceHitOnTheSecondPass() + [Theory] + [InlineData(true)] + [InlineData(false)] + public void TwentyThousandDistinctReadOnlyRangesBoundTwiceHitOnTheSecondPass(bool perRange) { if (!RequireDevice()) return; using var rig = MemoRig(); var host = rig.Host; + host.ReadBindingMemoRanges = perRange; // Verifying each hit runs the whole chain again; this test is about capacity, the others about soundness. host.ReadBindingMemoVerify = false; const int ranges = 20000; diff --git a/tests/SharpEmu.Gpu.Metal.Tests/MetalClearFoldingTests.cs b/tests/SharpEmu.Gpu.Metal.Tests/MetalClearFoldingTests.cs index a34209566..bdaeca514 100644 --- a/tests/SharpEmu.Gpu.Metal.Tests/MetalClearFoldingTests.cs +++ b/tests/SharpEmu.Gpu.Metal.Tests/MetalClearFoldingTests.cs @@ -241,11 +241,27 @@ private sealed class Rig : IDisposable private readonly PageGuard _pages; private readonly Backing _backing = new(); - public Rig(nint device) + // granuleMegabytes: windows of that many MiB (SHARPEMU_METAL_V2_GRANULE_MB) instead of one over the whole + // backing, so a range can cross a window edge; tests in this assembly do not run in parallel. + public Rig(nint device, int granuleMegabytes = 0) { _queue = MetalNative.Send(device, MetalNative.Selector("newCommandQueue")); _pages = new PageGuard(_space); - Host = new MetalRenderHost(device, _queue, _backing, _backing, _pages, new MetalGpuWorkerRelay(static () => { })); + const string granule = "SHARPEMU_METAL_V2_GRANULE_MB"; + var configured = Environment.GetEnvironmentVariable(granule); + if (granuleMegabytes != 0) + { + Environment.SetEnvironmentVariable(granule, granuleMegabytes.ToString()); + } + + try + { + Host = new MetalRenderHost(device, _queue, _backing, _backing, _pages, new MetalGpuWorkerRelay(static () => { })); + } + finally + { + Environment.SetEnvironmentVariable(granule, configured); + } } public MetalRenderHost Host { get; } diff --git a/tests/SharpEmu.Gpu.Metal.Tests/Scenes/BindingReuseSceneTests.cs b/tests/SharpEmu.Gpu.Metal.Tests/Scenes/BindingReuseSceneTests.cs index 04dfb325c..108a4feb0 100644 --- a/tests/SharpEmu.Gpu.Metal.Tests/Scenes/BindingReuseSceneTests.cs +++ b/tests/SharpEmu.Gpu.Metal.Tests/Scenes/BindingReuseSceneTests.cs @@ -169,19 +169,22 @@ float[] Pixel(int x) output.WriteLine($"graphics binding reuse={reuse} attempted={rig.Host.GraphicsBindingAttempts} skipped={rig.Host.GraphicsBindingSkipped}"); } - // Draws of one mesh read its vertex buffer through the same read-only storage binding: within a command buffer - // the binding after the first is answered from it (MetalReadBindingMemo), a new command buffer looks it up in - // full first, and every draw renders the texture it binds either way. + // Draws of one mesh read its vertex buffer through the same read-only storage binding: the binding after the + // first is answered from it (MetalReadBindingMemoV2), in the next command buffer too; the v1 memo + // (ranges: false, MetalReadBindingMemo) looks it up in full first in a new command buffer. Every draw renders the + // texture it binds either way. [Theory] - [InlineData(true)] - [InlineData(false)] - public void DrawsOfOneMeshReuseTheirReadOnlyVertexBindingAndRenderAsWithout(bool memo) + [InlineData(true, true)] + [InlineData(true, false)] + [InlineData(false, true)] + public void DrawsOfOneMeshReuseTheirReadOnlyVertexBindingAndRenderAsWithout(bool memo, bool ranges) { using var rig = CreateRig(); if (rig is null) return; var host = rig.Host; host.ReadBindingMemoEnabled = memo; host.ReadBindingMemoVerify = memo; + host.ReadBindingMemoRanges = ranges; const uint red = 0xFF0000FF; const uint green = 0xFF00FF00; const uint width = 16; @@ -235,12 +238,20 @@ float[] Pixel(int x) rig.Submit(again); AssertColour("next command buffer", Pixel(6), red); var afterSecond = host.ReadBindingMemoCounts; - output.WriteLine($"memo={memo}: first {afterFirst}, second {afterSecond}"); + output.WriteLine($"memo={memo} ranges={ranges}: first {afterFirst}, second {afterSecond}"); if (memo) { Assert.True(afterFirst.Hits > hits, "no draw's vertex binding was answered from the one before"); Assert.Equal(afterFirst.Hits - hits, afterFirst.Verified); - Assert.True(afterSecond.Misses > afterFirst.Misses, "the new command buffer's first binding did not miss"); + if (ranges) + { + Assert.True(afterSecond.Hits > afterFirst.Hits, "the new command buffer's binding was not answered from the one before"); + Assert.Equal(afterSecond.Hits - hits, afterSecond.Verified); + } + else + { + Assert.True(afterSecond.Misses > afterFirst.Misses, "the new command buffer's first binding did not miss"); + } } else { From 4bb35ece71fea0f3d9bc755b2782aa953770c144 Mon Sep 17 00:00:00 2001 From: kuba Date: Sun, 15 Nov 2026 09:34:53 +0000 Subject: [PATCH 047/178] [Metal] Read-binding memo v2: pending fills, label copies and staged copies refuse only the ranges they concern v1 refused every read-only memo lookup while any deferred fill, held label copy or listed staged copy existed; with label copies held to the commit that was most of every command buffer. A v2 hit now misses only when the chain would act for this range: a waiting fill over it (DeferredFillsOver: a span kept by Add/landing, then the walk), a label copy over it under the same gate as OrderAfterDeferredCopies (which it also mirrors by forgetting _labelTouchClass), or a staged copy that TryShare would answer with or whose recorded stores OrderAfterStagedStores would write back (MetalStagedStorage.MayConcern, behind a span kept by Add/Bind and measured again by Forget/EndSubmission). hits_with_pending counts the hits v1 would have refused. Tests: P1 (label copy over the range misses and lands; elsewhere hits and stays held; P6 the hit forgets the touched label class), P2 (copies held to the render encoder end with no compute encoder: hits), P3 (fill over misses and lands, elsewhere hits and stays), P4 (staged copy elsewhere hits, recorded stores over misses), P5 (exact-range copy: misses and binds the copy), and v1 still refusing on any label or staged copy. --- .../V2/MetalRenderHost.DeferredFills.cs | 13 ++ .../V2/MetalRenderHost.ReadBindingMemo.cs | 3 + .../MetalRenderHost.ReadBindingMemoRanges.cs | 43 +++--- .../V2/MetalRenderHost.StagedStorage.cs | 14 +- .../V2/MetalStagedStorage.cs | 58 +++++++- .../MetalClearFoldingTests.ReadBindingMemo.cs | 135 +++++++++++++++++- 6 files changed, 241 insertions(+), 25 deletions(-) diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.DeferredFills.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.DeferredFills.cs index 240be6c88..34b5b86bf 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.DeferredFills.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.DeferredFills.cs @@ -64,6 +64,8 @@ private bool TryDeferFillToPassEnd(ulong address, ulong size, uint value, in Met } _deferredFills.Add(new DeferredFill(address, size, value, range.Buffer, range.Offset)); + _deferredFillLow = Math.Min(_deferredFillLow, address); + _deferredFillHigh = Math.Max(_deferredFillHigh, address + size); _transferCauses[(int)MetalTransferCause.GuestFill]++; _fillsDeferred++; NoteRecordedWork(); @@ -75,6 +77,15 @@ private bool TryDeferFillToPassEnd(ulong address, ulong size, uint value, in Met return true; } + // The guest bytes the waiting fills span, low to high (MetalReadBindingMemoV2 tests a range against it first). + private ulong _deferredFillLow = ulong.MaxValue; + private ulong _deferredFillHigh; + + /// Whether a waiting fill lands in these guest bytes: the span first, then each fill. + private bool DeferredFillsOver(ulong address, ulong size) => + _deferredFills.Count != 0 && address < _deferredFillHigh && _deferredFillLow < address + size && + DeferredFillsTouch(address, size); + private bool DeferredFillsTouch(ulong address, ulong size) { foreach (var fill in _deferredFills) @@ -226,6 +237,8 @@ private void EncodeDeferredFills() } _deferredFills.Clear(); + _deferredFillLow = ulong.MaxValue; + _deferredFillHigh = 0; } finally { diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.ReadBindingMemo.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.ReadBindingMemo.cs index b87cc84e9..084b17fb2 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.ReadBindingMemo.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.ReadBindingMemo.cs @@ -58,6 +58,9 @@ internal sealed partial class MetalRenderHost /// The v2 memo and its counters (tests). internal MetalReadBindingMemoV2 ReadBindingMemoV2 => _readBindingMemoV2; + /// The held label copy class the last binding touched, -1 for none (tests). + internal int LabelTouchClass => _labelTouchClass; + // The entry the last v2 hit answered from (the verify mode reads its claims). private int _readBindingHitIndex = -1; diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.ReadBindingMemoRanges.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.ReadBindingMemoRanges.cs index 519664cf5..678cc1cd8 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.ReadBindingMemoRanges.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.ReadBindingMemoRanges.cs @@ -14,9 +14,11 @@ namespace SharpEmu.Gpu.Metal.V2; /// The window cuts: the window object the range was placed in is still in the partition (a cut move, a cut back /// to granules and a renewal all retire the windows they replace) and still has the buffer the entry holds; a window's /// bounds never change, so the range still fits it. +/// Deferred fills, held label copies and staged copies: the hit misses only when one is over the range, which is +/// exactly when the chain would land or order it, or answer with the staged copy (a span test first, so the common +/// case costs no walk). /// -/// The single-copy trap version and the image stamps are still read whole, as in v1, and so is the v1 refusal while any -/// fill, label copy or staged copy is pending. +/// The single-copy trap version and the image stamps are still read whole, as in v1. /// internal sealed partial class MetalRenderHost { @@ -36,21 +38,6 @@ private bool TryReadBindingMemoRanges(ulong address, ulong size, bool computeSta return MissReadBinding(ref memo.RefusedTrace); } - if (_deferredFills.Count != 0) - { - return MissReadBinding(ref memo.RefusedFill); - } - - if (_deferredLabelCopies.Count != 0) - { - return MissReadBinding(ref memo.RefusedLabel); - } - - if (_stagedStorageCopies is { Count: > 0 }) - { - return MissReadBinding(ref memo.RefusedStaged); - } - if (!_backing.TryResolveBackingAliasSpan(address, size, out var alias)) { return MissReadBinding(ref memo.RefusedUnmapped); @@ -100,6 +87,27 @@ private bool TryReadBindingMemoRanges(ulong address, ulong size, bool computeSta return MissReadBinding(ref memo.MissImageGpuModified); } + // Work the chain would land or order first, or a staged copy it would answer with: only over this range. + // OrderAfterDeferredCopies always forgets which held copy a binding last touched. + var fills = _deferredFills.Count != 0; + if (fills && DeferredFillsOver(address, size)) + { + return MissReadBinding(ref memo.RefusedFill); + } + + _labelTouchClass = -1; + var labels = _deferredLabelCopies.Count != 0; + if (labels && (_computeEncoder != 0 || LabelsAtCommit) && DeferredLabelCopiesTouch(address, size)) + { + return MissReadBinding(ref memo.RefusedLabel); + } + + var staged = _stagedStorageCopies is { Count: > 0 }; + if (staged && _stagedStorageCopies!.MayConcern(address, size)) + { + return MissReadBinding(ref memo.RefusedStaged); + } + if (!_guestMemory.UseWindowForHit(window, out var touched)) { return MissReadBinding(ref memo.MissWindowRetired); @@ -114,6 +122,7 @@ private bool TryReadBindingMemoRanges(ulong address, ulong size, bool computeSta side.Serial = _submissionSerial; } + memo.HitsWithPending += fills || labels || staged ? 1 : 0; _readBindingHitIndex = index; range = new MetalGuestRange(entry.Buffer, entry.Offset, size, entry.GpuAddress); return true; diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.StagedStorage.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.StagedStorage.cs index ccb341141..f854ac605 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.StagedStorage.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.StagedStorage.cs @@ -13,12 +13,20 @@ internal sealed partial class MetalRenderHost private MetalStagedStorage StagedStorage => _stagedStorageCopies ??= new MetalStagedStorage(_guestMemory, _stagedRanges); - /// Tests: a staged copy of these bytes, written by a recorded dispatch, to be written back at the encoder end. - internal void StageRecordedStoresForTest(ulong address, ulong size) + /// + /// Tests: a staged copy of these bytes, written by a recorded dispatch, to be written back at the encoder end; not + /// armed ( false), a copy whose dispatch is still being bound, which TryShare answers with. + /// + internal MetalGuestRange StageRecordedStoresForTest(ulong address, ulong size, bool armed = true) { var staging = _guestMemory.Stage(address, size); StagedStorage.Add(address, size, staging, _guestMemory.Stage(address, size), written: true); - StagedStorage.Arm(); + if (armed) + { + StagedStorage.Arm(); + } + + return staging; } private bool _encodingStagedStores; diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalStagedStorage.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalStagedStorage.cs index 675fc6a56..0e3bdaa14 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalStagedStorage.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalStagedStorage.cs @@ -111,6 +111,51 @@ private struct WritebackArguments public int Count => _copies.Count; + // The bytes the listed copies span, low to high: wider than they are after a copy leaves the list, until + // EndSubmission or Forget measures it again. + private ulong _spanLow = ulong.MaxValue; + private ulong _spanHigh; + + private void Widen(MetalStagedRangeCache.Entry copy) + { + _spanLow = Math.Min(_spanLow, copy.Address); + _spanHigh = Math.Max(_spanHigh, copy.Address + copy.Size); + } + + private void MeasureSpan() + { + _spanLow = ulong.MaxValue; + _spanHigh = 0; + foreach (var copy in _copies) + { + Widen(copy); + } + } + + /// + /// Whether a read-only binding of exactly these bytes would be answered by a copy () or + /// ordered after recorded stores (). False means neither would act; true may + /// also be a copy TryShare would pass over as stale (MetalReadBindingMemoV2 misses on it). + /// + public bool MayConcern(ulong address, ulong size) + { + if (_copies.Count == 0 || address >= _spanHigh || address + size <= _spanLow) + { + return false; + } + + foreach (var copy in _copies) + { + if ((copy.Address == address && copy.Size == size && !copy.Removed) || + (copy.Dirty && copy.Armed && Overlaps(copy, address, size))) + { + return true; + } + } + + return false; + } + /// The copy an earlier binding of exactly this range made, which this one shares. public bool TryShare(ulong address, ulong size, bool written, out MetalGuestRange staging) { @@ -157,6 +202,7 @@ public void Bind(MetalStagedRangeCache.Entry entry, bool written) { entry.InList = true; _copies.Add(entry); + Widen(entry); } if (written) @@ -204,8 +250,9 @@ public bool HasRecordedStores /// Keeps a staged copy for the later bindings of the same range. The pristine range /// holds the same bytes as the copy before any shader stores into it. /// - public void Add(ulong address, ulong size, MetalGuestRange staging, MetalGuestRange pristine, bool written) => - _copies.Add(new MetalStagedRangeCache.Entry + public void Add(ulong address, ulong size, MetalGuestRange staging, MetalGuestRange pristine, bool written) + { + var copy = new MetalStagedRangeCache.Entry { Address = address, Size = size, @@ -213,7 +260,10 @@ public void Add(ulong address, ulong size, MetalGuestRange staging, MetalGuestRa Pristine = pristine, Dirty = written, InList = true, - }); + }; + _copies.Add(copy); + Widen(copy); + } /// The draw or dispatch the copies were bound for has been recorded. public void Arm() @@ -253,6 +303,7 @@ public void Forget(ulong address, ulong size) if (kept != _copies.Count) { _copies.RemoveRange(kept, _copies.Count - kept); + MeasureSpan(); } } @@ -287,6 +338,7 @@ public void EndSubmission() copy.InList = false; return true; }); + MeasureSpan(); } /// diff --git a/tests/SharpEmu.Gpu.Metal.Tests/MetalClearFoldingTests.ReadBindingMemo.cs b/tests/SharpEmu.Gpu.Metal.Tests/MetalClearFoldingTests.ReadBindingMemo.cs index e6cf07548..aaf337d72 100644 --- a/tests/SharpEmu.Gpu.Metal.Tests/MetalClearFoldingTests.ReadBindingMemo.cs +++ b/tests/SharpEmu.Gpu.Metal.Tests/MetalClearFoldingTests.ReadBindingMemo.cs @@ -85,8 +85,10 @@ public void AReadOnlyBindingMissesOnceItsRangeIsRemapped() AssertMisses(host, () => BindRead(host), before with { Offset = before.Offset + 0x1000 }); } + // P4: a staged copy listed for other bytes leaves the binding to hit (v1: any listed copy refused it); one with + // recorded stores over the range makes it miss: the chain ends the encoders to write them back first. [Fact] - public void AReadOnlyBindingMissesWhileAStagedCopyIsBound() + public void AReadOnlyBindingHitsBesideAStagedCopyAndMissesUnderItsRecordedStores() { if (!RequireDevice()) return; using var rig = MemoRig(); @@ -94,12 +96,78 @@ public void AReadOnlyBindingMissesWhileAStagedCopyIsBound() var before = BindTwiceAndHit(host); // A written range across a view edge has no window: it is staged, and the copy is listed. + const ulong edge = GuestBase + 0x200000; + rig.ViewBoundary = edge; + Assert.True(host.ResolveStorageBuffer(edge - 0x80, 0x100, written: true).IsValid); + var pending = host.ReadBindingMemoV2.HitsWithPending; + AssertHits(host, () => BindRead(host), before); + Assert.Equal(pending + 1, host.ReadBindingMemoV2.HitsWithPending); + + host.StageRecordedStoresForTest(MemoBuffer + 0x40, 0x40); + AssertMissesBy(host, static memo => memo.RefusedStaged, () => BindRead(host)); + } + + // R1: the v1 memo refuses every binding while any staged copy is listed. + [Fact] + public void AV1ReadOnlyBindingMissesWhileAStagedCopyIsBound() + { + if (!RequireDevice()) return; + using var rig = MemoRig(); + var host = rig.Host; + host.ReadBindingMemoRanges = false; + var before = BindTwiceAndHit(host); + const ulong edge = GuestBase + 0x200000; rig.ViewBoundary = edge; Assert.True(host.ResolveStorageBuffer(edge - 0x80, 0x100, written: true).IsValid); AssertMisses(host, () => BindRead(host), before); } + // P5: a staged copy of exactly the range, its dispatch still being bound, is what the chain answers with. + [Fact] + public void AReadOnlyBindingMissesWhileAStagedCopyOfExactlyItsRangeIsListed() + { + if (!RequireDevice()) return; + using var rig = MemoRig(); + var host = rig.Host; + var before = BindTwiceAndHit(host); + + var staging = host.StageRecordedStoresForTest(MemoBuffer, MemoBufferBytes, armed: false); + var shared = AssertMissesBy(host, static memo => memo.RefusedStaged, () => BindRead(host)); + Assert.Equal(new BufferBinding((ulong)staging.Buffer, staging.Offset), shared); + Assert.NotEqual(before, shared); + } + + // P3: a fill the open pass holds over the range makes the binding miss (the chain ends the pass to land it); one + // elsewhere stays held and the binding hits. + [Fact] + public void AReadOnlyBindingMissesUnderADeferredFillAndHitsBesideOne() + { + if (!RequireDevice()) return; + using var rig = MemoRig(); + var host = rig.Host; + host.DeferPassFills = true; + using (host.BeginPreparation()) + { + var target = rig.Target(TargetAddress); + var attachment = ((IRenderHost)host).AcquireColorAttachment(in target); + host.BeginRendering(Rig.PassOver(attachment.View)); + var before = BindTwiceAndHit(host); + + host.FillGuestMemory(MemoBuffer + 0x10000, 0x100, 0x5A5A5A5Au, allowHost: false); + Assert.True(host.DeferredFillCount > 0, "the fill was not held by the pass"); + AssertHits(host, () => BindRead(host), before); + Assert.True(host.DeferredFillCount > 0, "the hit landed the fill"); + + host.FillGuestMemory(MemoBuffer + 0x80, 0x40, 0xA5A5A5A5u, allowHost: false); + AssertMissesBy(host, static memo => memo.RefusedFill, () => BindRead(host)); + Assert.Equal(0, host.DeferredFillCount); + host.EndRendering(); + } + + host.FlushAndWaitForGpu(); + } + [Fact] public void AReadOnlyBindingMissesOnceAnImageOverItGoesGpuModified() { @@ -120,20 +188,57 @@ public void AReadOnlyBindingMissesOnceAnImageOverItGoesGpuModified() } } + // P1: a label copy held to the commit over the range makes the binding miss (the chain lands it first); one held + // over other bytes stays held and the binding hits. P6: a hit forgets which held copy a binding last touched, as + // the chain does. [Fact] - public void AReadOnlyBindingMissesWhileADeferredLabelCopyIsHeld() + public void AReadOnlyBindingMissesUnderAHeldLabelCopyAndHitsBesideOne() { if (!RequireDevice()) return; using var rig = MemoRig(); var host = rig.Host; + Assert.True(host.LabelsAtCommit); using (host.BeginPreparation()) { var target = rig.Target(TargetAddress); var attachment = ((IRenderHost)host).AcquireColorAttachment(in target); host.BeginRendering(Rig.PassOver(attachment.View)); var before = BindTwiceAndHit(host); + var other = BindTwiceAndHit(host, MemoBuffer + 0x20000, 0x40); + + host.RecordCommandProcessorWrite(MemoBuffer + 0x10000, BitConverter.GetBytes(0xC0FFEE22u), "WRITE_DATA"); + Assert.True(host.DeferredLabelCopyCount > 0, "the write was not held as a label copy"); + AssertHits(host, () => BindRead(host), before); + Assert.True(host.DeferredLabelCopyCount > 0, "the hit landed the label copy"); host.RecordCommandProcessorWrite(MemoBuffer + 0x10, BitConverter.GetBytes(0xC0FFEE11u), "WRITE_DATA"); + AssertMissesBy(host, static memo => memo.RefusedLabel, () => BindRead(host)); + Assert.Equal(0, host.DeferredLabelCopyCount); + Assert.NotEqual(-1, host.LabelTouchClass); + AssertHits(host, () => BindRead(host, MemoBuffer + 0x20000, 0x40), other); + Assert.Equal(-1, host.LabelTouchClass); + host.EndRendering(); + } + + host.FlushAndWaitForGpu(); + } + + // R1: the v1 memo refuses every binding while any label copy is held. + [Fact] + public void AV1ReadOnlyBindingMissesWhileADeferredLabelCopyIsHeld() + { + if (!RequireDevice()) return; + using var rig = MemoRig(); + var host = rig.Host; + host.ReadBindingMemoRanges = false; + using (host.BeginPreparation()) + { + var target = rig.Target(TargetAddress); + var attachment = ((IRenderHost)host).AcquireColorAttachment(in target); + host.BeginRendering(Rig.PassOver(attachment.View)); + var before = BindTwiceAndHit(host); + + host.RecordCommandProcessorWrite(MemoBuffer + 0x10000, BitConverter.GetBytes(0xC0FFEE11u), "WRITE_DATA"); Assert.True(host.DeferredLabelCopyCount > 0, "the write was not held as a label copy"); AssertMisses(host, () => BindRead(host), before); host.EndRendering(); @@ -142,6 +247,32 @@ public void AReadOnlyBindingMissesWhileADeferredLabelCopyIsHeld() host.FlushAndWaitForGpu(); } + // P2: with copies held only to the end of the open encoder and no compute encoder open, a draw's binding needs + // nothing ordered (beginning a pass ends the compute encoder): even over the range it hits. + [Fact] + public void AReadOnlyBindingHitsOverALabelCopyHeldToARenderEncoderEnd() + { + if (!RequireDevice()) return; + using var rig = MemoRig(); + var host = rig.Host; + host.LabelsAtCommit = false; + using (host.BeginPreparation()) + { + var target = rig.Target(TargetAddress); + var attachment = ((IRenderHost)host).AcquireColorAttachment(in target); + host.BeginRendering(Rig.PassOver(attachment.View)); + var before = BindTwiceAndHit(host); + + host.RecordCommandProcessorWrite(MemoBuffer + 0x10, BitConverter.GetBytes(0xC0FFEE33u), "WRITE_DATA"); + Assert.True(host.DeferredLabelCopyCount > 0, "the write was not held as a label copy"); + AssertHits(host, () => BindRead(host), before); + Assert.True(host.DeferredLabelCopyCount > 0); + host.EndRendering(); + } + + host.FlushAndWaitForGpu(); + } + // R1: the v1 memo (SHARPEMU_METAL_V2_READ_BINDING_MEMO_RANGES=0) stamps the submission: a new command buffer misses. [Fact] public void AV1ReadOnlyBindingMissesInANewCommandBuffer() From f7ef33e45c42d0a15409a1de19301180b84fb73d Mon Sep 17 00:00:00 2001 From: kuba Date: Sun, 15 Nov 2026 09:35:18 +0000 Subject: [PATCH 048/178] [Metal] Read-binding memo v2: image validity per range (no owner pages, or the images over it unchanged and clean) The v1 stamp missed on any image added or dropped anywhere and on any image going GPU-modified. A v2 entry now records what the image flush answered by when it was stored: no image owns a page of the range (checked live with MayOwn on every hit), or the images overlapping its bytes (MetalImageCache.ListOverlapping, at most two, with the image-set version read under the cache lock). Such an entry hits while no image added or dropped since overlaps the range (MetalImageCache.ImageSetUnchangedOver walks the change ring, at most ImageSetWalkCap = 16 changes, then refreshes the version) and none of its held images is GPU-modified now. More than two images: not kept. Verify mode checks the claim behind every hit against the cache's current answer. Tests: I1 (image elsewhere hits, image over the pages misses), I2 (another image GPU-written hits, its own misses; v1 misses on any), I3 (same pages, no overlap: a far image is checked off and hits, an image over it misses), I4 (unrelated image churn hits), I5 (more than 16 changes: one miss, then hits). --- .../SharpEmu.Gpu.Metal/V2/MetalImageCache.cs | 70 +++++++++++++ .../V2/MetalReadBindingMemoV2.cs | 3 - .../MetalRenderHost.ReadBindingMemoRanges.cs | 80 +++++++++++++-- .../MetalClearFoldingTests.ReadBindingMemo.cs | 98 ++++++++++++++++++- 4 files changed, 239 insertions(+), 12 deletions(-) diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.cs index 740fc7471..cb1825cfd 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.cs @@ -402,6 +402,76 @@ private void NoteImageSetChanged(GuestSpan range) } } + // How many image-set changes a read-only binding memo entry is checked across before it just misses. + internal const int ImageSetWalkCap = 16; + + /// + /// Whether no image added or dropped after version overlaps the guest bytes + /// [, +) - which then have the same images over them as at + /// - and the version that holds for (). False when one does, when + /// more than changes were made since, or when the ring no longer holds them all + /// (MetalReadBindingMemoV2). + /// + public bool ImageSetUnchangedOver(long since, ulong address, ulong size, out long now) + { + lock (_imageSetChangeGate) + { + now = Volatile.Read(ref _imageSetVersion); + if (since < 0 || now < since || now - since > ImageSetWalkCap) + { + return false; + } + + var end = size > ulong.MaxValue - address ? ulong.MaxValue : address + size; + for (var version = since + 1; version <= now; version++) + { + var change = _imageSetChanges[version % ImageSetChangeCount]; + if (change.Version != version || (change.Start < end && address < change.End)) + { + return false; + } + } + + return true; + } + } + + /// + /// The images whose guest bytes overlap the range - those FlushGpuWrites would look at - up to two of them, how + /// many there are, and the image-set version they are listed at (read under the lock that adds and drops images). + /// + public void ListOverlapping( + ulong address, ulong size, out MetalCachedImage? first, out MetalCachedImage? second, out int count, out long version) + { + first = second = null; + count = 0; + using var held = _lock.Hold(); + version = ImageSetVersion; + if (!IsValidRange(address, size)) + { + return; + } + + foreach (var imageIdentifier in FindImagesInRange(address, size, pageOverlap: false)) + { + if (_slots.TryGet(imageIdentifier) is not { } image || !image.Overlaps(address, size)) + { + continue; + } + + if (count == 0) + { + first = image; + } + else if (count == 1) + { + second = image; + } + + count++; + } + } + /// /// The guest ranges of the images added or dropped after version up to /// , sorted by start and merged; false when they are no longer all known. diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalReadBindingMemoV2.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalReadBindingMemoV2.cs index ba96b138d..a2bbc224f 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalReadBindingMemoV2.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalReadBindingMemoV2.cs @@ -55,9 +55,6 @@ internal struct Side // The submission the entry last answered in (hits_new_cb). public ulong Serial; - // The image cache's GPU-modified epoch the entry was stored at. - public long GpuModified; - // Tier Held: the images over the range. public MetalCachedImage? Image0; public MetalCachedImage? Image1; diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.ReadBindingMemoRanges.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.ReadBindingMemoRanges.cs index 678cc1cd8..efa0c58e4 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.ReadBindingMemoRanges.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.ReadBindingMemoRanges.cs @@ -17,8 +17,12 @@ namespace SharpEmu.Gpu.Metal.V2; /// Deferred fills, held label copies and staged copies: the hit misses only when one is over the range, which is /// exactly when the chain would land or order it, or answer with the staged copy (a span test first, so the common /// case costs no walk). +/// Images: the flush finds nothing when no image owns a page of the range (checked live), or when the images +/// overlapping it are the ones the entry was stored with - none added or dropped over the range since (the image-set +/// change ring, up to MetalImageCache.ImageSetWalkCap changes back) - and none of them is GPU-modified now (up to two +/// held by the entry, checked live). An image's guest range never changes in place. /// -/// The single-copy trap version and the image stamps are still read whole, as in v1. +/// The single-copy trap version is still read whole, as in v1. /// internal sealed partial class MetalRenderHost { @@ -77,14 +81,33 @@ private bool TryReadBindingMemoRanges(ulong address, ulong size, bool computeSta return MissReadBinding(ref memo.MissTrap); } - if (entry.ImageSet != _imageCache.ImageSetVersion) + // The image flush would find no GPU-modified image over the range: none can own its pages, or the images over + // it are those the entry was stored with (none added or dropped over it since) and none is GPU-modified now. + if (entry.Tier == MetalReadBindingMemoV2.ImageTier.NoOwnerPages) { - return MissReadBinding(ref memo.MissImageSet); + if (_imageCache.MayOwn(address, size)) + { + return MissReadBinding(ref memo.MissImagePages); + } } - - if (side.GpuModified != _imageCache.Epochs.GpuModified) + else { - return MissReadBinding(ref memo.MissImageGpuModified); + if (entry.ImageSet != _imageCache.ImageSetVersion) + { + if (!_imageCache.ImageSetUnchangedOver(entry.ImageSet, address, size, out var now)) + { + return MissReadBinding(ref memo.MissImageSet); + } + + entry.ImageSet = now; + memo.RevalidatedImageSet++; + } + + if (entry.Tier == MetalReadBindingMemoV2.ImageTier.Held && + (side.Image0!.IsGpuModified || (side.Image1?.IsGpuModified ?? false))) + { + return MissReadBinding(ref memo.MissImageGpuModified); + } } // Work the chain would land or order first, or a staged copy it would answer with: only over this range. @@ -165,6 +188,25 @@ private void StoreReadBindingRanges( return; } + // What the flush answered by: no owner pages (checked live), or the images over the range now, listed with the + // version they hold at; more than two are not kept. + var tier = MetalReadBindingMemoV2.ImageTier.NoOwnerPages; + MetalCachedImage? first = null; + MetalCachedImage? second = null; + var count = 0; + var imageSet = 0L; + if (_imageCache.MayOwn(address, size)) + { + _imageCache.ListOverlapping(address, size, out first, out second, out count, out imageSet); + if (count > 2) + { + memo.StoreSkipImageMany++; + return; + } + + tier = count == 0 ? MetalReadBindingMemoV2.ImageTier.NoImage : MetalReadBindingMemoV2.ImageTier.Held; + } + var index = memo.Insert(address, (uint)size, computeStage); ref var entry = ref memo.At(index); entry.Alias = inPlaceAlias; @@ -172,11 +214,14 @@ private void StoreReadBindingRanges( entry.Buffer = range.Buffer; entry.Offset = range.Offset; entry.GpuAddress = range.GpuAddress; - entry.ImageSet = before.ImageSet; + entry.Tier = tier; + entry.HeldImages = (byte)count; + entry.ImageSet = imageSet; ref var side = ref memo.SideAt(index); side.Trap = before.Trap; - side.GpuModified = before.GpuModified; side.Serial = _submissionSerial; + side.Image0 = first; + side.Image1 = second; } // =verify, before the full chain runs behind a v2 hit: the hit pinned and touched its window (the chain would @@ -197,6 +242,25 @@ private void VerifyReadBindingHitClaims(ulong address, ulong size, bool computeS $"A memoised read-only binding did not pin and touch its window for this command buffer: address=0x{address:X16} " + $"size=0x{size:X} window={window.Id} retired={window.Retired} memo={memo}."); } + + // The images it answered by: none owns a page, or exactly the images it holds are over the range. + var side = _readBindingMemoV2.SideAt(index); + var mayOwn = _imageCache.MayOwn(address, size); + _imageCache.ListOverlapping(address, size, out var first, out var second, out var count, out _); + var holds = entry.Tier switch + { + MetalReadBindingMemoV2.ImageTier.NoOwnerPages => !mayOwn, + MetalReadBindingMemoV2.ImageTier.NoImage => count == 0, + _ => count == entry.HeldImages && + (ReferenceEquals(first, side.Image0) || ReferenceEquals(first, side.Image1)) && + (count == 1 || ReferenceEquals(second, side.Image0) || ReferenceEquals(second, side.Image1)), + }; + if (!holds) + { + throw Fatal( + $"A memoised read-only binding's images moved under it: address=0x{address:X16} size=0x{size:X} " + + $"tier={entry.Tier} held={entry.HeldImages} may_own={mayOwn} overlapping={count}."); + } } /// What the chain behind a read-only binding can do, read on both sides of it in the verify mode. diff --git a/tests/SharpEmu.Gpu.Metal.Tests/MetalClearFoldingTests.ReadBindingMemo.cs b/tests/SharpEmu.Gpu.Metal.Tests/MetalClearFoldingTests.ReadBindingMemo.cs index aaf337d72..be544499a 100644 --- a/tests/SharpEmu.Gpu.Metal.Tests/MetalClearFoldingTests.ReadBindingMemo.cs +++ b/tests/SharpEmu.Gpu.Metal.Tests/MetalClearFoldingTests.ReadBindingMemo.cs @@ -168,6 +168,8 @@ public void AReadOnlyBindingMissesUnderADeferredFillAndHitsBesideOne() host.FlushAndWaitForGpu(); } + // I2: an image over the range going GPU-modified makes the binding miss (the flush would write it back); another + // image going GPU-modified leaves it. I4: images added elsewhere leave it too. [Fact] public void AReadOnlyBindingMissesOnceAnImageOverItGoesGpuModified() { @@ -176,11 +178,22 @@ public void AReadOnlyBindingMissesOnceAnImageOverItGoesGpuModified() var host = rig.Host; var request = Rig.Request(TargetAddress, ImageRole.Texture); var image = host.ImageCache.FindImage(ref request); + var otherRequest = Rig.Request(OtherAddress, ImageRole.Texture); + var other = host.ImageCache.FindImage(ref otherRequest); var before = BindTwiceAndHit(host, TargetAddress + 0x40, 0x40); + var epoch = host.ImageCache.Epochs.GpuModified; + host.ImageCache.MarkGpuWritten(other); + Assert.NotEqual(epoch, host.ImageCache.Epochs.GpuModified); + AssertHits(host, () => BindRead(host, TargetAddress + 0x40, 0x40), before); + + var far = Rig.Request(GuestBase + 0x300000, ImageRole.Texture); + host.ImageCache.FindImage(ref far); + AssertHits(host, () => BindRead(host, TargetAddress + 0x40, 0x40), before); + host.ImageCache.MarkGpuWritten(image); Assert.True(host.ImageCache.HasGpuModifiedImageBytes(TargetAddress + 0x40, 0x40)); - AssertMisses(host, () => BindRead(host, TargetAddress + 0x40, 0x40), before); + AssertMissesBy(host, static memo => memo.MissImageGpuModified, () => BindRead(host, TargetAddress + 0x40, 0x40)); // While the image owns the bytes, the flush finds it each time: nothing is kept for the range. if (host.ImageCache.HasGpuModifiedImageBytes(TargetAddress + 0x40, 0x40)) { @@ -188,6 +201,89 @@ public void AReadOnlyBindingMissesOnceAnImageOverItGoesGpuModified() } } + // R1: the v1 memo stamps the GPU-modified epoch: another image going GPU-modified makes it miss. + [Fact] + public void AV1ReadOnlyBindingMissesOnceAnyImageGoesGpuModified() + { + if (!RequireDevice()) return; + using var rig = MemoRig(); + var host = rig.Host; + host.ReadBindingMemoRanges = false; + var otherRequest = Rig.Request(OtherAddress, ImageRole.Texture); + var other = host.ImageCache.FindImage(ref otherRequest); + var before = BindTwiceAndHit(host); + + host.ImageCache.MarkGpuWritten(other); + AssertMisses(host, () => BindRead(host), before); + } + + // I1: a range no image owns a page of; an image made elsewhere leaves it, one made over it makes it miss. + [Fact] + public void AReadOnlyBindingMissesOnceAnImageIsMadeOverItsPages() + { + if (!RequireDevice()) return; + using var rig = MemoRig(); + var host = rig.Host; + Assert.False(host.ImageCache.MayOwn(MemoBuffer, MemoBufferBytes)); + var before = BindTwiceAndHit(host); + + var elsewhere = Rig.Request(OtherAddress, ImageRole.Texture); + host.ImageCache.FindImage(ref elsewhere); + AssertHits(host, () => BindRead(host), before); + + var over = Rig.Request(MemoBuffer, ImageRole.Texture); + host.ImageCache.FindImage(ref over); + AssertMissesBy(host, static memo => memo.MissImagePages, () => BindRead(host)); + AssertHits(host, () => BindRead(host), before); + } + + // I3: a range on an image's pages that no image overlaps: an image added on far pages is checked off against the + // range and it hits; one added over the range makes it miss. + [Fact] + public void AReadOnlyBindingBesideAnImageMissesOnlyOnceAnImageIsMadeOverIt() + { + if (!RequireDevice()) return; + using var rig = MemoRig(); + var host = rig.Host; + var request = Rig.Request(TargetAddress, ImageRole.Texture); + host.ImageCache.FindImage(ref request); + const ulong beside = TargetAddress + 0x800; + Assert.True(host.ImageCache.MayOwn(beside, 0x40)); + var before = BindTwiceAndHit(host, beside, 0x40); + + var revalidated = host.ReadBindingMemoV2.RevalidatedImageSet; + var far = Rig.Request(GuestBase + 0x300000, ImageRole.Texture); + host.ImageCache.FindImage(ref far); + AssertHits(host, () => BindRead(host, beside, 0x40), before); + Assert.Equal(revalidated + 1, host.ReadBindingMemoV2.RevalidatedImageSet); + + var over = Rig.Request(beside, ImageRole.Texture); + host.ImageCache.FindImage(ref over); + AssertMissesBy(host, static memo => memo.MissImageSet, () => BindRead(host, beside, 0x40)); + AssertHits(host, () => BindRead(host, beside, 0x40), before); + } + + // I5: more image-set changes since the entry was checked than a hit walks: it misses once, then hits again. + [Fact] + public void AReadOnlyBindingMissesOnceTooManyImagesChangedSinceItWasChecked() + { + if (!RequireDevice()) return; + using var rig = MemoRig(); + var host = rig.Host; + var request = Rig.Request(TargetAddress, ImageRole.Texture); + host.ImageCache.FindImage(ref request); + var before = BindTwiceAndHit(host, TargetAddress + 0x40, 0x40); + + for (var image = 0; image <= MetalImageCache.ImageSetWalkCap; image++) + { + var far = Rig.Request(GuestBase + 0x300000 + ((ulong)image * 0x1000), ImageRole.Texture); + host.ImageCache.FindImage(ref far); + } + + AssertMissesBy(host, static memo => memo.MissImageSet, () => BindRead(host, TargetAddress + 0x40, 0x40)); + AssertHits(host, () => BindRead(host, TargetAddress + 0x40, 0x40), before); + } + // P1: a label copy held to the commit over the range makes the binding miss (the chain lands it first); one held // over other bytes stays held and the binding hits. P6: a hit forgets which held copy a binding last touched, as // the chain does. From fc160c414a16d2954a6eff2fce7dc467babe23ed Mon Sep 17 00:00:00 2001 From: kuba Date: Sun, 15 Nov 2026 09:36:25 +0000 Subject: [PATCH 049/178] [Metal] Read-binding memo v2: single-copy trap moves re-checked per range under the window lock An entry stands at the single-copy trap version (holes and stale windows) it was checked at. When the version moved, MetalGuestMemory.RevalidateInPlace asks under the window lock whether the resolve would do anything for this range and window: the window still in the partition with its buffer, not stale, no hole in the range's chunks, no released chunk. Stricter than the resolve, so a no only costs the full path; a yes refreshes the entry's version (revalidated.trap). Without single-copy textures the version never moves. Test (next to the single-copy tests, on a real chunked backing): released chunks refuse the range (W5), a hole elsewhere in the window leaves the range beside standing, a hole under the range and a stale window refuse it (T1), the renewed window stands again and the old one is retired. --- .../V2/MetalGuestMemory.SingleCopy.cs | 34 +++++++++++ .../MetalRenderHost.ReadBindingMemoRanges.cs | 16 ++++- .../MetalSingleCopyTests.ReadBindingMemo.cs | 59 +++++++++++++++++++ 3 files changed, 107 insertions(+), 2 deletions(-) create mode 100644 tests/SharpEmu.Gpu.Metal.Tests/MetalSingleCopyTests.ReadBindingMemo.cs diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalGuestMemory.SingleCopy.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalGuestMemory.SingleCopy.cs index a5a48b235..65bee56e4 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalGuestMemory.SingleCopy.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalGuestMemory.SingleCopy.cs @@ -256,6 +256,40 @@ internal bool IsStaleSingleCopyRange(ulong offset, ulong size) } } + /// Whether single-copy textures are on: holes and stale windows can lie under a window. + internal bool SingleCopyActive => _singleCopy is not null; + + /// + /// Whether resolving a range that translates to in place, through + /// holding , would restore, fill and renew nothing now, and give + /// that window: it is still in the partition with that buffer, it is not stale, no hole lies in the range's chunks + /// and no chunk of it is released. is the trap version this holds at (read under the + /// same lock). Stricter than the resolve (a hole it would not fill, a stale window whose stale bytes are elsewhere, + /// both answer false), so a false answer only costs the full path (MetalReadBindingMemoV2). + /// + internal bool RevalidateInPlace(MetalWindowPartition.Window window, nint buffer, ulong alias, ulong size, out long trapVersion) + { + var offset = alias - _aliasBase; + lock (_windowLock) + { + trapVersion = _trapVersion; + if (window.Retired || window.Buffer != buffer || _staleWindows.ContainsKey(window) || size == 0 || + (_singleCopy is { } state && state.AnyReleased(offset, size))) + { + return false; + } + + if (_holes is not { } holes || _holeCount == 0) + { + return true; + } + + var first = (int)(offset / _chunkBytes); + var last = (int)Math.Min((offset + size - 1) / _chunkBytes, (ulong)holes.Length - 1); + return first > last || holes.AsSpan(first, last - first + 1).IndexOfAnyExcept((byte)0) < 0; + } + } + internal bool TryTakeSingleCopyPunched(out (int Chunk, ulong Serial) punched) => _punched.TryDequeue(out punched); /// Whether the GPU alias maps the dummy over a chunk now. diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.ReadBindingMemoRanges.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.ReadBindingMemoRanges.cs index efa0c58e4..3a2713bef 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.ReadBindingMemoRanges.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.ReadBindingMemoRanges.cs @@ -21,8 +21,12 @@ namespace SharpEmu.Gpu.Metal.V2; /// overlapping it are the ones the entry was stored with - none added or dropped over the range since (the image-set /// change ring, up to MetalImageCache.ImageSetWalkCap changes back) - and none of them is GPU-modified now (up to two /// held by the entry, checked live). An image's guest range never changes in place. +/// Single-copy holes and stale windows: an entry stands at the trap version it was checked at; when that moved, +/// MetalGuestMemory.RevalidateInPlace asks under the window lock whether one is under this range and window. +/// The mapping (the backing alias, compared on every hit) and what MetalGuestMemory.InPlaceAnswerStands +/// checks live (nothing stages everything, no slot trap, no released chunk under the range). /// -/// The single-copy trap version is still read whole, as in v1. +/// Written bindings always take the full chain. Every miss is counted once, by the first check that failed. /// internal sealed partial class MetalRenderHost { @@ -75,10 +79,18 @@ private bool TryReadBindingMemoRanges(ulong address, ulong size, bool computeSta return MissReadBinding(ref memo.RefusedWindow); } + // Single-copy holes or stale windows changed somewhere since the entry was checked: whether any is under this + // range and window is asked under the window lock. ref var side = ref memo.SideAt(index); if (side.Trap != _guestMemory.TrapVersionNow) { - return MissReadBinding(ref memo.MissTrap); + if (!_guestMemory.RevalidateInPlace(window, entry.Buffer, alias, size, out var trap)) + { + return MissReadBinding(ref memo.MissTrap); + } + + side.Trap = trap; + memo.RevalidatedTrap++; } // The image flush would find no GPU-modified image over the range: none can own its pages, or the images over diff --git a/tests/SharpEmu.Gpu.Metal.Tests/MetalSingleCopyTests.ReadBindingMemo.cs b/tests/SharpEmu.Gpu.Metal.Tests/MetalSingleCopyTests.ReadBindingMemo.cs new file mode 100644 index 000000000..82bb00cbe --- /dev/null +++ b/tests/SharpEmu.Gpu.Metal.Tests/MetalSingleCopyTests.ReadBindingMemo.cs @@ -0,0 +1,59 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using SharpEmu.Gpu.Metal.V2; +using SharpEmu.Libs.Gpu.Images; +using Xunit; + +namespace SharpEmu.Gpu.Metal.Tests; + +public sealed unsafe partial class MetalSingleCopyTests +{ + // What the read-only binding memo (MetalReadBindingMemoV2) asks of the windows once single-copy holes or stale + // windows changed: a range's in-place answer stands only with no released chunk (W5), no hole (T1) and no stale + // window under it, through a window still in the partition; holes elsewhere in the window leave it standing. + [Fact] + public void AnInPlaceAnswerStandsOnlyWithNoReleasedChunkHoleOrStaleWindowUnderIt() + { + if (!RequireDevice()) return; + using var rig = new Rig(Device.Value); + var request = Request(rig.ImageAddress, GuestTileMode.Standard64KB); + var size = request.Description.Data.Size; + var bytes = Pattern(size, 71); + rig.Release(request, bytes, (int)(size / Chunk)); + ulong Alias(ulong address) => rig.Views.AliasBase + (address - rig.Address); + + // W5: released chunks under the run. + Assert.False(rig.Memory.InPlaceAnswerStands(Alias(rig.ImageAddress), size)); + + // The bytes beside the run, in the same window: the holes are elsewhere in it. + Assert.True(rig.Memory.TryResolveInPlace(rig.ImageAddress + size, size, out var near, out var nearAlias, out var window)); + Assert.NotNull(window); + Assert.True(rig.Memory.InPlaceAnswerStands(nearAlias, size)); + Assert.True(rig.Memory.RevalidateInPlace(window, near.Buffer, nearAlias, size, out _)); + + // Restored: no chunk released any more, but the holes are still punched until something fills them. + Assert.Equal(bytes, rig.Read(rig.ImageAddress, size)); + Assert.True(rig.Memory.IsSingleCopyHole(rig.ChunkOf(rig.ImageAddress))); + Assert.True(rig.Memory.InPlaceAnswerStands(Alias(rig.ImageAddress), size)); + // T1: a hole under the range. + Assert.False(rig.Memory.RevalidateInPlace(window, near.Buffer, Alias(rig.ImageAddress), size, out _)); + Assert.True(rig.Memory.RevalidateInPlace(window, near.Buffer, nearAlias, size, out var trap)); + + // Binding the run fills its holes; the window, pinned by the binding beside, is stale until the next + // submission, for the bytes beside too. + var staged = rig.Memory.Resolve(rig.ImageAddress, size); + Assert.False(rig.Memory.IsInPlace(staged)); + Assert.True(rig.Memory.HasStaleSingleCopyWindows); + Assert.False(rig.Memory.RevalidateInPlace(window, near.Buffer, nearAlias, size, out var staleTrap)); + Assert.NotEqual(trap, staleTrap); + + // The next submission renews it: the old window has left the partition, the new one stands. + rig.Submit(); + Assert.True(window.Retired); + Assert.False(rig.Memory.RevalidateInPlace(window, near.Buffer, nearAlias, size, out _)); + Assert.True(rig.Memory.TryResolveInPlace(rig.ImageAddress + size, size, out var renewed, out nearAlias, out var renewedWindow)); + Assert.True(rig.Memory.RevalidateInPlace(renewedWindow!, renewed.Buffer, nearAlias, size, out _)); + Assert.True(rig.Memory.RevalidateInPlace(renewedWindow!, renewed.Buffer, Alias(rig.ImageAddress), size, out _)); + } +} From 5abf5c18ec4b1018b544e01ad6960dfee425b9fe Mon Sep 17 00:00:00 2001 From: kuba Date: Sun, 15 Nov 2026 09:41:02 +0000 Subject: [PATCH 050/178] [Tests] DS draw-cost bench: GameShaped variation for the read-binding memo The Draws variation binds some 200 distinct ranges in one submission, where both memos hit ~98%. GameShaped is shaped like a Demon's Souls frame where the memo sees it: 3000 meshes (SHARPEMU_DS_DRAW_BENCH_MESHES) of about seven read-only ranges, 7300 draws a round (_GAME_DRAWS), each mesh in two draws in a row ~1.2 times a round far apart; 39 submissions with a commit about every 2.2 (~17.5 command buffers); WRITE_DATA label writes held to the commit in the last submission before each commit (~600 a round, every 200th into the object constants all draws bind); four dispatches per pass storing buffers that four meshes' draws read; and a texture on far pages dropped every third submission and made again when sampled. The round's CPU time covers the 39 recordings and commits. The v1 memo hits ~34% on it (Demon's Souls: 37-38%); the checksum covers the targets and the stored buffers. --- .../Scenes/DsDrawCostBenchTests.cs | 217 ++++++++++++++++-- 1 file changed, 204 insertions(+), 13 deletions(-) diff --git a/tests/SharpEmu.Gpu.Metal.Tests/Scenes/DsDrawCostBenchTests.cs b/tests/SharpEmu.Gpu.Metal.Tests/Scenes/DsDrawCostBenchTests.cs index 9b982f7b3..71ab5cbc2 100644 --- a/tests/SharpEmu.Gpu.Metal.Tests/Scenes/DsDrawCostBenchTests.cs +++ b/tests/SharpEmu.Gpu.Metal.Tests/Scenes/DsDrawCostBenchTests.cs @@ -214,7 +214,13 @@ private static uint[] TablePixel(int targets) // CLOCK_THREAD_CPUTIME_ID: the recording thread's own CPU time. private static ulong ThreadCpuNanoseconds() => clock_gettime_nsec_np(16); - private enum Variation { Draws, Dispatches } + private enum Variation { Draws, Dispatches, GameShaped } + + // GameShaped: the draw stream split into this many submissions a round, a command buffer committed about every + // SubmissionsPerCommit of them (Demon's Souls: ~39 submissions and ~17.5 command buffers a frame). + private const int GameSubmissions = 39; + private const double SubmissionsPerCommit = 2.2; + private const int ChurnTextures = 8; private static ulong Texels(SceneRig rig, uint width, uint height, uint layers, uint bytesPerTexel, Func word) { @@ -280,17 +286,17 @@ int Setting(string name, int fallback) => // Each mesh a quad over one cell of a 6x4 grid, four 16-byte-record vertex buffers and a constants buffer; // indices 0-5 and an indexed-indirect argument record. var objectConstants = rig.Memory.Upload(new float[16], 256); - var meshes = Enumerable.Range(0, Meshes).Select(mesh => + (ulong table, ulong indices, ulong arguments) Mesh(int mesh, ulong normalBuffer = 0) { - var (column, row) = (mesh % 6, mesh / 6); + var (column, row) = (mesh % 6, mesh / 6 % 4); var (left, right) = (-1f + column / 3f, -1f + (column + 1) / 3f); var (top, bottom) = (1f - row / 2f, 1f - (row + 1) / 2f); float[] positions = [left, bottom, 0.5f, 1, right, bottom, 0.5f, 1, left, top, 0.5f, 1, left, top, 0.5f, 1, right, bottom, 0.5f, 1, right, top, 0.5f, 1]; float[] uvs = [0, 1, 0, 1, 1, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 0, 1, 1, 0, 0, 1]; var position = rig.Memory.Upload(positions); var uv = rig.Memory.Upload(uvs); - var normal = rig.Memory.Upload(new float[24]); - var color = rig.Memory.Upload(Enumerable.Range(0, 24).Select(index => index % 4 == 3 ? 0f : mesh / 512f).ToArray()); + var normal = normalBuffer != 0 ? normalBuffer : rig.Memory.Upload(new float[24]); + var color = rig.Memory.Upload(Enumerable.Range(0, 24).Select(index => index % 4 == 3 ? 0f : mesh % 512 / 512f).ToArray()); var constants = rig.Memory.Upload(new float[8], 256); var table = rig.Memory.Upload( [ @@ -300,12 +306,64 @@ .. Descriptors.Buffer(color, 16, 6), .. Descriptors.Buffer(constants, 16, 2), var indices = rig.Memory.Upload([0, 1, 2, 3, 4, 5, 0, 0], 256); var arguments = rig.Memory.Upload([6, 1, 0, 0, 0, 0, 0, 0], 256); return (table, indices, arguments); - }).ToArray(); + } + + var meshes = Enumerable.Range(0, Meshes).Select(mesh => Mesh(mesh)).ToArray(); var vertexPrograms = Enumerable.Range(0, 3).Select(count => rig.Program(WithNops(TableVertex, count))).ToArray(); var pixelPrograms = new[] { 5, 6 }.Select(attachments => Enumerable.Range(0, 4).Select(count => rig.Program(WithNops(TablePixel(attachments), count))).ToArray()).ToArray(); + // One draw as DrawStream records it: a pass's first draw (or a submission's) sets the targets and depth. + void EmitDraw(ScenePm4 pm4, int draw, int pass, bool fullState, (ulong table, ulong indices, ulong arguments) mesh, ulong material) + { + var attachments = pass % 2 == 0 ? 5 : 6; + var set = pass % TargetSets; + uint[] vertexData = [Descriptors.Lo(mesh.table), Descriptors.Hi(mesh.table), 0, 0, .. Descriptors.Buffer(objectConstants, 16, 4)]; + uint[] pixelData = [Descriptors.Lo(material), Descriptors.Hi(material), 0, 0, .. Descriptors.Buffer(pixelConstants, 16, 2)]; + var vertexProgram = vertexPrograms[(draw / 3) % vertexPrograms.Length]; + var pixelProgram = pixelPrograms[attachments - 5][(draw / 2) % 4]; + SceneState state; + if (fullState) + { + state = new SceneState(TargetSize, TargetSize) + .DepthTarget(depths[set], TargetSize, TargetSize, zFormat: 3) + .DepthControl(test: true, write: true, CompareFunc.LessEqual); + for (var slot = 0u; slot < attachments; slot++) + state.ColorTarget(slot, targets[set][slot], TargetSize, TargetSize, format: 14, numberType: 7); + var mask = (1u << (attachments * 4)) - 1; + state.Context[Cx.CbTargetMask] = mask; + state.Context[Cx.CbShaderMask] = mask; + state.Context[Cx.SpiShaderColFormat] = 0x99999999u & mask; + pm4.Event(ScenePm4.EventCsPartialFlush); + } + else + { + state = new SceneState(TargetSize, TargetSize); + state.Context.Clear(); + state.Uconfig.Clear(); + state.Shader.Clear(); + } + + state.VertexShader(vertexProgram, vertexData).PixelShader(pixelProgram, pixelData).Emit(pm4); + pm4.NumInstances(1); + switch (draw % 10) + { + case < 7: + pm4.IndexType(0); + pm4.DrawIndexed(mesh.indices, 6, 6); + break; + case < 9: + pm4.Raw(ScenePm4.Header(4, ScenePm4.OpSetBase), 1u, (uint)mesh.arguments, (uint)(mesh.arguments >> 32)); + pm4.IndexType(0).Packet(ScenePm4.OpIndexBase, (uint)mesh.indices, (uint)(mesh.indices >> 32)).Packet(ScenePm4.OpIndexBufferSize, 6u); + pm4.Packet(ScenePm4.OpDrawIndexIndirect, 0u, 0u, 0u, 0u); + break; + default: + pm4.DrawAuto(6); + break; + } + } + uint[] DrawStream() { var pm4 = new ScenePm4(); @@ -407,15 +465,129 @@ uint[] DispatchStream() return pm4.ToArray(); } + // The dispatch table DispatchStream binds for dispatch n, storing its buffer into writeBuffer. + ulong DispatchTable(int dispatch, ulong writeBuffer) + { + var table = new List(); + table.AddRange(Descriptors.Texture(dispatch < StorageImages ? sources[dispatch] : storage[dispatch - StorageImages], Rgba32F, StorageEdge, StorageEdge)); + for (var texture = 1; texture < 5; texture++) + table.AddRange(Descriptors.Texture(textures[(dispatch * 3 + texture) % SampledTextures], Rgba8, TextureSize, TextureSize)); + table.AddRange(Descriptors.Texture(storage[dispatch], Rgba32F, StorageEdge, StorageEdge)); + table.AddRange(Descriptors.Texture(scratch[dispatch], Rgba32F, StorageEdge, StorageEdge)); + table.AddRange(samplers[dispatch % samplers.Length]); + table.AddRange(samplers[(dispatch + 1) % samplers.Length]); + for (var buffer = 0; buffer < 3; buffer++) + table.AddRange(Descriptors.Buffer(readBuffers[(dispatch + buffer) % readBuffers.Length], 4, StorageEdge * StorageEdge, 20)); + table.AddRange(Descriptors.Buffer(writeBuffer, 4, StorageEdge * StorageEdge, 20)); + return rig.Memory.Upload([.. table], 256); + } + + // GameShaped: the draw stream shaped like a Demon's Souls frame where the read-binding memo sees it. _MESHES + // (3000) meshes of about seven read-only ranges each (some 21k distinct ranges), _GAME_DRAWS (7300) draws a + // round, each mesh in two draws in a row ~1.2 times a round, far apart; GameSubmissions submissions with a commit + // about every SubmissionsPerCommit; in the last submission before each commit a WRITE_DATA every sixth draw into + // a label area, held to the commit (~600 a round, pending for about half of each command buffer, which leaves + // the v1 memo the ~38% of hits it had in game), every 200th of them into the object constants every draw binds; + // four dispatches at the start of each pass storing four buffers that + // the draws of four meshes read as their normals; and a texture on far pages dropped every third submission and + // made again when sampled next (image-set changes). + var gameMeshCount = Setting("MESHES", 3000); + var gameDrawCount = Setting("GAME_DRAWS", 7300); + (uint[][] Streams, ulong[] Written, ulong[] Churn) GameStreams() + { + var gameMeshes = Enumerable.Range(0, gameMeshCount).Select(mesh => Mesh(mesh)).ToArray(); + var written = Enumerable.Range(0, 4).Select(_ => rig.Memory.Upload(new uint[StorageEdge * StorageEdge], 256)).ToArray(); + var dynamicMeshes = written.Select((buffer, index) => Mesh(index, normalBuffer: buffer)).ToArray(); + var dispatchTables = written.Select((buffer, index) => DispatchTable(index, buffer)).ToArray(); + var labels = rig.Memory.Allocate(0x10000, 0x10000); + var churn = Enumerable.Range(0, ChurnTextures).Select(index => + Texels(rig, TextureSize, TextureSize, 1, 4, (_, y, x) => 0x30000000u + (uint)index * 0x00020406u + y * 0x0200u + x * 0x20u)).ToArray(); + var churnMaterials = churn.Select((texture, index) => + { + var table = new List(); + table.AddRange(Descriptors.Texture(texture, Rgba8, TextureSize, TextureSize)); + for (var slot = 1; slot < 12; slot++) + table.AddRange(Descriptors.Texture(textures[(index * 5 + slot * 3) % SampledTextures], Rgba8, TextureSize, TextureSize)); + for (var slot = 0; slot < 2; slot++) + table.AddRange(Descriptors.Texture(arrays[(index + slot) % ArrayTextures], Rgba8, TextureSize, TextureSize, type: 13, depthOrLastLayer: 1)); + for (var sampler = 0; sampler < 5; sampler++) table.AddRange(samplers[(sampler + index) % samplers.Length]); + return rig.Memory.Upload([.. table], 256); + }).ToArray(); + + var streams = new uint[GameSubmissions][]; + var passLength = (gameDrawCount + Passes - 1) / Passes; + var labelWrites = 0; + ScenePm4? pm4 = null; + var submission = -1; + for (var draw = 0; draw <= gameDrawCount; draw++) + { + var next = draw == gameDrawCount ? GameSubmissions : (int)((long)draw * GameSubmissions / gameDrawCount); + if (next != submission) + { + if (pm4 is not null) streams[submission] = pm4.ToArray(); + if (draw == gameDrawCount) break; + pm4 = new ScenePm4(); + submission = next; + } + + var pass = draw / passLength; + var passStart = draw % passLength == 0; + if (passStart) + { + for (var dispatch = 0; dispatch < dispatchTables.Length; dispatch++) + { + var compute = new SceneState(1, 1); + compute.Context.Clear(); + compute.Uconfig.Clear(); + compute.ComputeShader(computePrograms[dispatch % computePrograms.Length], 8, 8, 1, + [Descriptors.Lo(dispatchTables[dispatch]), Descriptors.Hi(dispatchTables[dispatch])], true, true, false, 1, 0); + compute.Emit(pm4!); + pm4!.DispatchDirect(StorageEdge / 8, StorageEdge / 8, 1); + } + } + + var firstOfSubmission = (int)((long)draw * GameSubmissions / gameDrawCount) != (int)((long)(draw - 1) * GameSubmissions / gameDrawCount) || draw == 0; + var mesh = draw % 16 == 15 + ? dynamicMeshes[draw / 16 % dynamicMeshes.Length] + : gameMeshes[(int)((ulong)(draw / 2) * 7919UL % (ulong)gameMeshCount)]; + var material = firstOfSubmission + ? churnMaterials[submission % ChurnTextures] + : materials[(draw * 11 + pass * 3) % Materials]; + EmitDraw(pm4!, draw, pass, passStart || firstOfSubmission, mesh, material); + var commitFollows = (int)((submission + 1) / SubmissionsPerCommit) != (int)(submission / SubmissionsPerCommit); + if (commitFollows && draw % 6 == 5) + { + labelWrites++; + var constants = labelWrites % 200 == 0; + var address = constants ? objectConstants + 0x3C : labels + (ulong)(labelWrites % 4096) * 4; + pm4!.Packet(ScenePm4.OpWriteData, [1u << 8, (uint)address, (uint)(address >> 32), constants ? 0u : (uint)labelWrites]); + } + } + + return (streams, written, churn); + } + var phases = Enum.GetValues().Where(phase => phase != RenderPhaseProfile.Phase.Count).ToArray(); var profiling = RenderPhaseProfile.Enabled; var results = new List(); ulong submissionId = 1000; foreach (var variation in Enum.GetValues().Where(variation => only is null || variation.ToString() == only)) { - var words = variation == Variation.Draws ? DrawStream() : DispatchStream(); - var items = variation == Variation.Draws ? drawCount : dispatchCount; - var streamAddress = rig.Memory.Upload(words, 256); + var game = variation == Variation.GameShaped ? GameStreams() : default; + var words = variation switch + { + Variation.Draws => DrawStream(), + Variation.Dispatches => DispatchStream(), + _ => [], + }; + var items = variation switch + { + Variation.Draws => drawCount, + Variation.Dispatches => dispatchCount, + _ => gameDrawCount, + }; + var streamAddress = words.Length != 0 ? rig.Memory.Upload(words, 256) : 0; + var gameStreams = game.Streams?.Select(stream => (Address: rig.Memory.Upload(stream, 256), Length: (uint)stream.Length)).ToArray(); var wall = new List(); var cpu = new List(); var phaseTotals = new Dictionary(); @@ -427,13 +599,31 @@ uint[] DispatchStream() if (round == warm) _ = PrefetchCounters.Invoke(rig.Host, null); RenderPasses.SetValue(rig.Host, 0L); var before = profiling ? phases.Select(phase => PhaseTicks(phase)).ToArray() : null; - rig.Host.CommandStream.EnqueueGraphics(streamAddress, (uint)words.Length, ++submissionId, null); + if (gameStreams is null) rig.Host.CommandStream.EnqueueGraphics(streamAddress, (uint)words.Length, ++submissionId, null); var allocatedBefore = GC.GetAllocatedBytesForCurrentThread(); var allBefore = GC.GetTotalAllocatedBytes(precise: false); var collectionsBefore = GC.CollectionCount(0); var cpuStarted = ThreadCpuNanoseconds(); var started = Stopwatch.GetTimestamp(); - rig.RecordPending(); + if (gameStreams is null) + { + rig.RecordPending(); + } + else + { + for (var index = 0; index < gameStreams.Length; index++) + { + rig.Host.CommandStream.EnqueueGraphics(gameStreams[index].Address, gameStreams[index].Length, ++submissionId, null); + rig.RecordPending(); + if ((int)((index + 1) / SubmissionsPerCommit) != (int)(index / SubmissionsPerCommit)) rig.Host.FlushCommandBuffer(); + if (index % 3 == 2) + { + var churn = game.Churn[index % ChurnTextures]; + ((SharpEmu.HLE.GpuMemory.IGuestImageStore)rig.Host.ImageCache).Unregister(churn, 0x10000); + } + } + } + var elapsed = Stopwatch.GetTimestamp() - started; var cpuElapsed = ThreadCpuNanoseconds() - cpuStarted; var roundAllocated = GC.GetAllocatedBytesForCurrentThread() - allocatedBefore; @@ -466,11 +656,12 @@ void Fold(ulong address, int count) foreach (var word in rig.Read(address, count)) checksum = (checksum ^ word) * 0x100000001B3UL; } - if (variation == Variation.Draws) + if (variation != Variation.Dispatches) { foreach (var set in targets) foreach (var target in set) Fold(target, (int)(SceneDraws.LinearPitchBytes(TargetSize, 16) / 4 * TargetSize)); + foreach (var buffer in game.Written ?? []) Fold(buffer, (int)(StorageEdge * StorageEdge)); } else { @@ -480,7 +671,7 @@ void Fold(ulong address, int count) wall.Sort(); cpu.Sort(); - var unit = variation == Variation.Draws ? "draw" : "dispatch"; + var unit = variation == Variation.Dispatches ? "dispatch" : "draw"; Output.WriteLine($"{variation}: wall median {wall[wall.Count / 2]:F2} us/{unit}, p25 {wall[wall.Count / 4]:F2}; " + $"thread cpu median {cpu[cpu.Count / 2]:F2}, p25 {cpu[cpu.Count / 4]:F2}; {allocated / (double)(rounds * items):F0} B/{unit} (all threads {allAllocated / (double)(rounds * items):F0}), " + $"gen0 {collections}; checksum {checksum:X16}"); From 6dcd381271edf7300aa4d0c9d0e6c8c25d174225 Mon Sep 17 00:00:00 2001 From: kuba Date: Sun, 15 Nov 2026 09:53:50 +0000 Subject: [PATCH 051/178] [Metal] Read-binding memo: make only the table in use (each is ~7 MiB per host) --- .../V2/MetalRenderHost.ReadBindingMemo.cs | 35 +++++++++++-------- .../MetalRenderHost.ReadBindingMemoRanges.cs | 10 +++--- 2 files changed, 25 insertions(+), 20 deletions(-) diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.ReadBindingMemo.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.ReadBindingMemo.cs index 084b17fb2..8dad734bd 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.ReadBindingMemo.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.ReadBindingMemo.cs @@ -52,11 +52,14 @@ internal sealed partial class MetalRenderHost internal bool ReadBindingMemoRanges { get; set; } = Environment.GetEnvironmentVariable("SHARPEMU_METAL_V2_READ_BINDING_MEMO_RANGES") != "0"; - private readonly MetalReadBindingMemo _readBindingMemo = new(); - private readonly MetalReadBindingMemoV2 _readBindingMemoV2 = new(); + // Each table is about 7 MiB at the default 16384 sets: only the one in use is made. + private MetalReadBindingMemo? _readBindingMemoV1; + private MetalReadBindingMemoV2? _readBindingMemoV2; + + private MetalReadBindingMemo ReadBindingMemoV1 => _readBindingMemoV1 ??= new(); /// The v2 memo and its counters (tests). - internal MetalReadBindingMemoV2 ReadBindingMemoV2 => _readBindingMemoV2; + internal MetalReadBindingMemoV2 ReadBindingMemoV2 => _readBindingMemoV2 ??= new(); /// The held label copy class the last binding touched, -1 for none (tests). internal int LabelTouchClass => _labelTouchClass; @@ -65,8 +68,10 @@ internal sealed partial class MetalRenderHost private int _readBindingHitIndex = -1; internal (long Hits, long Misses, long Stores, long Verified) ReadBindingMemoCounts => - (_readBindingMemo.Hits + _readBindingMemoV2.Hits, _readBindingMemo.Misses + _readBindingMemoV2.Misses, - _readBindingMemo.Stores + _readBindingMemoV2.Stores, _readBindingMemo.Verified + _readBindingMemoV2.Verified); + ((_readBindingMemoV1?.Hits ?? 0) + (_readBindingMemoV2?.Hits ?? 0), + (_readBindingMemoV1?.Misses ?? 0) + (_readBindingMemoV2?.Misses ?? 0), + (_readBindingMemoV1?.Stores ?? 0) + (_readBindingMemoV2?.Stores ?? 0), + (_readBindingMemoV1?.Verified ?? 0) + (_readBindingMemoV2?.Verified ?? 0)); // Nothing that reports bindings is on. private bool ReadBindingTracesOff => @@ -84,7 +89,7 @@ internal sealed partial class MetalRenderHost // Counts the first reason ReadBindingMemoApplies (or the range's mapping) refused a lookup. private void NoteReadBindingRefusal(bool unmapped) { - var memo = _readBindingMemo; + var memo = ReadBindingMemoV1; memo.Misses++; if (!ReadBindingTracesOff) { @@ -148,21 +153,21 @@ private bool TryReadBindingMemo(ulong address, ulong size, bool computeStage, ou return false; } - if (!_readBindingMemo.TryGet(address, size, computeStage, alias, ReadBindingStamp(), out range) || + if (!ReadBindingMemoV1.TryGet(address, size, computeStage, alias, ReadBindingStamp(), out range) || !_guestMemory.InPlaceAnswerStands(alias, size)) { if (range.IsValid) { // The entry matched; the window under it no longer stands. - _readBindingMemo.RefusedWindow++; + ReadBindingMemoV1.RefusedWindow++; } - _readBindingMemo.Misses++; + ReadBindingMemoV1.Misses++; range = default; return false; } - _readBindingMemo.Hits++; + ReadBindingMemoV1.Hits++; MetalGpuReferenceCensus.Mark(address, size); return true; } @@ -191,11 +196,11 @@ private void StoreReadBinding( if (_readBindingRefusedPending) { - _readBindingMemo.StoreAfterRefusal++; + ReadBindingMemoV1.StoreAfterRefusal++; _readBindingRefusedPending = false; } - _readBindingMemo.Store(address, size, computeStage, inPlaceAlias, before, range); + ReadBindingMemoV1.Store(address, size, computeStage, inPlaceAlias, before, range); } // =verify: the full chain behind a hit, which must give the same range and find no image to flush; behind a v2 @@ -228,11 +233,11 @@ private void VerifyReadBinding(ulong address, ulong size, bool computeStage, Met $"size=0x{size:X} compute={computeStage} before={before} after={after}."); } - _readBindingMemoV2.Verified++; + ReadBindingMemoV2.Verified++; return; } - _readBindingMemo.Verified++; + ReadBindingMemoV1.Verified++; } // ---- The shape of the stage bindings (the PERF line's bind_shape): ---- @@ -307,7 +312,7 @@ private void NoteSnapshotRef(int kind, int array, object reference) private string TakeReadBindingCounters() { - var memo = ReadBindingMemoRanges ? _readBindingMemoV2.TakeCounters() : _readBindingMemo.TakeCounters(); + var memo = ReadBindingMemoRanges ? ReadBindingMemoV2.TakeCounters() : ReadBindingMemoV1.TakeCounters(); var text = $"read_binding_memo=({memo}) bind_shape=(binds={_bindCalls} " + $"image_set_moves={_bindImageSetMoves} binding_epoch_moves={_bindBindingEpochMoves} " + $"snapshot_repeats=[images={_snapshotRefRepeats[0]},samplers={_snapshotRefRepeats[1]},buffers={_snapshotRefRepeats[2]}]/{_snapshotRefChecks} " + diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.ReadBindingMemoRanges.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.ReadBindingMemoRanges.cs index 3a2713bef..4aa0e20b7 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.ReadBindingMemoRanges.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.ReadBindingMemoRanges.cs @@ -32,14 +32,14 @@ internal sealed partial class MetalRenderHost { private bool MissReadBinding(ref long cause) { - _readBindingMemoV2.Misses++; + ReadBindingMemoV2.Misses++; cause++; return false; } private bool TryReadBindingMemoRanges(ulong address, ulong size, bool computeStage, out MetalGuestRange range) { - var memo = _readBindingMemoV2; + var memo = ReadBindingMemoV2; range = default; if (!ReadBindingTracesOff) { @@ -170,7 +170,7 @@ private void StoreReadBindingRanges( ulong address, ulong size, bool computeStage, in MetalReadBindingMemo.Stamp before, bool flushFoundImage, ulong inPlaceAlias, MetalWindowPartition.Window? window, in MetalGuestRange range) { - var memo = _readBindingMemoV2; + var memo = ReadBindingMemoV2; if (!ReadBindingTracesOff) { return; @@ -241,7 +241,7 @@ private void StoreReadBindingRanges( private void VerifyReadBindingHitClaims(ulong address, ulong size, bool computeStage, in MetalGuestRange memo) { var index = _readBindingHitIndex; - var entry = index >= 0 ? _readBindingMemoV2.At(index) : default; + var entry = index >= 0 ? ReadBindingMemoV2.At(index) : default; if (entry.Window is not { } window || entry.Address != address || entry.Size != size) { throw Fatal( @@ -256,7 +256,7 @@ private void VerifyReadBindingHitClaims(ulong address, ulong size, bool computeS } // The images it answered by: none owns a page, or exactly the images it holds are over the range. - var side = _readBindingMemoV2.SideAt(index); + var side = ReadBindingMemoV2.SideAt(index); var mayOwn = _imageCache.MayOwn(address, size); _imageCache.ListOverlapping(address, size, out var first, out var second, out var count, out _); var holds = entry.Tier switch From 10edea540609d909f3a957fa4535adb5a2223e0f Mon Sep 17 00:00:00 2001 From: kuba Date: Sun, 15 Nov 2026 10:15:13 +0000 Subject: [PATCH 052/178] [GPU] Resolve thread: a kept fast snapshot revalidates with its own draw's inputs, FinishJob wakes only waiters, no clock read per draw FastOrigin held the ResourceRuntimeInputs that ShaderProgramCache refills for every lookup, so RevalidateFast evaluated a kept snapshot with the user data and shader base of whatever stage or draw was materialized last (for a kept pixel stage, the vertex stage's): usually a miss, but it could pass with the kept draw's own words changed. The origin now keeps the draw's user data, shader base and compute state, and revalidation evaluates with a per-thread copy of the readers filled with them. FinishJob pulsed the queue monitor for every job; it now pulses only when a thread waits on it (WaitFor, WaitIdle, WaitFinished, Pause, the worker's gate wait) or the worker is idle in its queue wait. A draw's resolution no longer reads the clock only a dispatch's job keeps. --- .../Gpu/Rendering/ParallelProgramPrefetch.cs | 23 ++++++- .../Resources/ResourceMaterializer.cs | 32 ++++++++- .../Resources/ResourceRuntimeInputs.cs | 22 ++++++ ...arallelProgramPrefetchCallerTests.Wakes.cs | 67 ++++++++++++++++++ .../Resources/FastOriginRevalidationTests.cs | 69 +++++++++++++++++++ 5 files changed, 209 insertions(+), 4 deletions(-) create mode 100644 tests/SharpEmu.Libs.Tests/Gpu/Rendering/ParallelProgramPrefetchCallerTests.Wakes.cs create mode 100644 tests/SharpEmu.ShaderCompiler.Tests/Resources/FastOriginRevalidationTests.cs diff --git a/src/SharpEmu.Libs/Gpu/Rendering/ParallelProgramPrefetch.cs b/src/SharpEmu.Libs/Gpu/Rendering/ParallelProgramPrefetch.cs index 97c4deffa..cc6aad38b 100644 --- a/src/SharpEmu.Libs/Gpu/Rendering/ParallelProgramPrefetch.cs +++ b/src/SharpEmu.Libs/Gpu/Rendering/ParallelProgramPrefetch.cs @@ -217,7 +217,9 @@ public void WaitIdle() { while (_outstanding != 0) { + _waiters++; Monitor.Wait(_lock); + _waiters--; } } } @@ -251,7 +253,9 @@ public void WaitFinished(long count) { while (_finished < count) { + _waiters++; Monitor.Wait(_lock); + _waiters--; } } } @@ -265,7 +269,9 @@ public void Pause() _paused = true; while (_running) { + _waiters++; Monitor.Wait(_lock); + _waiters--; } } } @@ -420,7 +426,9 @@ private void WaitFor(Job job) { while (job.State == 0) { + _waiters++; Monitor.Wait(_lock); + _waiters--; } } } @@ -490,6 +498,10 @@ public long TakeClaimSteals() (Interlocked.Exchange(ref _callerResolves, 0), Interlocked.Exchange(ref _callerResolveTicks, 0) * 1000.0 / System.Diagnostics.Stopwatch.Frequency); + // Threads in a Monitor.Wait on _lock for a finished job, the queue to drain, the worker to stop, or the worker's own gate + // or pause (under _lock). FinishJob wakes only when one waits: a pulse per job was a kernel call per draw for nobody. + private int _waiters; + private void FinishJob(bool worker) { lock (_lock) @@ -498,7 +510,11 @@ private void FinishJob(bool worker) _finished++; _running = false; if (worker) _workerClaimed = false; - Monitor.PulseAll(_lock); + // The worker idle in Run waits for _running to fall after a caller's resolution as well as for jobs. + if (_waiters != 0 || _idleForJobs) + { + Monitor.PulseAll(_lock); + } } } @@ -551,7 +567,9 @@ private void Run() } _waitingOnPause = _paused; + _waiters++; Monitor.Wait(_lock, 50); + _waiters--; _waitingOnPause = false; } @@ -613,11 +631,12 @@ private void ResolveCore(Job job) { _concurrent.BeginConcurrentResolve(); _resolvingJob = job.Index + 1; - var started = System.Diagnostics.Stopwatch.GetTimestamp(); try { if (job.Compute is { } compute) { + // Only a dispatch's job keeps its resolving time (dispatch_saved_ms); a draw's read the clock for nothing. + var started = System.Diagnostics.Stopwatch.GetTimestamp(); job.ComputeResult = _executor.ResolveComputeProgramAhead(job.Banks, compute.DispatchInitiator, compute.GroupsX, compute.GroupsY, compute.GroupsZ, compute.Indirect, out job.ComputeRefusal); job.Assumptions = _concurrent.EndConcurrentResolve(); diff --git a/src/SharpEmu.ShaderCompiler/Resources/ResourceMaterializer.cs b/src/SharpEmu.ShaderCompiler/Resources/ResourceMaterializer.cs index 456e35577..1ce6b6a22 100644 --- a/src/SharpEmu.ShaderCompiler/Resources/ResourceMaterializer.cs +++ b/src/SharpEmu.ShaderCompiler/Resources/ResourceMaterializer.cs @@ -366,7 +366,17 @@ private static int NextSpecializationMemo(SpecializationMemoTable table, ulong h public static string TakeFastReport() => FormattableString.Invariant( $"fast_materializations={_fastMaterializations.Take()} fast_specialization_hits={_fastSpecializationHits.Take()} fast_statistics_hits={_fastStatisticsHits.Take()}"); - private sealed record FastOrigin(ShaderResourcePlan Plan, ResourceRuntimeInputs Inputs); + // The plan a fast snapshot came from and the draw inputs it was evaluated with. The inputs object is refilled for + // every lookup (ShaderProgramCache), so the draw's own user data, shader base and compute state are kept beside it: + // revalidating with whatever the object held last evaluated another stage's or another draw's words. + private sealed record FastOrigin(ShaderResourcePlan Plan, ResourceRuntimeInputs Inputs, IReadOnlyList UserData, ulong ShaderBase, + ComputeSelectorState? ComputeState) + { + public FastOrigin(ShaderResourcePlan plan, ResourceRuntimeInputs inputs) + : this(plan, inputs, inputs.UserData, inputs.ShaderBase, inputs.ComputeState) + { + } + } [ThreadStatic] private static MaterializationTally.Outcome _lastFastOutcome; @@ -394,17 +404,35 @@ private sealed record FastOrigin(ShaderResourcePlan Plan, ResourceRuntimeInputs return false; } + var inputs = TakeRevalidationInputs(origin.Inputs); + inputs.UserData = origin.UserData; + inputs.ShaderBase = origin.ShaderBase; + inputs.ComputeState = origin.ComputeState; var output = TakeOutput(); try { - return EvaluateInto(plan, origin.Inputs, output) && SameAsOutput(plan, snapshot, output); + return EvaluateInto(plan, inputs, output) && SameAsOutput(plan, snapshot, output); } finally { _programOutput = output; + inputs.UserData = []; + _revalidationInputs = inputs; } } + // A copy of an origin's readers for its draw's own values, one per thread and reader set; taken out of its slot while + // in use, like the output (a guest read can revalidate another draw on this thread). + [ThreadStatic] + private static ResourceRuntimeInputs? _revalidationInputs; + + private static ResourceRuntimeInputs TakeRevalidationInputs(ResourceRuntimeInputs readers) + { + var inputs = _revalidationInputs; + _revalidationInputs = null; + return inputs is not null && inputs.SameReaders(readers) ? inputs : readers.CopyReaders(); + } + [ThreadStatic] private static MaterializationProgram.Output? _programOutput; diff --git a/src/SharpEmu.ShaderCompiler/Resources/ResourceRuntimeInputs.cs b/src/SharpEmu.ShaderCompiler/Resources/ResourceRuntimeInputs.cs index d82d1d222..65bbd0d55 100644 --- a/src/SharpEmu.ShaderCompiler/Resources/ResourceRuntimeInputs.cs +++ b/src/SharpEmu.ShaderCompiler/Resources/ResourceRuntimeInputs.cs @@ -42,6 +42,28 @@ public sealed class ResourceRuntimeInputs // materialization reports the table as incompatible. public bool NullsOffClassLoopRecords { get; init; } + // The same readers and settings with no draw values, for a caller that fills them per use. + public ResourceRuntimeInputs CopyReaders() => new() + { + ReadMemory = ReadMemory, + ReadCleanMemory = ReadCleanMemory, + TraceImageCandidate = TraceImageCandidate, + TablePhase = TablePhase, + ReadResidentMemory = ReadResidentMemory, + CompareResidentMemory = CompareResidentMemory, + ReadsClean = ReadsClean, + DataWritePending = DataWritePending, + NullsOffClassLoopRecords = NullsOffClassLoopRecords, + }; + + // Whether a copy of these readers (CopyReaders) reads exactly as other does. + public bool SameReaders(ResourceRuntimeInputs other) => + ReferenceEquals(ReadMemory, other.ReadMemory) && ReferenceEquals(ReadCleanMemory, other.ReadCleanMemory) && + ReferenceEquals(TraceImageCandidate, other.TraceImageCandidate) && ReferenceEquals(TablePhase, other.TablePhase) && + ReferenceEquals(ReadResidentMemory, other.ReadResidentMemory) && ReferenceEquals(CompareResidentMemory, other.CompareResidentMemory) && + ReadsClean == other.ReadsClean && ReferenceEquals(DataWritePending, other.DataWritePending) && + NullsOffClassLoopRecords == other.NullsOffClassLoopRecords; + public ResourceRuntimeInputs WithReader(GuestWordReader? reader) => new() { UserData = UserData, diff --git a/tests/SharpEmu.Libs.Tests/Gpu/Rendering/ParallelProgramPrefetchCallerTests.Wakes.cs b/tests/SharpEmu.Libs.Tests/Gpu/Rendering/ParallelProgramPrefetchCallerTests.Wakes.cs new file mode 100644 index 000000000..7bebce2e8 --- /dev/null +++ b/tests/SharpEmu.Libs.Tests/Gpu/Rendering/ParallelProgramPrefetchCallerTests.Wakes.cs @@ -0,0 +1,67 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using System.Reflection; +using SharpEmu.Libs.Gpu.Rendering; +using Xunit; +using static SharpEmu.Libs.Tests.Gpu.Rendering.RenderExecutorFixtures; + +namespace SharpEmu.Libs.Tests.Gpu.Rendering; + +// FinishJob wakes only registered waiters and the worker idle in its queue wait: none of them may be left asleep. +public sealed partial class ParallelProgramPrefetchCallerTests +{ + private static int Waiters(Fixture f) => + (int)typeof(ParallelProgramPrefetch).GetField("_waiters", BindingFlags.Instance | BindingFlags.NonPublic)!.GetValue(f.Prefetch)!; + + [Fact] + public void TheWorkerIdleBehindACallerResolutionResolvesTheNextJobOnceItFinishes() + { + for (var round = 0; round < 50; round++) + { + using var f = new Fixture(); + var firstBanks = Banks(); var secondBanks = Banks(); + ParallelProgramPrefetch.Job second; + lock (f.QueueLock) + { + var first = f.Prefetch.Submit(firstBanks); + second = f.Prefetch.Submit(secondBanks); + Assert.True(f.Take(firstBanks, first)); + } + + // Nobody waits on the second job: only the caller's FinishJob can wake a worker idle behind it. + Assert.True(SpinWait.SpinUntil(() => second.State != 0, TimeSpan.FromSeconds(10)), "The worker was left asleep."); + f.Idle(); + lock (f.QueueLock) + { + Assert.Equal(0, Waiters(f)); + } + } + } + + [Fact] + public void EveryWaiterWakesWhenTheWorkerFinishesAndNoneIsLeftCounted() + { + using var f = new Fixture(); + var gate = new ManualResetEventSlim(); + var entered = new ManualResetEventSlim(); + f.Pipelines.BeforeGraphicsResolve = _ => + { + entered.Set(); + gate.Wait(TimeSpan.FromSeconds(10)); + }; + var banks = Banks(); + var job = f.Prefetch.Submit(banks); + Assert.True(entered.Wait(TimeSpan.FromSeconds(10))); + var waits = new[] { Task.Run(f.Prefetch.WaitIdle), Task.Run(() => f.Prefetch.WaitFinished(1)), Task.Run(f.Prefetch.Pause) }; + Assert.True(SpinWait.SpinUntil(() => { lock (f.QueueLock) return Waiters(f) == 3; }, TimeSpan.FromSeconds(10))); + gate.Set(); + Assert.True(Task.WaitAll(waits, TimeSpan.FromSeconds(10))); + f.Prefetch.Resume(); + Assert.Equal(1, job.State); + lock (f.QueueLock) + { + Assert.Equal(0, Waiters(f)); + } + } +} diff --git a/tests/SharpEmu.ShaderCompiler.Tests/Resources/FastOriginRevalidationTests.cs b/tests/SharpEmu.ShaderCompiler.Tests/Resources/FastOriginRevalidationTests.cs new file mode 100644 index 000000000..a19b86c9c --- /dev/null +++ b/tests/SharpEmu.ShaderCompiler.Tests/Resources/FastOriginRevalidationTests.cs @@ -0,0 +1,69 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using SharpEmu.ShaderCompiler.Resources; +using Xunit; +using static SharpEmu.ShaderCompiler.Tests.Resources.ResourceTestProgram; + +namespace SharpEmu.ShaderCompiler.Tests.Resources; + +// A fast snapshot is revalidated with its own draw's inputs, never with whatever the shared inputs object held last. +public sealed class FastOriginRevalidationTests +{ + private static ShaderResourcePlan PointerPlan() + { + // s[0:1] points at a V# the program loads into s[4:7] and reads through. + var plan = ShaderResourcePlan.Extract(Program(ScalarLoad(0, 0, 4, 4), BufferLoad(8, 4), EndProgram(16)), ShaderStage.Compute, Hash, 0, 4); + Assert.True(ResourceMaterializer.CanMaterializeFast(plan)); + return plan; + } + + [Fact] + public void AKeptSnapshotIsStaleWhenItsOwnDescriptorChangedThoughTheLastDrawsAreEqual() + { + var plan = PointerPlan(); + var memory = new TestWordMemory { Base = 0x1000, Words = new uint[16] }; + uint[] descriptor = [0x8000, 0x10 << 16, 64, 0x24FAC]; + descriptor.CopyTo(memory.Words, 0); + descriptor.CopyTo(memory.Words, 8); + // One inputs object refilled per lookup, as ShaderProgramCache does. + var inputs = new ResourceRuntimeInputs { ReadMemory = memory.Read }; + inputs.UserData = new uint[] { 0x1000, 0, 0, 0 }; + var kept = new ResourceSnapshot(); + var specialization = new ResourceSpecialization(); + Assert.True(ResourceMaterializer.MaterializeFast(plan, inputs, ref kept, ref specialization, out _)); + + // Another draw materialized last, through a pointer to an equal V#. + inputs.UserData = new uint[] { 0x1020, 0, 0, 0 }; + var other = new ResourceSnapshot(); + Assert.True(ResourceMaterializer.MaterializeFast(plan, inputs, ref other, ref specialization, out _)); + Assert.True(ResourceMaterializer.RevalidateFast(kept)); + + // The kept draw's own V# changes; the other draw's does not. + memory.Words[0] = 0x9000; + Assert.False(ResourceMaterializer.RevalidateFast(kept)); + Assert.True(ResourceMaterializer.RevalidateFast(other)); + } + + [Fact] + public void AKeptSnapshotIsCurrentWhenOnlyTheLastDrawsDescriptorChanged() + { + var plan = PointerPlan(); + var memory = new TestWordMemory { Base = 0x1000, Words = new uint[16] }; + uint[] descriptor = [0x8000, 0x10 << 16, 64, 0x24FAC]; + descriptor.CopyTo(memory.Words, 0); + descriptor.CopyTo(memory.Words, 8); + var inputs = new ResourceRuntimeInputs { ReadMemory = memory.Read }; + inputs.UserData = new uint[] { 0x1000, 0, 0, 0 }; + var kept = new ResourceSnapshot(); + var specialization = new ResourceSpecialization(); + Assert.True(ResourceMaterializer.MaterializeFast(plan, inputs, ref kept, ref specialization, out _)); + inputs.UserData = new uint[] { 0x1020, 0, 0, 0 }; + var other = new ResourceSnapshot(); + Assert.True(ResourceMaterializer.MaterializeFast(plan, inputs, ref other, ref specialization, out _)); + + memory.Words[8] = 0x9000; + Assert.True(ResourceMaterializer.RevalidateFast(kept)); + Assert.False(ResourceMaterializer.RevalidateFast(other)); + } +} From 01c8fdc9db3ede141b541bb1e5550bfe2207a3ba Mon Sep 17 00:00:00 2001 From: kuba Date: Sun, 15 Nov 2026 10:16:16 +0000 Subject: [PATCH 053/178] [GPU] Resolve thread counters: unresolved takes by cause, idle and gate time, idle wakes, bytes per job, resolver CPU prefetch=[...] gains takes_unresolved=(busy,gated,queued) (why a draw's job was not resolved when its draw took it), resolver_jobs, resolver_idle_ms (queue wait), gate_sleep_ms (gate and pause spin and wait), idle_wakes, alloc_b_per_job (the resolving thread's allocations, sampled every 64th job) and resolver_cpu_ms (its thread CPU time from proc_pidinfo, so a bench can report the resolver's cost per draw). --- .../Gpu/Rendering/ParallelProgramPrefetch.cs | 97 ++++++++++++++++++- .../V2/MetalRenderHost.ConcurrentResolve.cs | 2 +- 2 files changed, 93 insertions(+), 6 deletions(-) diff --git a/src/SharpEmu.Libs/Gpu/Rendering/ParallelProgramPrefetch.cs b/src/SharpEmu.Libs/Gpu/Rendering/ParallelProgramPrefetch.cs index cc6aad38b..02704cb09 100644 --- a/src/SharpEmu.Libs/Gpu/Rendering/ParallelProgramPrefetch.cs +++ b/src/SharpEmu.Libs/Gpu/Rendering/ParallelProgramPrefetch.cs @@ -304,6 +304,7 @@ public bool TryTakeGraphics(RegisterBanks banks, in GraphicsProgramInputs inputs // well-prefetched burst is one, and two clock reads per draw were measurable. if (job.State == 0) { + NoteUnresolvedTake(job); var waitStarted = System.Diagnostics.Stopwatch.GetTimestamp(); // Caller work is reported separately, not disguised as a shorter resolver wait. // Keep long queues out of the claim routine's lock/finally frame. @@ -393,6 +394,63 @@ public bool TryTakeCompute(RegisterBanks banks, uint dispatchInitiator, uint gro return true; } + // Why a draw's job was not resolved when its draw took it: still gated on the work before it, the resolving + // thread busy with another job, or queued behind others with its gate open (takes_unresolved). + private long _unresolvedGated, _unresolvedBusy, _unresolvedQueued; + + private void NoteUnresolvedTake(Job job) + { + if (job.Gate > Volatile.Read(ref _executedGate)) Interlocked.Increment(ref _unresolvedGated); + else if (Volatile.Read(ref _running)) Interlocked.Increment(ref _unresolvedBusy); + else Interlocked.Increment(ref _unresolvedQueued); + } + + // The resolving thread's idle time in its queue wait and its wakes from it, its time spinning and sleeping on job + // gates, the bytes it allocated per job (sampled every AllocationSamplePeriod jobs), and its CPU time. + private long _idleTicks, _gateTicks, _idleWakes, _sampledBytes, _sampledJobs, _resolverJobs; + private const int AllocationSamplePeriod = 64; + private ulong _resolverThreadId; + private long _lastResolverCpu = -1; + + public string TakeResolverReport() + { + var culture = System.Globalization.CultureInfo.InvariantCulture; + static double Milliseconds(long ticks) => ticks * 1000.0 / System.Diagnostics.Stopwatch.Frequency; + var sampledJobs = Interlocked.Exchange(ref _sampledJobs, 0); + var sampledBytes = Interlocked.Exchange(ref _sampledBytes, 0); + var cpu = ResolverCpuNanoseconds(); + var lastCpu = Interlocked.Exchange(ref _lastResolverCpu, cpu); + var cpuMs = cpu < 0 || lastCpu < 0 ? -1.0 : (cpu - lastCpu) / 1e6; + return $"takes_unresolved=(busy={Interlocked.Exchange(ref _unresolvedBusy, 0)},gated={Interlocked.Exchange(ref _unresolvedGated, 0)}," + + $"queued={Interlocked.Exchange(ref _unresolvedQueued, 0)}) resolver_jobs={Interlocked.Exchange(ref _resolverJobs, 0)} " + + $"resolver_idle_ms={Milliseconds(Interlocked.Exchange(ref _idleTicks, 0)).ToString("F1", culture)} " + + $"gate_sleep_ms={Milliseconds(Interlocked.Exchange(ref _gateTicks, 0)).ToString("F1", culture)} idle_wakes={Interlocked.Exchange(ref _idleWakes, 0)} " + + $"alloc_b_per_job={(sampledJobs == 0 ? 0 : sampledBytes / (double)sampledJobs).ToString("F0", culture)} " + + $"resolver_cpu_ms={cpuMs.ToString("F1", culture)}"; + } + + // The resolving thread's CPU time (user and system), or -1 where it cannot be read. + private long ResolverCpuNanoseconds() + { + var thread = Volatile.Read(ref _resolverThreadId); + if (thread == 0 || !OperatingSystem.IsMacOS()) + return -1; + Span info = stackalloc ulong[ThreadInfoBytes / sizeof(ulong)]; + return ProcessThreadInfo(Environment.ProcessId, ThreadId64Info, thread, ref info[0], ThreadInfoBytes) == ThreadInfoBytes + ? (long)(info[0] + info[1]) + : -1; + } + + // PROC_PIDTHREADID64INFO fills a proc_threadinfo: user and system time first, 112 bytes in all. + private const int ThreadId64Info = 15; + private const int ThreadInfoBytes = 112; + + [System.Runtime.InteropServices.DllImport("libc", EntryPoint = "pthread_threadid_np")] + private static extern int PthreadThreadId(nint thread, out ulong id); + + [System.Runtime.InteropServices.DllImport("libc", EntryPoint = "proc_pidinfo")] + private static extern int ProcessThreadInfo(int pid, int flavor, ulong argument, ref ulong buffer, int size); + // The job is finished with: nothing reads its assumptions again. private void ReleaseAssumptions(Job job) { @@ -521,16 +579,28 @@ private void FinishJob(bool worker) private void Run() { GpuFatal.ThrowOnFatal = true; + if (OperatingSystem.IsMacOS() && PthreadThreadId(0, out var threadId) == 0) + { + Volatile.Write(ref _resolverThreadId, threadId); + } + while (true) { Job job; lock (_lock) { - while ((_queue.Count == 0 || _running) && !_stopping) + if ((_queue.Count == 0 || _running) && !_stopping) { - _idleForJobs = true; - Monitor.Wait(_lock); - _idleForJobs = false; + var idleStarted = System.Diagnostics.Stopwatch.GetTimestamp(); + while ((_queue.Count == 0 || _running) && !_stopping) + { + _idleForJobs = true; + Monitor.Wait(_lock); + _idleForJobs = false; + _idleWakes++; + } + + Interlocked.Add(ref _idleTicks, System.Diagnostics.Stopwatch.GetTimestamp() - idleStarted); } if (_stopping) @@ -540,6 +610,7 @@ private void Run() job = _queue.Peek(); _workerClaimed = true; + var gateStarted = job.Gate > Volatile.Read(ref _executedGate) || _paused ? System.Diagnostics.Stopwatch.GetTimestamp() : 0; if (job.Gate > Volatile.Read(ref _executedGate)) { // The gate usually opens within a few items: spin before sleeping. @@ -574,6 +645,11 @@ private void Run() } Volatile.Write(ref _sleepingOnGate, long.MaxValue); + if (gateStarted != 0) + { + Interlocked.Add(ref _gateTicks, System.Diagnostics.Stopwatch.GetTimestamp() - gateStarted); + } + if (_stopping) { return; @@ -590,11 +666,22 @@ private void Run() _running = true; } + var sampled = (++_resolverJobs & (AllocationSamplePeriod - 1)) == 0; + var allocatedBefore = sampled ? GC.GetAllocatedBytesForCurrentThread() : 0; try { Resolve(job); } - finally { FinishJob(worker: true); } + finally + { + if (sampled) + { + Interlocked.Add(ref _sampledBytes, GC.GetAllocatedBytesForCurrentThread() - allocatedBefore); + Interlocked.Increment(ref _sampledJobs); + } + + FinishJob(worker: true); + } } } diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.ConcurrentResolve.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.ConcurrentResolve.cs index 727653fcc..36a5f40d3 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.ConcurrentResolve.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.ConcurrentResolve.cs @@ -168,7 +168,7 @@ private string FormatPrefetchCounters() $"dispatch_saved_ms={computeSavedMs.ToString("F1", culture)}"; return $"resolved={resolved} abandoned={abandoned} abandoned_by=({TakeAbandonCauses()}) taken={taken} refused={refused} drains={drains} drained={drained} deferred_barriers={deferredBarriers} operand_reads_kept={operandReadsKept} " + $"wait_ms={waitMs.ToString("F1", culture)} resolve_ms={prefetch.TakeResolveMilliseconds().ToString("F1", culture)} " + - $"caller_jobs={callerResolves} caller_ms={callerMs.ToString("F1", culture)} claim_steals={prefetch.TakeClaimSteals()}{dispatches}{FormatPacketCounters()} {own} {TakeOwnerTestCounters()}{TakeDrainCallers()}"; + $"caller_jobs={callerResolves} caller_ms={callerMs.ToString("F1", culture)} claim_steals={prefetch.TakeClaimSteals()} {prefetch.TakeResolverReport()}{dispatches}{FormatPacketCounters()} {own} {TakeOwnerTestCounters()}{TakeDrainCallers()}"; } private static string FormatProviderRefusals(long[] refused) => From f6a7bb1e2368fd6edc51b2743d57e7942ed3a572 Mon Sep 17 00:00:00 2001 From: kuba Date: Sun, 15 Nov 2026 10:19:57 +0000 Subject: [PATCH 054/178] [GPU] Resolve memo, shadow: key every draw's resolution inputs and count the draws it would find GraphicsResolveMemo keys a draw by everything its graphics resolution reads from the registers and the draw: the flags and export mapping, the vertex and pixel stage registers, the context registers the resolver, the viewport transform and the target resolution read (the blend state as PixelOutputBlend's bits), the whole shader interface, and each stage's user data words last. 2-way sets of SHARPEMU_RESOLVE_MEMO_ENTRIES (16384) entries, the older way replaced. For now it only counts: [PERF][KEPT_PROGRAMS] gains resolve_memo=(would_hit, key_miss=(new, user_data_only, regs_only), uncacheable_by, evictions, entries); the kept path runs as before. SHARPEMU_RESOLVE_MEMO=0 turns it off. The allocation test's bound grows by the 48 bytes each fast snapshot's origin now carries (the previous commit). --- .../Gpu/Pipelines/GraphicsResolveMemo.cs | 399 ++++++++++++++++++ .../Gpu/Pipelines/ShaderPipelineCache.cs | 55 ++- .../Pipelines/GraphicsResolveMemoKeyTests.cs | 98 +++++ .../ShaderPipelineCacheAllocationTests.cs | 5 +- 4 files changed, 554 insertions(+), 3 deletions(-) create mode 100644 src/SharpEmu.Libs/Gpu/Pipelines/GraphicsResolveMemo.cs create mode 100644 tests/SharpEmu.Libs.Tests/Gpu/Pipelines/GraphicsResolveMemoKeyTests.cs diff --git a/src/SharpEmu.Libs/Gpu/Pipelines/GraphicsResolveMemo.cs b/src/SharpEmu.Libs/Gpu/Pipelines/GraphicsResolveMemo.cs new file mode 100644 index 000000000..02b65f958 --- /dev/null +++ b/src/SharpEmu.Libs/Gpu/Pipelines/GraphicsResolveMemo.cs @@ -0,0 +1,399 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using System.IO.Hashing; +using System.Runtime.InteropServices; +using SharpEmu.HLE.Diagnostics; +using SharpEmu.Libs.Gpu.GpuCommands.Registers; +using SharpEmu.Libs.Gpu.Images; +using SharpEmu.Libs.Gpu.Rendering; + +namespace SharpEmu.Libs.Gpu.Pipelines; + +// SHARPEMU_RESOLVE_MEMO: on (default), 0 (the kept programs of the last draw only, as before), shadow (counts what the +// memo would hit and keeps the kept path), verify (every hit also resolves in full and stops on any difference). +internal enum ResolveMemoMode +{ + Off, + Shadow, + On, + Verify, +} + +// Why a draw found no usable memo entry; each falls through to the full resolution. +internal enum ResolveMemoMiss +{ + // No entry has the draw's key. + New, + // The program cache replaced or refused an entry since (ShaderProgramCache.ContentEpoch), or the vertex table + // metadata was dropped. + Epoch, + // The code address names another header record. + Header, + // The code's identity changed. + Identity, + // The vertex attribute or buffer table words changed. + Tables, + // The pixel input semantics changed. + Semantics, + // A stage's descriptor words no longer evaluate to its snapshot. + Words, + // Device data loads were learned (DeviceDataLoads.Generation). + Generation, + Count, +} + +// Why a draw's resolution is never kept in the memo. +internal enum ResolveMemoUncacheable +{ + Frontend, + Mesh, + Tessellation, + Calls, + Unavailable, + Tables, + Trace, + // A snapshot with no origin to revalidate it from. + Origin, + // A user data count over the bank (the full resolution stops on it). + Key, + Count, +} + +// The graphics programs of draws already resolved, keyed by everything their resolution reads from the registers and +// the draw (ResolveKey), many per frame: a draw whose key matches an entry takes its programs once every guest read the +// full resolution makes still gives the same answer (ShaderPipelineCache.TryTakeResolveMemo). Used under the pipeline +// cache's _resolveGate only. +internal sealed class GraphicsResolveMemo +{ + internal static readonly ResolveMemoMode DefaultMode = ParseMode(Environment.GetEnvironmentVariable("SHARPEMU_RESOLVE_MEMO")); + + // SHARPEMU_RESOLVE_MEMO_ENTRIES: at least twice a frame's draws (Demon's Souls ~7300). + internal static readonly int DefaultCapacity = + int.TryParse(Environment.GetEnvironmentVariable("SHARPEMU_RESOLVE_MEMO_ENTRIES"), out var entries) && entries >= 2 ? entries : 16384; + + // The memo only counts what it would hit for now (shadow); 0 turns that off too. + internal static ResolveMemoMode ParseMode(string? value) => value?.Trim().ToLowerInvariant() switch + { + "0" or "off" => ResolveMemoMode.Off, + _ => ResolveMemoMode.Shadow, + }; + + // One way of a set: the key it was resolved under and what the hit re-checks. + internal sealed class Entry + { + public required byte[] Key; + public required ulong Hash; + public long Used; + public GraphicsPrograms? Programs; + public RegisteredShader? VertexShader; + public ulong VertexAddress; + public ulong VertexHash; + public RegisteredShader? PixelShader; + public ulong PixelAddress; + public ulong PixelHash; + public VertexTableWords? TableWords; + public ulong AttributeTable; + public ulong BufferTable; + public uint PixelSemanticCount; + public uint PixelCustomMask; + public long ContentEpoch; + public int DeviceDataGeneration; + public long TablesGeneration; + // GraphicsProgramsComparer.Fingerprint at insertion (verify: nothing wrote the shared result since). + public ulong Fingerprint; + } + + private const int MaxKeyBytes = 4096; + private readonly byte[] _key = new byte[MaxKeyBytes]; + private int _keyLength; + private int _userDataStart; + private readonly Entry?[] _ways; + private readonly int _setMask; + private long _clock; + private int _count; + // The register and user-data halves of the keys stored, to tell a miss's cause (key_miss); bounded. + private readonly HashSet _registerHalves = []; + private readonly HashSet _userDataHalves = []; + + public GraphicsResolveMemo(ResolveMemoMode mode, int capacity) + { + Mode = mode; + var sets = 1; + while (sets * 2 < capacity) sets <<= 1; + _setMask = sets - 1; + _ways = new Entry?[sets * 2]; + } + + public ResolveMemoMode Mode { get; } + + public int Count => _count; + + public ulong Hash { get; private set; } + + public ReadOnlySpan Key => _key.AsSpan(0, _keyLength); + + // The draw's key: every register and draw input the resolution reads, the user data words last. False when the user + // data count is over the bank (the full resolution stops there). + public bool Fill(RegisterBanks banks, ReadOnlySpan targetExportMapping, in KeptGraphicsFlags flags, + PixelOutputBlendBits blendBits) + { + var key = _key.AsSpan(); + var at = 0; + var vertex = banks.Shader.Vertex; + var pixel = banks.Shader.Pixel; + var context = banks.Context; + var shaderInterface = context.ShaderInterface; + + Put(key, ref at, flags); + Put(key, ref at, targetExportMapping.Length); + PutSpan(key, ref at, targetExportMapping); + + // The vertex stage: every plain register (the hull, legacy and export user scalars are not read). + Put(key, ref at, vertex.ExportAddress); + Put(key, ref at, vertex.LocalAddress); + Put(key, ref at, vertex.HullAddress); + Put(key, ref at, vertex.HullUserDataAddress); + Put(key, ref at, vertex.HullResource1); + Put(key, ref at, vertex.HullResource2); + Put(key, ref at, vertex.GeometryAddress); + Put(key, ref at, vertex.GeometryUserDataAddress); + Put(key, ref at, vertex.GeometryResource1); + Put(key, ref at, vertex.GeometryResource2); + Put(key, ref at, vertex.ExportResource1); + Put(key, ref at, vertex.ExportResource2); + Put(key, ref at, vertex.LegacyVertexAddress); + Put(key, ref at, vertex.LegacyVertexResource1); + Put(key, ref at, vertex.LegacyVertexResource2); + Put(key, ref at, vertex.GeometryUserScalars.Count); + if (flags.PixelActive) + { + Put(key, ref at, pixel.Address); + Put(key, ref at, pixel.UserDataAddress); + Put(key, ref at, pixel.AuxiliaryTableAddress); + Put(key, ref at, pixel.Resource1); + Put(key, ref at, pixel.Resource2); + Put(key, ref at, pixel.UserScalars.Count); + } + + // The context registers the resolution reads (ShaderPipelineCache, HostViewportTransform, ColorTargetResolver, + // PixelExportRouting): the blend state as the bits it resolves from (PixelOutputBlend), the viewport's transform. + Put(key, ref at, context.ShaderStages); + Put(key, ref at, context.RenderTargetMask); + PutSpan(key, ref at, context.ColorTargets.AsSpan()); + Put(key, ref at, blendBits.Value); + Put(key, ref at, context.Clip); + Put(key, ref at, context.DepthRenderOverride); + Put(key, ref at, context.DepthTarget.ZInfo); + Put(key, ref at, context.ScreenViewport.TransformControl); + ref readonly var viewport = ref context.ScreenViewport.Primary; + Put(key, ref at, viewport.MinDepth); + Put(key, ref at, viewport.MaxDepth); + Put(key, ref at, viewport.XScale); + Put(key, ref at, viewport.XOffset); + Put(key, ref at, viewport.YScale); + Put(key, ref at, viewport.YOffset); + Put(key, ref at, viewport.ZScale); + Put(key, ref at, viewport.ZOffset); + PutSpan(key, ref at, context.UserClipPlanes.AsSpan()); + + // The whole shader interface. + Put(key, ref at, shaderInterface.VertexOutputConfiguration); + Put(key, ref at, shaderInterface.PositionExportFormat); + Put(key, ref at, shaderInterface.VertexOutputControl); + PutSpan(key, ref at, shaderInterface.PixelInterpolatorSettings.AsSpan()); + Put(key, ref at, shaderInterface.PixelInterpolatorWritten); + Put(key, ref at, shaderInterface.IndexExportFormat); + Put(key, ref at, shaderInterface.PrimitiveShaderSubgroupControl); + Put(key, ref at, shaderInterface.GeometryInstanceCount); + Put(key, ref at, shaderInterface.GeometryOnChipControl); + Put(key, ref at, shaderInterface.MaxTessellationLevel); + Put(key, ref at, shaderInterface.MinTessellationLevel); + Put(key, ref at, shaderInterface.MaxOutputPerSubgroup); + Put(key, ref at, shaderInterface.ExportRingItemSize); + Put(key, ref at, shaderInterface.GeometryMaxVerticesOut); + Put(key, ref at, shaderInterface.GeometryOutputPrimitiveType); + Put(key, ref at, shaderInterface.PrimitiveIdEnable); + Put(key, ref at, shaderInterface.VertexReuseOff); + Put(key, ref at, shaderInterface.TessellationDistribution); + Put(key, ref at, shaderInterface.LocalHullConfiguration); + Put(key, ref at, shaderInterface.TessellationFactorParameter); + Put(key, ref at, shaderInterface.DepthExportFormat); + PutSpan(key, ref at, shaderInterface.TargetOutputModes.AsSpan()); + Put(key, ref at, shaderInterface.PixelInputEnable); + Put(key, ref at, shaderInterface.PixelInputAddress); + Put(key, ref at, shaderInterface.PixelInputControl); + Put(key, ref at, shaderInterface.BarycentricControl); + Put(key, ref at, shaderInterface.ColorShaderMask); + Put(key, ref at, shaderInterface.ScanShaderControl); + Put(key, ref at, shaderInterface.DepthShaderControl); + + // The user data words each stage resolves with (ShaderPipelineCache.UserData): its declared count, else the + // registers the guest wrote. + _userDataStart = at; + if (!PutUserData(key, ref at, vertex.GeometryUserScalars, vertex.GeometryResource2.UserScalarCount) || + (flags.PixelActive && !PutUserData(key, ref at, pixel.UserScalars, pixel.Resource2.UserScalarCount))) + { + return false; + } + + _keyLength = at; + Hash = XxHash3.HashToUInt64(key[..at]); + return true; + } + + private static bool PutUserData(Span key, ref int at, UserScalarRegisters registers, uint declared) + { + var count = declared != 0 ? declared : registers.Count; + if (count > UserScalarRegisters.Capacity) + { + return false; + } + + Put(key, ref at, count); + PutSpan(key, ref at, registers.ValueSpan((int)count)); + return true; + } + + private static void Put(Span key, ref int at, in T value) where T : unmanaged + { + MemoryMarshal.Write(key[at..], in value); + at += System.Runtime.CompilerServices.Unsafe.SizeOf(); + } + + private static void PutSpan(Span key, ref int at, ReadOnlySpan values) where T : unmanaged + { + var bytes = MemoryMarshal.AsBytes(values); + bytes.CopyTo(key[at..]); + at += bytes.Length; + } + + // The entry with the filled key, or null. + public Entry? Find() + { + var set = (int)(Hash & (ulong)_setMask) * 2; + var key = Key; + for (var way = set; way < set + 2; way++) + { + if (_ways[way] is { } entry && entry.Hash == Hash && key.SequenceEqual(entry.Key)) + { + entry.Used = ++_clock; + return entry; + } + } + + return null; + } + + // Why the filled key has no entry: only its user data or only its registers differ from a key stored. + public ResolveMemoKeyMiss ClassifyMiss() + { + var key = Key; + var registers = XxHash3.HashToUInt64(key[.._userDataStart]); + var userData = XxHash3.HashToUInt64(key[_userDataStart..]); + return _registerHalves.Contains(registers) ? ResolveMemoKeyMiss.UserDataOnly + : _userDataHalves.Contains(userData) ? ResolveMemoKeyMiss.RegistersOnly + : ResolveMemoKeyMiss.New; + } + + // A new entry for the filled key, in place of the set's older way; the caller fills it. + public Entry Store() + { + var key = Key; + var set = (int)(Hash & (ulong)_setMask) * 2; + var way = set; + for (var candidate = set; candidate < set + 2; candidate++) + { + if (_ways[candidate] is not { } held) + { + way = candidate; + break; + } + + if (held.Hash == Hash && key.SequenceEqual(held.Key)) + { + way = candidate; + break; + } + + if (held.Used < (_ways[way]?.Used ?? long.MinValue)) + { + way = candidate; + } + } + + if (_ways[way] is { } replaced) + { + if (replaced.Hash != Hash || !key.SequenceEqual(replaced.Key)) + { + _evictions.Increment(); + } + } + else + { + _count++; + _entries.Increment(); + } + + if (_registerHalves.Count >= _ways.Length * 2) + { + _registerHalves.Clear(); + _userDataHalves.Clear(); + } + + _registerHalves.Add(XxHash3.HashToUInt64(key[.._userDataStart])); + _userDataHalves.Add(XxHash3.HashToUInt64(key[_userDataStart..])); + var entry = new Entry { Key = key.ToArray(), Hash = Hash, Used = ++_clock }; + _ways[way] = entry; + return entry; + } + + private static readonly ThreadCounter _hits = new(); + private static readonly ThreadCounter _evictions = new(); + private static readonly ThreadCounter _entries = new(); + private static readonly ThreadCounter _verifyChecked = new(); + private static readonly ThreadCounter _shadowWouldHit = new(); + private static readonly ThreadCounter[] _misses = NewCounters((int)ResolveMemoMiss.Count); + private static readonly ThreadCounter[] _keyMisses = NewCounters((int)ResolveMemoKeyMiss.Count); + private static readonly ThreadCounter[] _uncacheable = NewCounters((int)ResolveMemoUncacheable.Count); + private static long _verifyFailed; + + private static ThreadCounter[] NewCounters(int count) => Enumerable.Range(0, count).Select(_ => new ThreadCounter()).ToArray(); + + public static void NoteHit() => _hits.Increment(); + + public static void NoteShadowHit() => _shadowWouldHit.Increment(); + + public static void NoteMiss(ResolveMemoMiss cause) => _misses[(int)cause].Increment(); + + public static void NoteKeyMiss(ResolveMemoKeyMiss cause) => _keyMisses[(int)cause].Increment(); + + public static void NoteUncacheable(ResolveMemoUncacheable cause) => _uncacheable[(int)cause].Increment(); + + public static void NoteVerified() => _verifyChecked.Increment(); + + public static void NoteVerifyFailed() => Interlocked.Increment(ref _verifyFailed); + + private static string Take(ThreadCounter[] counters, params string[] names) => + string.Join(",", names.Select((name, index) => FormattableString.Invariant($"{name}={counters[index].Take()}"))); + + // The resolve_memo=(...) part of [PERF][KEPT_PROGRAMS]; entries counts every live memo. + public static string TakeReport() => FormattableString.Invariant( + $"resolve_memo=(mode={DefaultMode.ToString().ToLowerInvariant()},hits={_hits.Take()},would_hit={_shadowWouldHit.Take()},") + + "miss_by=(" + Take(_misses, "new", "epoch", "header", "identity", "tables", "semantics", "words", "generation") + ")," + + "key_miss=(" + Take(_keyMisses, "new", "user_data_only", "regs_only") + ")," + + "uncacheable_by=(" + Take(_uncacheable, "frontend", "mesh", "tess", "calls", "unavailable", "tables", "trace", "origin", "key") + ")," + + FormattableString.Invariant($"evictions={_evictions.Take()},entries={_entries.Total},verify_checked={_verifyChecked.Take()},") + + FormattableString.Invariant($"verify_failed={Interlocked.Read(ref _verifyFailed)})"); +} + +internal enum ResolveMemoKeyMiss +{ + New, + UserDataOnly, + RegistersOnly, + Count, +} + +// ShaderPipelineCache.PixelOutputBlend of a draw's context: the blend state its resolution reads. +internal readonly record struct PixelOutputBlendBits(uint Value); diff --git a/src/SharpEmu.Libs/Gpu/Pipelines/ShaderPipelineCache.cs b/src/SharpEmu.Libs/Gpu/Pipelines/ShaderPipelineCache.cs index ad794309d..d3561c82a 100644 --- a/src/SharpEmu.Libs/Gpu/Pipelines/ShaderPipelineCache.cs +++ b/src/SharpEmu.Libs/Gpu/Pipelines/ShaderPipelineCache.cs @@ -314,11 +314,13 @@ public GraphicsPrograms GetGraphicsPrograms( banks.Stamp(RegisterStamp.ShaderPrograms), banks.Stamp(RegisterStamp.VertexUserData), banks.Stamp(RegisterStamp.PixelUserData), banks.Stamp(RegisterStamp.ColorTargets, RegisterStamp.ShaderInterface), ShaderHeaderRegistry.Registrations); var flags = new KeptGraphicsFlags(pixelActive, depthBound, depthAspectBound, stencilAspectBound, triangleList, startInstanceUserData); + var shadowMiss = ShadowResolveMemo(banks, targetExportMapping, flags); ClaimKeptPrograms(); var kept = _keptGraphics ??= new KeptGraphicsPrograms(); if (TryKeepGraphicsPrograms(context, kept, stamps, flags, targetExportMapping, out var keptPrograms)) { _graphicsKept.Increment(); + if (shadowMiss) _resolveMemo!.Store(); return keptPrograms; } @@ -328,10 +330,60 @@ public GraphicsPrograms GetGraphicsPrograms( depthAspectBound, stencilAspectBound, triangleList, mesh: null, startInstanceUserData: startInstanceUserData, nativeTessellation: true); KeepGraphicsPrograms(kept, programs, context, stamps, flags, targetExportMapping); + if (shadowMiss) _resolveMemo!.Store(); return programs; } } + // The resolve memo of this cache (GraphicsResolveMemo), or null with it off; SHARPEMU_DRAW_REUSE=0 turns it off too. + private GraphicsResolveMemo? _resolveMemo = DrawReuseDisabled || GraphicsResolveMemo.DefaultMode == ResolveMemoMode.Off + ? null + : new GraphicsResolveMemo(GraphicsResolveMemo.DefaultMode, GraphicsResolveMemo.DefaultCapacity); + + // For tests: the memo's mode on this cache, with a fresh memo. + internal ResolveMemoMode ResolveMemoMode + { + get => _resolveMemo?.Mode ?? ResolveMemoMode.Off; + set + { + lock (_resolveGate) + { + _resolveMemo = value == ResolveMemoMode.Off ? null : new GraphicsResolveMemo(value, GraphicsResolveMemo.DefaultCapacity); + } + } + } + + // Shadow mode: counts whether the memo would have the draw's key; true when it has not and the key is to be stored + // once the draw resolved. + private bool ShadowResolveMemo(RegisterBanks banks, ReadOnlySpan targetExportMapping, in KeptGraphicsFlags flags) + { + if (_resolveMemo is not { Mode: ResolveMemoMode.Shadow } memo) + { + return false; + } + + if (_registry.HasFrontend) + { + GraphicsResolveMemo.NoteUncacheable(ResolveMemoUncacheable.Frontend); + return false; + } + + if (!memo.Fill(banks, targetExportMapping, flags, new PixelOutputBlendBits(PixelOutputBlend(banks.Context)))) + { + GraphicsResolveMemo.NoteUncacheable(ResolveMemoUncacheable.Key); + return false; + } + + if (memo.Find() is not null) + { + GraphicsResolveMemo.NoteShadowHit(); + return false; + } + + GraphicsResolveMemo.NoteKeyMiss(memo.ClassifyMiss()); + return true; + } + // The interface's earlier forms, for callers holding only the four inputs. public GraphicsPrograms GetGraphicsPrograms( RegisterBanks banks, @@ -412,7 +464,8 @@ private void ClaimKeptPrograms() public static string TakeKeptProgramsReport() => FormattableString.Invariant($"[PERF][KEPT_PROGRAMS] graphics_kept={_graphicsKept.Take()} graphics_resolved={_graphicsResolved.Take()} ") + - FormattableString.Invariant($"compute_kept={_computeKept.Take()} compute_rebound={_computeRebound.Take()} compute_resolved={_computeResolved.Take()}"); + FormattableString.Invariant($"compute_kept={_computeKept.Take()} compute_rebound={_computeRebound.Take()} compute_resolved={_computeResolved.Take()} ") + + GraphicsResolveMemo.TakeReport(); // Besides upstream's register stamps, the fork's resolution reads the host viewport transform (dynamic // viewport registers, compared resolved), the depth aspects and triangle-list assembly (per-vertex pixel diff --git a/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/GraphicsResolveMemoKeyTests.cs b/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/GraphicsResolveMemoKeyTests.cs new file mode 100644 index 000000000..439e1f3ee --- /dev/null +++ b/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/GraphicsResolveMemoKeyTests.cs @@ -0,0 +1,98 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using SharpEmu.Libs.Gpu.GpuCommands.Registers; +using SharpEmu.Libs.Gpu.Images; +using SharpEmu.Libs.Gpu.Pipelines; +using Xunit; + +namespace SharpEmu.Libs.Tests.Gpu.Pipelines; + +// The resolve memo's key: equal for equal registers and draw inputs, different for any word the resolution reads, and +// a miss told apart by the half that differs. +public sealed class GraphicsResolveMemoKeyTests +{ + private static readonly KeptGraphicsFlags Flags = new(PixelActive: true, DepthBound: false, DepthAspectBound: false, + StencilAspectBound: false, TriangleList: true, StartInstanceUserData: -1); + + private static RegisterBanks Banks() + { + var banks = new RegisterBanks(static message => new InvalidOperationException(message)); + banks.Shader.Vertex.ExportAddress = 0x1000; + banks.Shader.Pixel.Address = 0x2000; + banks.Shader.Vertex.GeometryUserScalars.Set(0, 0x1234, UserScalarKind.Unknown); + banks.Shader.Pixel.UserScalars.Set(0, 0x5678, UserScalarKind.Unknown); + return banks; + } + + private static bool Fill(GraphicsResolveMemo memo, RegisterBanks banks, KeptGraphicsFlags? flags = null) => + memo.Fill(banks, [ColorComponentMap.Identity], flags ?? Flags, new PixelOutputBlendBits(0)); + + [Fact] + public void EqualBanksFindTheStoredKeyAndAChangedWordDoesNot() + { + var memo = new GraphicsResolveMemo(ResolveMemoMode.Shadow, 64); + var banks = Banks(); + Assert.True(Fill(memo, banks)); + Assert.Null(memo.Find()); + var stored = memo.Store(); + Assert.True(Fill(memo, Banks())); + Assert.Same(stored, memo.Find()); + + banks.Context.ColorTargets[3] = banks.Context.ColorTargets[3] with { Info = 1 }; + Assert.True(Fill(memo, banks)); + Assert.Null(memo.Find()); + Assert.Equal(ResolveMemoKeyMiss.RegistersOnly, memo.ClassifyMiss()); + + Assert.True(Fill(memo, Banks(), Flags with { DepthBound = true })); + Assert.Null(memo.Find()); + } + + [Fact] + public void AUserDataWordOnlyMissIsToldApartAndAnUnreadWordIsNotInTheKey() + { + var memo = new GraphicsResolveMemo(ResolveMemoMode.Shadow, 64); + Assert.True(Fill(memo, Banks())); + memo.Store(); + + var banks = Banks(); + banks.Shader.Pixel.UserScalars.Set(0, 0x9999, UserScalarKind.Unknown); + Assert.True(Fill(memo, banks)); + Assert.Null(memo.Find()); + Assert.Equal(ResolveMemoKeyMiss.UserDataOnly, memo.ClassifyMiss()); + + // A pixel stage the draw does not run is not part of its key. + Assert.True(Fill(memo, Banks(), Flags with { PixelActive = false })); + memo.Store(); + Assert.True(Fill(memo, banks, Flags with { PixelActive = false })); + Assert.NotNull(memo.Find()); + + // A user data count over the bank is refused (the full resolution stops on it). + var over = Banks(); + over.Shader.Vertex.GeometryResource2 = over.Shader.Vertex.GeometryResource2 with { UserScalarCount = 40 }; + Assert.False(Fill(memo, over)); + } + + [Fact] + public void ASetKeepsTwoKeysAndReplacesTheOlder() + { + var memo = new GraphicsResolveMemo(ResolveMemoMode.Shadow, 2); + var keys = Enumerable.Range(0, 3).Select(index => + { + var banks = Banks(); + banks.Shader.Vertex.ExportAddress = 0x1000 + (ulong)index * 0x100; + return banks; + }).ToArray(); + foreach (var banks in keys) + { + Assert.True(Fill(memo, banks)); + memo.Store(); + } + + Assert.Equal(2, memo.Count); + Assert.True(Fill(memo, keys[0])); + Assert.Null(memo.Find()); + Assert.True(Fill(memo, keys[2])); + Assert.NotNull(memo.Find()); + } +} diff --git a/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/ShaderPipelineCacheAllocationTests.cs b/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/ShaderPipelineCacheAllocationTests.cs index 082cee4f3..4ec3e220f 100644 --- a/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/ShaderPipelineCacheAllocationTests.cs +++ b/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/ShaderPipelineCacheAllocationTests.cs @@ -50,8 +50,9 @@ long Draw() // GraphicsPrograms, VertexInputInfo and, with a pixel stage, PixelInputInfo: about 130 bytes each, and 32 more for each // input's stage, whose shader-call fields (ShaderStageResources.CallArguments and the rest) stay null for a draw. // The upstream merge (tessellation, frontend and kept-pipeline fields) grew these to 520 and 880 bytes, and the binding - // packet slot on each stage's resource snapshot (ResourceSnapshot.BindingPacket) to 528 and 896. - Assert.True(perDraw[^1] <= (pixelActive ? 896 : 528), $"bytes={perDraw[^1]}"); + // packet slot on each stage's resource snapshot (ResourceSnapshot.BindingPacket) to 528 and 896, and the draw's own + // user data, shader base and compute state on each fast snapshot's origin (ResourceMaterializer.FastOrigin) to 576 and 992. + Assert.True(perDraw[^1] <= (pixelActive ? 992 : 576), $"bytes={perDraw[^1]}"); var first = cache.GetGraphicsPrograms(banks.Shader.Vertex, banks.Shader.Pixel, banks.Context.ShaderInterface, banks.Context, mappings, pixelActive, depthBound: false, depthAspectBound: false); var second = cache.GetGraphicsPrograms(banks.Shader.Vertex, banks.Shader.Pixel, banks.Context.ShaderInterface, From b3d768d6994975b3bce46fa2ab014630a07144bf Mon Sep 17 00:00:00 2001 From: kuba Date: Sun, 15 Nov 2026 10:20:35 +0000 Subject: [PATCH 055/178] [Shader] ResourceMaterializer.Revalidate with explicit inputs; RevalidateFast evaluates through it Revalidate(plan, snapshot, inputs) evaluates the plan's materialization program with a draw's own user data, shader base and readers and compares the words with the snapshot (EvaluateInto + SameAsOutput); a reader that splits the table phase is refused (LastRevalidateRefused). RevalidateFast fills a per-thread copy of the origin's readers with the origin's draw values and calls it. --- .../Resources/ResourceMaterializer.cs | 29 +++++++++++++++---- .../Resources/FastOriginRevalidationTests.cs | 26 +++++++++++++++++ 2 files changed, 50 insertions(+), 5 deletions(-) diff --git a/src/SharpEmu.ShaderCompiler/Resources/ResourceMaterializer.cs b/src/SharpEmu.ShaderCompiler/Resources/ResourceMaterializer.cs index 1ce6b6a22..dded13e67 100644 --- a/src/SharpEmu.ShaderCompiler/Resources/ResourceMaterializer.cs +++ b/src/SharpEmu.ShaderCompiler/Resources/ResourceMaterializer.cs @@ -397,10 +397,9 @@ public FastOrigin(ShaderResourcePlan plan, ResourceRuntimeInputs inputs) return null; } - var plan = origin.Plan; - _lastRevalidateRefused = origin.Inputs.TablePhase is not null; - if (_lastRevalidateRefused) + if (origin.Inputs.TablePhase is not null) { + _lastRevalidateRefused = true; return false; } @@ -408,6 +407,28 @@ public FastOrigin(ShaderResourcePlan plan, ResourceRuntimeInputs inputs) inputs.UserData = origin.UserData; inputs.ShaderBase = origin.ShaderBase; inputs.ComputeState = origin.ComputeState; + try + { + return Revalidate(origin.Plan, snapshot, inputs); + } + finally + { + inputs.UserData = []; + _revalidationInputs = inputs; + } + } + + // Whether the plan evaluates to the snapshot's words again for these inputs (a draw's user data, shader base and + // readers), read as a materialization reads them; a reader wrapper that tells table words apart (TablePhase) is + // refused (LastRevalidateRefused). + public static bool Revalidate(ShaderResourcePlan plan, ResourceSnapshot snapshot, ResourceRuntimeInputs inputs) + { + _lastRevalidateRefused = inputs.TablePhase is not null || plan.MaterializationProgram is null; + if (_lastRevalidateRefused) + { + return false; + } + var output = TakeOutput(); try { @@ -416,8 +437,6 @@ public FastOrigin(ShaderResourcePlan plan, ResourceRuntimeInputs inputs) finally { _programOutput = output; - inputs.UserData = []; - _revalidationInputs = inputs; } } diff --git a/tests/SharpEmu.ShaderCompiler.Tests/Resources/FastOriginRevalidationTests.cs b/tests/SharpEmu.ShaderCompiler.Tests/Resources/FastOriginRevalidationTests.cs index a19b86c9c..a0ad637f6 100644 --- a/tests/SharpEmu.ShaderCompiler.Tests/Resources/FastOriginRevalidationTests.cs +++ b/tests/SharpEmu.ShaderCompiler.Tests/Resources/FastOriginRevalidationTests.cs @@ -66,4 +66,30 @@ public void AKeptSnapshotIsCurrentWhenOnlyTheLastDrawsDescriptorChanged() Assert.True(ResourceMaterializer.RevalidateFast(kept)); Assert.False(ResourceMaterializer.RevalidateFast(other)); } + + [Fact] + public void ExplicitInputsRevalidateWithTheirOwnUserDataAndShaderBase() + { + var plan = PointerPlan(); + var memory = new TestWordMemory { Base = 0x1000, Words = new uint[16] }; + uint[] descriptor = [0x8000, 0x10 << 16, 64, 0x24FAC]; + descriptor.CopyTo(memory.Words, 0); + descriptor.CopyTo(memory.Words, 8); + var snapshot = new ResourceSnapshot(); + var specialization = new ResourceSpecialization(); + Assert.True(ResourceMaterializer.MaterializeFast(plan, Inputs([0x1000, 0, 0, 0], memory.Read), ref snapshot, ref specialization, out _)); + + // Equal words through another pointer revalidate; a changed word or an unreadable one does not. + Assert.True(ResourceMaterializer.Revalidate(plan, snapshot, Inputs([0x1020, 0, 0, 0], memory.Read))); + memory.Words[9] = 0x20 << 16; + Assert.False(ResourceMaterializer.Revalidate(plan, snapshot, Inputs([0x1020, 0, 0, 0], memory.Read))); + Assert.True(ResourceMaterializer.Revalidate(plan, snapshot, Inputs([0x1000, 0, 0, 0], memory.Read))); + Assert.False(ResourceMaterializer.Revalidate(plan, snapshot, Inputs([0x4000, 0, 0, 0], memory.Read))); + Assert.False(ResourceMaterializer.LastRevalidateRefused); + + // A reader wrapper that splits the table phase is refused, never guessed. + var phased = new ResourceRuntimeInputs { UserData = new uint[] { 0x1000, 0, 0, 0 }, ReadMemory = memory.Read, TablePhase = _ => { } }; + Assert.False(ResourceMaterializer.Revalidate(plan, snapshot, phased)); + Assert.True(ResourceMaterializer.LastRevalidateRefused); + } } From 0ce695f3b851cd3e80a762583527284b0a5970f8 Mon Sep 17 00:00:00 2001 From: kuba Date: Sun, 15 Nov 2026 10:32:56 +0000 Subject: [PATCH 056/178] [GPU] Resolve memo on: keep many draws' graphics programs by content key A draw whose registers and user data match an entry takes its programs once every guest read the full resolution made gives the same answer (program cache epoch, device data loads, header record, code identity, vertex table words, pixel input semantics, descriptor words). The memo replaces the kept programs of the last draw while on. SHARPEMU_RESOLVE_MEMO=0 restores the kept path, =shadow only counts, =verify resolves each hit again and stops on a difference. --- .../Gpu/Pipelines/GraphicsProgramsComparer.cs | 169 +++++++++++ .../Gpu/Pipelines/GraphicsResolveMemo.cs | 10 +- .../Gpu/Pipelines/PixelStageInputResolver.cs | 2 +- .../Gpu/Pipelines/ShaderPipelineCache.cs | 282 +++++++++++++++++- .../Gpu/Pipelines/ShaderProgramCache.cs | 22 ++ .../Gpu/Pipelines/VertexInputResolver.cs | 4 + .../KeptStageInputsTests.ResolveMemo.cs | 210 +++++++++++++ .../Gpu/Pipelines/KeptStageInputsTests.cs | 5 +- 8 files changed, 697 insertions(+), 7 deletions(-) create mode 100644 src/SharpEmu.Libs/Gpu/Pipelines/GraphicsProgramsComparer.cs create mode 100644 tests/SharpEmu.Libs.Tests/Gpu/Pipelines/KeptStageInputsTests.ResolveMemo.cs diff --git a/src/SharpEmu.Libs/Gpu/Pipelines/GraphicsProgramsComparer.cs b/src/SharpEmu.Libs/Gpu/Pipelines/GraphicsProgramsComparer.cs new file mode 100644 index 000000000..a82b83fce --- /dev/null +++ b/src/SharpEmu.Libs/Gpu/Pipelines/GraphicsProgramsComparer.cs @@ -0,0 +1,169 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using SharpEmu.Libs.Gpu.Rendering; +using SharpEmu.ShaderCompiler.Resources; + +namespace SharpEmu.Libs.Gpu.Pipelines; + +// Whether two graphics resolutions hand the executor the same programs, inputs and resources: every field and array of +// GraphicsPrograms, its vertex and pixel inputs and each stage's program, shader base and snapshot words. The resolve +// memo's verify mode and its tests compare a hit with a full resolution through it. +internal static class GraphicsProgramsComparer +{ + // The first field that differs, or null when none does. + public static string? Difference(GraphicsPrograms memo, GraphicsPrograms full) + { + if (memo.Available != full.Available) return "available"; + if (memo.Vertex != full.Vertex) return "vertex_program"; + if (memo.Pixel != full.Pixel) return "pixel_program"; + if (!ReferenceEquals(memo.MeshInput, full.MeshInput) && memo.MeshInput != full.MeshInput) return "mesh_input"; + if (memo.Tessellation is not null || full.Tessellation is not null) return "tessellation"; + if (memo.SolidClear != full.SolidClear) return "solid_clear"; + if (memo.DisableBlending != full.DisableBlending) return "disable_blending"; + if (memo.DropUnwrittenColorTargets != full.DropUnwrittenColorTargets) return "drop_unwritten"; + if (memo.PositionStream != full.PositionStream) return "position_stream"; + return VertexDifference(memo.VertexInput, full.VertexInput) ?? PixelDifference(memo.PixelInput, full.PixelInput); + } + + private static string? VertexDifference(VertexInputInfo memo, VertexInputInfo full) + { + if (memo.Tessellation is not null || full.Tessellation is not null) return "vertex.tessellation"; + if (!memo.Buffers.AsSpan().SequenceEqual(full.Buffers)) return "vertex.buffers"; + if (!memo.Attributes.AsSpan().SequenceEqual(full.Attributes)) return "vertex.attributes"; + if (memo.FetchEmbedded != full.FetchEmbedded || memo.FetchAttributeRegister != full.FetchAttributeRegister || + memo.FetchBufferRegister != full.FetchBufferRegister) return "vertex.fetch"; + if (memo.IeeeMode != full.IeeeMode || memo.FloatMode != full.FloatMode || memo.Dx10Clamp != full.Dx10Clamp) return "vertex.modes"; + if (memo.ScratchDwords != full.ScratchDwords) return "vertex.scratch"; + 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"; + return StageDifference("vertex", memo.Stage, full.Stage); + } + + private static bool SameClipSpace(in ClipSpaceTransform memo, in ClipSpaceTransform full) => + (memo with { UserClipPlanes = null }) == (full with { UserClipPlanes = null }) && + (memo.UserClipPlanes ?? []).AsSpan().SequenceEqual(full.UserClipPlanes ?? []) && + (memo.UserClipPlanes is null) == (full.UserClipPlanes is null); + + private static string? PixelDifference(PixelInputInfo memo, PixelInputInfo full) + { + if (memo.InputCount != full.InputCount || memo.SystemInputBase != full.SystemInputBase || + memo.CustomInterpolationMask != full.CustomInterpolationMask || memo.PerspectiveCenterRegister != full.PerspectiveCenterRegister) + return "pixel.inputs"; + if (!memo.InterpolatorSettings.AsSpan().SequenceEqual(full.InterpolatorSettings)) return "pixel.interpolators"; + if (!memo.TargetOutputModes.AsSpan().SequenceEqual(full.TargetOutputModes)) return "pixel.output_modes"; + if (!memo.TargetExportMappings.AsSpan().SequenceEqual(full.TargetExportMappings)) return "pixel.export_mappings"; + if (!memo.TargetExportFormats.AsSpan().SequenceEqual(full.TargetExportFormats)) return "pixel.export_formats"; + if (memo.GuestWave32 != full.GuestWave32 || memo.IeeeMode != full.IeeeMode || memo.FloatMode != full.FloatMode || + memo.Dx10Clamp != full.Dx10Clamp) return "pixel.modes"; + if (memo.ScratchDwords != full.ScratchDwords) return "pixel.scratch"; + if (memo.PositionX != full.PositionX || memo.PositionY != full.PositionY || memo.PositionZ != full.PositionZ || + memo.PositionW != full.PositionW || memo.FrontFace != full.FrontFace || memo.FrontFaceAllBits != full.FrontFaceAllBits || + memo.NoPerspective != full.NoPerspective || memo.SampleShading != full.SampleShading) return "pixel.system_inputs"; + if (memo.KillEnable != full.KillEnable || memo.DepthExportEnable != full.DepthExportEnable || + memo.StencilExportEnable != full.StencilExportEnable || memo.SampleMaskExportEnable != full.SampleMaskExportEnable || + memo.DepthExportFormat != full.DepthExportFormat || memo.EarlyDepth != full.EarlyDepth || memo.ExecuteOnNoop != full.ExecuteOnNoop) + return "pixel.depth_control"; + return StageDifference("pixel", memo.Stage, full.Stage); + } + + private static string? StageDifference(string stage, in ShaderStageResources memo, in ShaderStageResources full) + { + 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 (!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)) + return stage + ".calls"; + if (memo.Program is null) return null; + return SnapshotDifference(stage, memo.Resources, full.Resources); + } + + private static string? SnapshotDifference(string stage, ResourceSnapshot memo, ResourceSnapshot full) + { + if (ReferenceEquals(memo, full)) return null; + if (!SameJagged(memo.Buffers, full.Buffers)) return stage + ".buffers"; + if (!SameJagged(memo.Images, full.Images)) return stage + ".images"; + if (!SameJagged(memo.Samplers, full.Samplers)) return stage + ".samplers"; + if (!memo.FlattenedResourceTable.AsSpan().SequenceEqual(full.FlattenedResourceTable)) return stage + ".table"; + 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.BindlessImages.Length != full.BindlessImages.Length) return stage + ".bindless"; + for (var index = 0; index < memo.BindlessImages.Length; index++) + { + var (a, b) = (memo.BindlessImages[index], full.BindlessImages[index]); + if (!ReferenceEquals(a, b) && (a.Slot != b.Slot || a.Address != b.Address || !a.VariantImages.AsSpan().SequenceEqual(b.VariantImages) || + !SameJagged(a.Descriptors, b.Descriptors) || !a.DescriptorVariants.AsSpan().SequenceEqual(b.DescriptorVariants) || + !a.Entries.AsSpan().SequenceEqual(b.Entries))) + return stage + ".bindless"; + } + + return null; + } + + private static bool SameArray(T[]? memo, T[]? full) => + ReferenceEquals(memo, full) || (memo is not null && full is not null && memo.AsSpan().SequenceEqual(full)); + + private static bool SameJagged(uint[][] memo, uint[][] full) + { + if (memo.Length != full.Length) return false; + for (var index = 0; index < memo.Length; index++) + { + if (!memo[index].AsSpan().SequenceEqual(full[index])) return false; + } + + return true; + } + + // A hash of everything Difference compares, taken when a result is kept and again before it is handed out, so a + // write into a shared result shows. + public static ulong Fingerprint(GraphicsPrograms programs) + { + var hash = 0xCBF29CE484222325UL; + void Mix(ulong value) => hash = (hash ^ value) * 0x100000001B3UL; + void MixWords(ReadOnlySpan words) + { + Mix((ulong)words.Length); + foreach (var word in words) Mix(word); + } + + void MixStage(in ShaderStageResources stage) + { + Mix((ulong)System.Runtime.CompilerServices.RuntimeHelpers.GetHashCode(stage.Program)); + Mix(stage.ShaderBase); + if (stage.Program is null) return; + var snapshot = stage.Resources; + foreach (var words in snapshot.Buffers) MixWords(words); + foreach (var words in snapshot.Images) MixWords(words); + foreach (var words in snapshot.Samplers) MixWords(words); + MixWords(snapshot.FlattenedResourceTable); + MixWords(snapshot.UserData); + MixWords(snapshot.MipStatistics ?? []); + foreach (var range in snapshot.DeviceAddressRanges) Mix((ulong)range.GetHashCode()); + } + + Mix(programs.Vertex.Id); + Mix(programs.Pixel.Id); + Mix(programs.DropUnwrittenColorTargets ? 1u : 0u); + var vertex = programs.VertexInput; + foreach (var buffer in vertex.Buffers) Mix((ulong)buffer.GetHashCode()); + foreach (var attribute in vertex.Attributes) Mix((ulong)attribute.GetHashCode()); + Mix((ulong)(vertex.ClipSpace with { UserClipPlanes = null }).GetHashCode()); + Mix((uint)vertex.StartInstanceUserData); + Mix((vertex.IeeeMode ? 1u : 0u) | (vertex.Dx10Clamp ? 2u : 0u) | ((ulong)vertex.FloatMode << 8)); + MixStage(vertex.Stage); + var pixel = programs.PixelInput; + Mix(pixel.InputCount); + Mix(pixel.CustomInterpolationMask); + MixWords(pixel.InterpolatorSettings); + foreach (var mode in pixel.TargetOutputModes) Mix(mode); + foreach (var mapping in pixel.TargetExportMappings) Mix(mapping.Packed); + foreach (var format in pixel.TargetExportFormats) Mix(format); + Mix((pixel.IeeeMode ? 1u : 0u) | (pixel.Dx10Clamp ? 2u : 0u) | (pixel.GuestWave32 ? 4u : 0u) | ((ulong)pixel.FloatMode << 8)); + MixStage(pixel.Stage); + return hash; + } +} diff --git a/src/SharpEmu.Libs/Gpu/Pipelines/GraphicsResolveMemo.cs b/src/SharpEmu.Libs/Gpu/Pipelines/GraphicsResolveMemo.cs index 02b65f958..0efff5420 100644 --- a/src/SharpEmu.Libs/Gpu/Pipelines/GraphicsResolveMemo.cs +++ b/src/SharpEmu.Libs/Gpu/Pipelines/GraphicsResolveMemo.cs @@ -57,6 +57,9 @@ internal enum ResolveMemoUncacheable Origin, // A user data count over the bank (the full resolution stops on it). Key, + // A program entry, the device data loads or the vertex table metadata changed while the draw resolved, or its + // vertex source is not the draw's. + Changed, Count, } @@ -72,11 +75,12 @@ internal sealed class GraphicsResolveMemo internal static readonly int DefaultCapacity = int.TryParse(Environment.GetEnvironmentVariable("SHARPEMU_RESOLVE_MEMO_ENTRIES"), out var entries) && entries >= 2 ? entries : 16384; - // The memo only counts what it would hit for now (shadow); 0 turns that off too. internal static ResolveMemoMode ParseMode(string? value) => value?.Trim().ToLowerInvariant() switch { "0" or "off" => ResolveMemoMode.Off, - _ => ResolveMemoMode.Shadow, + "shadow" => ResolveMemoMode.Shadow, + "verify" => ResolveMemoMode.Verify, + _ => ResolveMemoMode.On, }; // One way of a set: the key it was resolved under and what the hit re-checks. @@ -382,7 +386,7 @@ public static string TakeReport() => FormattableString.Invariant( $"resolve_memo=(mode={DefaultMode.ToString().ToLowerInvariant()},hits={_hits.Take()},would_hit={_shadowWouldHit.Take()},") + "miss_by=(" + Take(_misses, "new", "epoch", "header", "identity", "tables", "semantics", "words", "generation") + ")," + "key_miss=(" + Take(_keyMisses, "new", "user_data_only", "regs_only") + ")," + - "uncacheable_by=(" + Take(_uncacheable, "frontend", "mesh", "tess", "calls", "unavailable", "tables", "trace", "origin", "key") + ")," + + "uncacheable_by=(" + Take(_uncacheable, "frontend", "mesh", "tess", "calls", "unavailable", "tables", "trace", "origin", "key", "changed") + ")," + FormattableString.Invariant($"evictions={_evictions.Take()},entries={_entries.Total},verify_checked={_verifyChecked.Take()},") + FormattableString.Invariant($"verify_failed={Interlocked.Read(ref _verifyFailed)})"); } diff --git a/src/SharpEmu.Libs/Gpu/Pipelines/PixelStageInputResolver.cs b/src/SharpEmu.Libs/Gpu/Pipelines/PixelStageInputResolver.cs index 3aadd540e..99fb59fca 100644 --- a/src/SharpEmu.Libs/Gpu/Pipelines/PixelStageInputResolver.cs +++ b/src/SharpEmu.Libs/Gpu/Pipelines/PixelStageInputResolver.cs @@ -61,7 +61,7 @@ public static uint CountSystemInputRegisters(ShaderInterfaceRegisters shaderInte // draw still reads it. One read for all of them: this was one guest read per input (up to 32), each // taking the memory read lock, to decode a few words. // semantics: the words a shader frontend already read (IShaderFrontend), instead of the guest table. - private static uint CustomInterpolationMask(CpuContext context, RegisteredShader shader, uint semanticCount, uint[]? semantics = null) + internal static uint CustomInterpolationMask(CpuContext context, RegisteredShader shader, uint semanticCount, uint[]? semantics = null) { if (semanticCount == 0) { diff --git a/src/SharpEmu.Libs/Gpu/Pipelines/ShaderPipelineCache.cs b/src/SharpEmu.Libs/Gpu/Pipelines/ShaderPipelineCache.cs index d3561c82a..4e549df48 100644 --- a/src/SharpEmu.Libs/Gpu/Pipelines/ShaderPipelineCache.cs +++ b/src/SharpEmu.Libs/Gpu/Pipelines/ShaderPipelineCache.cs @@ -310,10 +310,16 @@ public GraphicsPrograms GetGraphicsPrograms( lock (_resolveGate) { using var workScope = RenderPhaseProfile.MeasureDetail(RenderPhaseProfile.Phase.ProgramPreparation); + var flags = new KeptGraphicsFlags(pixelActive, depthBound, depthAspectBound, stencilAspectBound, triangleList, startInstanceUserData); + if (_resolveMemo is { Mode: ResolveMemoMode.On or ResolveMemoMode.Verify } memo) + { + // The memo replaces the kept programs of the last draw: it holds them too. + return ResolveThroughMemo(memo, banks, targetExportMapping, flags); + } + var stamps = new KeptGraphicsStamps( banks.Stamp(RegisterStamp.ShaderPrograms), banks.Stamp(RegisterStamp.VertexUserData), banks.Stamp(RegisterStamp.PixelUserData), banks.Stamp(RegisterStamp.ColorTargets, RegisterStamp.ShaderInterface), ShaderHeaderRegistry.Registrations); - var flags = new KeptGraphicsFlags(pixelActive, depthBound, depthAspectBound, stencilAspectBound, triangleList, startInstanceUserData); var shadowMiss = ShadowResolveMemo(banks, targetExportMapping, flags); ClaimKeptPrograms(); var kept = _keptGraphics ??= new KeptGraphicsPrograms(); @@ -384,6 +390,275 @@ private bool ShadowResolveMemo(RegisterBanks banks, ReadOnlySpan targetExportMapping, + in KeptGraphicsFlags flags) + { + var cacheable = false; + if (_registry.HasFrontend) + { + GraphicsResolveMemo.NoteUncacheable(ResolveMemoUncacheable.Frontend); + } + else if (_programs.TracesLookups) + { + GraphicsResolveMemo.NoteUncacheable(ResolveMemoUncacheable.Trace); + } + else if (!memo.Fill(banks, targetExportMapping, flags, new PixelOutputBlendBits(PixelOutputBlend(banks.Context)))) + { + GraphicsResolveMemo.NoteUncacheable(ResolveMemoUncacheable.Key); + } + else + { + cacheable = true; + if (memo.Find() is { } entry) + { + if (TryTakeResolveMemo(entry, flags.PixelActive) is not { } miss) + { + GraphicsResolveMemo.NoteHit(); + if (memo.Mode == ResolveMemoMode.Verify) + { + VerifyResolveMemo(entry, banks, targetExportMapping, flags); + } + + return entry.Programs!; + } + + GraphicsResolveMemo.NoteMiss(miss); + } + else + { + GraphicsResolveMemo.NoteMiss(ResolveMemoMiss.New); + GraphicsResolveMemo.NoteKeyMiss(memo.ClassifyMiss()); + } + } + + _graphicsResolved.Increment(); + var deviceDataGeneration = DeviceDataLoads.Generation; + var contentEpoch = _programs.ContentEpoch; + var linkedLookups = _programs.LinkedLookups; + var tablesGeneration = _vertexTables.Generation; + var programs = ResolveFull(banks, targetExportMapping, flags); + if (cacheable) + { + StoreResolveMemo(memo, banks, programs, flags.PixelActive, deviceDataGeneration, contentEpoch, linkedLookups, tablesGeneration); + } + + return programs; + } + + private GraphicsPrograms ResolveFull(RegisterBanks banks, ReadOnlySpan targetExportMapping, in KeptGraphicsFlags flags) => + ResolveGraphicsProgramsCore(banks.Shader.Vertex, banks.Shader.Pixel, banks.Context.ShaderInterface, banks.Context, targetExportMapping, + flags.PixelActive, flags.DepthBound, flags.DepthAspectBound, flags.StencilAspectBound, flags.TriangleList, mesh: null, + startInstanceUserData: flags.StartInstanceUserData, nativeTessellation: true); + + // Null when every guest read the entry's resolution made still gives the same answer: the program cache and the + // device data loads unchanged, the same header record and code identity at each stage's address, the same vertex + // table words and pixel input semantics, and each stage's descriptor words evaluating to its snapshot (the reads + // the full resolution records are made here as well). + private ResolveMemoMiss? TryTakeResolveMemo(GraphicsResolveMemo.Entry entry, bool pixelActive) + { + if (entry.ContentEpoch != _programs.ContentEpoch || entry.TablesGeneration != _vertexTables.Generation) + { + return ResolveMemoMiss.Epoch; + } + + if (entry.DeviceDataGeneration != DeviceDataLoads.Generation) + { + return ResolveMemoMiss.Generation; + } + + if (!ReferenceEquals(_registry.Require(entry.VertexAddress, "vertex"), entry.VertexShader)) + { + return ResolveMemoMiss.Header; + } + + if (HashOf(entry.VertexShader!, entry.VertexAddress, "vertex") != entry.VertexHash) + { + return ResolveMemoMiss.Identity; + } + + if (pixelActive) + { + if (!ReferenceEquals(_registry.Require(entry.PixelAddress, "pixel"), entry.PixelShader)) + { + return ResolveMemoMiss.Header; + } + + if (HashOf(entry.PixelShader!, entry.PixelAddress, "pixel") != entry.PixelHash) + { + return ResolveMemoMiss.Identity; + } + } + + if (entry.TableWords is { } words && !VertexInputResolver.SameTableWords(_context, words, entry.AttributeTable, entry.BufferTable, + _vertexTableScratch ??= new uint[VertexTableWords.MaxWords])) + { + return ResolveMemoMiss.Tables; + } + + if (pixelActive && + PixelStageInputResolver.CustomInterpolationMask(_context, entry.PixelShader!, entry.PixelSemanticCount) != entry.PixelCustomMask) + { + return ResolveMemoMiss.Semantics; + } + + var programs = entry.Programs!; + if ((pixelActive && !RevalidateMemoStage(programs.PixelInput.Stage)) || !RevalidateMemoStage(programs.VertexInput.Stage)) + { + return ResolveMemoMiss.Words; + } + + // A load learned while the words were read. + return entry.DeviceDataGeneration != DeviceDataLoads.Generation ? ResolveMemoMiss.Generation : null; + } + + private bool RevalidateMemoStage(in ShaderStageResources stage) + { + _host.BeginGuestWordReads(); + try + { + return _programs.Revalidate(stage); + } + finally + { + _host.EndGuestWordReads(); + } + } + + // Keeps a full resolution under the filled key, with what a hit re-checks, when it can be repeated from them: one + // vertex and pixel program pair with no tessellation, mesh or shader calls, nothing changed while it resolved, and + // vertex tables read back to the inputs it decoded (the guest may have written them since). + private void StoreResolveMemo(GraphicsResolveMemo memo, RegisterBanks banks, GraphicsPrograms programs, bool pixelActive, + int deviceDataGeneration, long contentEpoch, long linkedLookups, long tablesGeneration) + { + var cause = !programs.Available ? ResolveMemoUncacheable.Unavailable + : programs.MeshInput is not null ? ResolveMemoUncacheable.Mesh + : programs.Tessellation is not null || programs.VertexInput.Tessellation is not null ? ResolveMemoUncacheable.Tessellation + : _programs.LinkedLookups != linkedLookups || HasCalls(programs.VertexInput.Stage) || HasCalls(programs.PixelInput.Stage) + ? ResolveMemoUncacheable.Calls + : DeviceDataLoads.Generation != deviceDataGeneration || _programs.ContentEpoch != contentEpoch || + _vertexTables.Generation != tablesGeneration ? ResolveMemoUncacheable.Changed + : programs.VertexInput.Stage.Program is null || programs.VertexInput.Stage.Resources.Origin is null || + (pixelActive && (programs.PixelInput.Stage.Program is null || programs.PixelInput.Stage.Resources.Origin is null)) + ? ResolveMemoUncacheable.Origin + : (ResolveMemoUncacheable?)null; + var vertexSource = _lastSources[(int)ShaderStage.Vertex]; + var pixelSource = pixelActive ? _lastSources[(int)ShaderStage.Pixel] : null; + if (cause is null && (vertexSource is null || vertexSource.Address != banks.Shader.Vertex.ExportAddress || + (pixelActive && (pixelSource is null || pixelSource.Address != banks.Shader.Pixel.Address)))) + { + cause = ResolveMemoUncacheable.Changed; + } + + VertexTableWords? tableWords = null; + ulong attributeTable = 0, bufferTable = 0; + if (cause is null && !TryReadMemoTables(vertexSource!, programs.VertexInput, out tableWords, out attributeTable, out bufferTable)) + { + cause = ResolveMemoUncacheable.Tables; + } + + if (cause is { } refused) + { + GraphicsResolveMemo.NoteUncacheable(refused); + return; + } + + var entry = memo.Store(); + entry.Programs = programs; + entry.VertexShader = vertexSource!.Registered; + entry.VertexAddress = vertexSource.Address; + entry.VertexHash = vertexSource.Hash; + entry.TableWords = tableWords; + entry.AttributeTable = attributeTable; + entry.BufferTable = bufferTable; + if (pixelSource is not null) + { + entry.PixelShader = pixelSource.Registered; + entry.PixelAddress = pixelSource.Address; + entry.PixelHash = pixelSource.Hash; + entry.PixelSemanticCount = Math.Min(Math.Min(pixelSource.Registered.InputSemanticsCount, programs.PixelInput.InputCount), + (uint)PixelInputInfo.InterpolatorCount); + entry.PixelCustomMask = programs.PixelInput.CustomInterpolationMask; + } + + entry.ContentEpoch = contentEpoch; + entry.DeviceDataGeneration = deviceDataGeneration; + entry.TablesGeneration = tablesGeneration; + entry.Fingerprint = memo.Mode == ResolveMemoMode.Verify ? GraphicsProgramsComparer.Fingerprint(programs) : 0; + } + + private static bool HasCalls(in ShaderStageResources stage) => + stage.CallArguments is { Length: > 0 } || stage.CallTargets is { Length: > 0 } || stage.CallRecords is { Length: > 0 } || + stage.CallRecordRanges is { Length: > 0 }; + + // The vertex table words the draw's inputs decode from, read again now: false when they cannot be compared later + // (static attributes, more inputs than a table holds, a table not read whole) or no longer decode to the draw's + // attributes and buffers. Null words when the program reads no tables. + private bool TryReadMemoTables(ShaderSource source, VertexInputInfo resolved, out VertexTableWords? words, out ulong attributeTable, + out ulong bufferTable) + { + words = null; + attributeTable = bufferTable = 0; + if (!_vertexTables.TryGet(source.Registered, source.Hash, out var metadata) || metadata is null) + { + return false; + } + + if (!VertexInputResolver.ReadsTables(metadata)) + { + return resolved.Attributes.Length == 0 && resolved.Buffers.Length == 0; + } + + if (metadata.InputSemantics.Length > VertexInputInfo.MaxBuffers) + { + return false; + } + + foreach (var word in metadata.InputSemantics) + { + var semantic = new ShaderInputSemantic(word); + if (semantic.StaticBufferIndex || semantic.StaticAttribute) + { + return false; + } + } + + attributeTable = VertexInputResolver.ReadTablePointer(source.UserData, metadata.VertexAttributeRegister); + bufferTable = VertexInputResolver.ReadTablePointer(source.UserData, metadata.VertexBufferRegister); + if (attributeTable == 0 || bufferTable == 0) + { + return false; + } + + var decoded = VertexInputResolver.ResolveVertexInputs(_context, source.Registered, metadata, source.UserData, resolved.PositionExportControl, + resolved.ClipSpace, out words); + return words is { WholeSpans: true } && + decoded.Attributes.AsSpan().SequenceEqual(resolved.Attributes) && decoded.Buffers.AsSpan().SequenceEqual(resolved.Buffers); + } + + // Verify: the hit's programs against a full resolution of the same draw, and against what they were when kept; any + // difference stops emulation. + private void VerifyResolveMemo(GraphicsResolveMemo.Entry entry, RegisterBanks banks, ReadOnlySpan targetExportMapping, + in KeptGraphicsFlags flags) + { + var memoPrograms = entry.Programs!; + var full = ResolveFull(banks, targetExportMapping, flags); + var difference = GraphicsProgramsComparer.Difference(memoPrograms, full) ?? + (GraphicsProgramsComparer.Fingerprint(memoPrograms) != entry.Fingerprint ? "written_since_kept" : null); + GraphicsResolveMemo.NoteVerified(); + if (difference is null) + { + return; + } + + GraphicsResolveMemo.NoteVerifyFailed(); + var message = $"[GPU][RESOLVE_MEMO] verify mismatch field={difference} vs=0x{entry.VertexAddress:X16} ps=0x{entry.PixelAddress:X16} " + + $"key_hash=0x{entry.Hash:X16}."; + Console.Error.WriteLine(message); + throw GpuFatal.Fatal(message); + } + // The interface's earlier forms, for callers holding only the four inputs. public GraphicsPrograms GetGraphicsPrograms( RegisterBanks banks, @@ -778,6 +1053,11 @@ public GraphicsPrograms GetMeshGraphicsPrograms( } return new GraphicsPrograms { Available = false }; } + if (ResolveMemoMode is ResolveMemoMode.On or ResolveMemoMode.Verify) + { + GraphicsResolveMemo.NoteUncacheable(ResolveMemoUncacheable.Mesh); + } + return GetGraphicsProgramsCore(vertex, pixel, shaderInterface, context, targetExportMapping, pixelActive, depthBound, depthAspectBound: depthBound, stencilAspectBound: false, triangleList: false, mesh); } diff --git a/src/SharpEmu.Libs/Gpu/Pipelines/ShaderProgramCache.cs b/src/SharpEmu.Libs/Gpu/Pipelines/ShaderProgramCache.cs index 706fd0c9f..a308e6760 100644 --- a/src/SharpEmu.Libs/Gpu/Pipelines/ShaderProgramCache.cs +++ b/src/SharpEmu.Libs/Gpu/Pipelines/ShaderProgramCache.cs @@ -337,6 +337,22 @@ private sealed record PendingTranslation(ProgramSourceEntry Entry, ResourceSpeci public ResourceMaterializationCache? Materializations => _materializations; + // Bumped whenever a program entry is replaced (a re-plan) or a plan refused: a lookup made before may find another + // entry now (ShaderPipelineCache's resolve memo). + private long _contentEpoch; + + internal long ContentEpoch => Interlocked.Read(ref _contentEpoch); + + // Lookups that linked shader calls or ran a runtime fallback, which a resolve memo hit could not repeat. + private long _linkedLookups; + + internal long LinkedLookups => Interlocked.Read(ref _linkedLookups); + + // A lookup made now logs or traces what it reads, which a resolve memo hit would skip. + internal bool TracesLookups => + _spirvDumpEnabled || ReadLog is not null || Diagnostics.GpuReadTrace.Enabled || SharpEmu.Libs.Gpu.Images.ImageClearTrace.Enabled || + RenderTrace.Enabled; + public bool Revalidate(in ShaderStageResources stage) { if (stage.Program is null) @@ -692,6 +708,7 @@ private ShaderProgram GetOrCompileCore(ShaderSource source, StageCompileOptions { BuildStaticState(source.Stage, options); _rejectedPlans[BuildProgramKey(source)] = (exception.Message, deviceDataLoads); + Interlocked.Increment(ref _contentEpoch); throw; } @@ -757,6 +774,7 @@ private ShaderProgram CompleteProgram(ProgramSourceEntry entry, bool sourceWasCa BuildStaticState(source.Stage, options); key = BuildProgramKey(source); _programs[key] = entry; + Interlocked.Increment(ref _contentEpoch); DeviceDataLoads.CountReplan(); } } @@ -796,6 +814,10 @@ private ShaderProgram CompleteProgram(ProgramSourceEntry entry, bool sourceWasCa // A backend that cannot link compiles the caller alone, as every backend did before // linking existed: its S_SWAPPC_B64 calls are skipped rather than the program refused. var hasShaderCalls = entry.HasShaderCalls && _compiler.LinkedShaderCallsSupported; + if (hasShaderCalls || entry.RuntimeCallRecords || runtimeFallback is not null) + { + Interlocked.Increment(ref _linkedLookups); + } // Both are assigned by the materialization that follows; a failed one throws. ResourceSnapshot snapshot = null!; diff --git a/src/SharpEmu.Libs/Gpu/Pipelines/VertexInputResolver.cs b/src/SharpEmu.Libs/Gpu/Pipelines/VertexInputResolver.cs index 8dd92ea62..f14decde6 100644 --- a/src/SharpEmu.Libs/Gpu/Pipelines/VertexInputResolver.cs +++ b/src/SharpEmu.Libs/Gpu/Pipelines/VertexInputResolver.cs @@ -54,12 +54,16 @@ public sealed partial class VertexTableMetadataCache internal bool TryGet(RegisteredShader shader, ulong codeHash, out VertexTableMetadata? metadata) => _entries.TryGetValue((shader, codeHash), out metadata); + // Bumped when the entries are dropped: an entry found before may be read from the header again. + internal long Generation { get; private set; } + internal void Add(RegisteredShader shader, ulong codeHash, VertexTableMetadata metadata) { if (_entries.Count >= MaxEntries) { _entries.Clear(); _history?.Clear(); + Generation++; } _entries[(shader, codeHash)] = metadata; diff --git a/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/KeptStageInputsTests.ResolveMemo.cs b/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/KeptStageInputsTests.ResolveMemo.cs new file mode 100644 index 000000000..fc63d4ff1 --- /dev/null +++ b/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/KeptStageInputsTests.ResolveMemo.cs @@ -0,0 +1,210 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using System.Reflection; +using SharpEmu.Libs.Gpu.GpuCommands.Registers; +using SharpEmu.Libs.Gpu.Pipelines; +using SharpEmu.Libs.Gpu.Rendering; +using SharpEmu.ShaderCompiler.Resources; +using Xunit; + +namespace SharpEmu.Libs.Tests.Gpu.Pipelines; + +// The resolve memo (GraphicsResolveMemo) hands a draw the programs of an earlier draw with its key only while every +// guest read of that resolution gives the same answer; verify mode resolves each hit again and stops on a difference. +public sealed partial class KeptStageInputsTests +{ + private const ulong LoadingPixelAddress = PipelineTestGuest.MemoryBase + 0x3000; + private const ulong LoadingPixelHeader = PipelineTestGuest.MemoryBase + 0x8200; + private const ulong Descriptor = PipelineTestGuest.MemoryBase + 0xD000; + private const ulong OtherDescriptor = PipelineTestGuest.MemoryBase + 0xD100; + + private ShaderPipelineCache MemoCache(ResolveMemoMode mode = ResolveMemoMode.Verify) => + new(_guest.Context, _guest.Host, _guest.Compiler, _guest.Registry) { ResolveMemoMode = mode }; + + private GraphicsPrograms Programs(ShaderPipelineCache cache, bool pixelActive) + { + var programs = cache.GetGraphicsPrograms(_banks, [], pixelActive, depthBound: false); + Assert.True(programs.Available); + return programs; + } + + private static string Report() => GraphicsResolveMemo.TakeReport(); + + // A pixel program that loads a V# through the pointer in s[0:1] and reads through it. + private void UseLoadingPixelProgram(ulong descriptor) + { + _guest.RegisterProgram(LoadingPixelAddress, LoadingPixelHeader, [0xF4080000, 0xFA000000, 0xE0000000, 0x80000000, 0xBF810000], + PixelUserDataBlock); + _guest.WriteWords(Descriptor, PipelineTestGuest.BufferDescriptor(StreamBase, 16, 4, Format32x4Float)); + _guest.WriteWords(OtherDescriptor, PipelineTestGuest.BufferDescriptor(StreamBase, 16, 4, Format32x4Float)); + _banks.Shader.Pixel.Address = LoadingPixelAddress; + PointPixelAt(descriptor); + } + + private void PointPixelAt(ulong descriptor) + { + _banks.Shader.Pixel.UserScalars.Set(0, (uint)descriptor, UserScalarKind.Unknown); + _banks.Shader.Pixel.UserScalars.Set(1, (uint)(descriptor >> 32), UserScalarKind.Unknown); + _banks.MarkWritten(1u << (int)RegisterStamp.PixelUserData); + } + + [Fact] + public void ResolveMemo_HandsADrawSeenBeforeItsProgramsAndVerifiesThem() + { + var cache = MemoCache(); + Report(); + var vertexOnly = Programs(cache, pixelActive: false); + var withPixel = Programs(cache, pixelActive: true); + Assert.NotSame(vertexOnly, withPixel); + // Not only the last draw: both keys are held. + Assert.Same(vertexOnly, Programs(cache, pixelActive: false)); + Assert.Same(withPixel, Programs(cache, pixelActive: true)); + var report = Report(); + Assert.Contains("hits=2,", report); + Assert.Contains("verify_checked=2,", report); + Assert.Contains("verify_failed=0)", report); + } + + [Fact] + public void ResolveMemo_TakesAnotherKeyForOtherUserDataAndComesBackToTheFirst() + { + var cache = MemoCache(); + UseLoadingPixelProgram(Descriptor); + var first = Programs(cache, pixelActive: true); + PointPixelAt(OtherDescriptor); + var other = Programs(cache, pixelActive: true); + Assert.NotSame(first, other); + PointPixelAt(Descriptor); + Assert.Same(first, Programs(cache, pixelActive: true)); + PointPixelAt(OtherDescriptor); + Assert.Same(other, Programs(cache, pixelActive: true)); + } + + [Fact] + public void ResolveMemo_MissesWhenAStagesDescriptorWordChanges() + { + var cache = MemoCache(); + UseLoadingPixelProgram(Descriptor); + var first = Programs(cache, pixelActive: true); + Assert.Same(first, Programs(cache, pixelActive: true)); + Report(); + _guest.WriteWords(Descriptor, PipelineTestGuest.BufferDescriptor(StreamBase + 0x100, 16, 4, Format32x4Float)); + var changed = Programs(cache, pixelActive: true); + Assert.NotSame(first, changed); + Assert.Contains("words=1", Report()); + Assert.Same(changed, Programs(cache, pixelActive: true)); + } + + [Fact] + public void ResolveMemo_MissesWhenTheVertexTableWordsChange() + { + var cache = MemoCache(); + var first = Programs(cache, pixelActive: false); + Assert.Same(first, Programs(cache, pixelActive: false)); + Report(); + WriteTables(AttributeTable, BufferTable, stride: 32); + var changed = Programs(cache, pixelActive: false); + Assert.NotSame(first, changed); + Assert.Equal(32u, changed.VertexInput.Buffers[0].Stride); + Assert.Contains("tables=1", Report()); + } + + [Fact] + public void ResolveMemo_MissesWhenAContextRegisterTheResolutionReadsChanges() + { + var cache = MemoCache(); + var first = Programs(cache, pixelActive: true); + WriteContext(ContextRegisterOffset.CbShaderMask, 0x0000_000F); + var masked = Programs(cache, pixelActive: true); + Assert.NotSame(first, masked); + WriteContext(ContextRegisterOffset.PaClClipCntl, 1u << 16); + WriteContext(ContextRegisterOffset.PaClViewportXScale, Float(32f)); + var unclipped = Programs(cache, pixelActive: true); + Assert.NotSame(masked, unclipped); + WriteContext(ContextRegisterOffset.PaClViewportXScale, Float(64f)); + Assert.Equal(64f, Programs(cache, pixelActive: true).VertexInput.ClipSpace.ScaleX); + } + + [Fact] + public void ResolveMemo_KeepsTheProgramsOverAGlobalRegistrationButNotOverANewHeader() + { + var cache = MemoCache(); + var first = Programs(cache, pixelActive: false); + // Another header registered elsewhere: this draw's header record is unchanged. + ShaderHeaderRegistry.NoteRegistration(); + Assert.Same(first, Programs(cache, pixelActive: false)); + Report(); + _guest.RegisterProgram(VertexAddress, VertexHeader, [0xBF800000, 0xBF810000], UserDataBlock, Semantics, 2); + Assert.NotSame(first, Programs(cache, pixelActive: false)); + var report = Report(); + Assert.True(report.Contains("header=1") || report.Contains("identity=1") || report.Contains("epoch=1"), report); + } + + [Fact] + public void ResolveMemo_MissesWhenThePixelInputSemanticsChange() + { + const ulong PixelSemantics = PipelineTestGuest.MemoryBase + 0x9300; + _guest.WriteWords(PixelSemantics, 0); + _guest.RegisterProgram(PixelAddress, PixelHeader, PipelineTestGuest.EndProgram, PixelUserDataBlock, PixelSemantics, 1); + WriteContext(ContextRegisterOffset.SpiPsInControl, 1); + var cache = MemoCache(); + var first = Programs(cache, pixelActive: true); + Assert.Same(first, Programs(cache, pixelActive: true)); + Report(); + _guest.WriteWords(PixelSemantics, 1u << 24); + var custom = Programs(cache, pixelActive: true); + Assert.NotSame(first, custom); + Assert.Equal(1u, custom.PixelInput.CustomInterpolationMask); + Assert.Contains("semantics=1", Report()); + } + + [Fact] + public void ResolveMemo_MissesOnceADeviceDataLoadIsLearned() + { + var cache = MemoCache(); + var first = Programs(cache, pixelActive: false); + Assert.Same(first, Programs(cache, pixelActive: false)); + DeviceDataLoads.Learn(0x5EED_0000_0000_0000UL | (ulong)Environment.TickCount64, [3]); + Assert.NotSame(first, Programs(cache, pixelActive: false)); + } + + [Fact] + public void ResolveMemo_OffResolvesAsTheKeptProgramsDid() + { + var cache = MemoCache(ResolveMemoMode.Off); + _ = Programs(cache, pixelActive: true); + var cached = Programs(cache, pixelActive: true); + Assert.Same(cached, Programs(cache, pixelActive: true)); + Assert.NotSame(cached, Programs(cache, pixelActive: false)); + Assert.NotSame(cached, Programs(cache, pixelActive: true)); + } + + // The comparer behind verify names every field of what a resolution hands out: a field added later fails here + // until the comparer (and the memo's key, if the resolution reads something new for it) covers it. + [Fact] + public void ResolveMemo_TheVerifyComparerCoversEveryFieldOfAResolution() + { + // Every settable property and public field (computed getters derive from them). + static string[] Names(Type type) => type.GetProperties(BindingFlags.Instance | BindingFlags.Public) + .Where(property => property.SetMethod is not null).Select(property => property.Name) + .Concat(type.GetFields(BindingFlags.Instance | BindingFlags.Public).Select(field => field.Name)) + .Order(StringComparer.Ordinal).ToArray(); + + Assert.Equal(["Available", "DisableBlending", "DropUnwrittenColorTargets", "MeshInput", "Pixel", "PixelInput", "PositionStream", + "SolidClear", "Tessellation", "Vertex", "VertexInput"], Names(typeof(GraphicsPrograms))); + Assert.Equal(["Attributes", "Buffers", "ClipSpace", "Dx10Clamp", "FetchAttributeRegister", "FetchBufferRegister", "FetchEmbedded", + "FloatMode", "IeeeMode", "PositionExportControl", "ScratchDwords", "Stage", "StartInstanceUserData", "Tessellation"], + Names(typeof(VertexInputInfo))); + Assert.Equal(["CustomInterpolationMask", "DepthExportEnable", "DepthExportFormat", "Dx10Clamp", "EarlyDepth", "ExecuteOnNoop", + "FloatMode", "FrontFace", "FrontFaceAllBits", "GuestWave32", "IeeeMode", "InputCount", "InterpolatorSettings", "KillEnable", + "NoPerspective", "PerspectiveCenterRegister", "PositionW", "PositionX", "PositionY", "PositionZ", "SampleMaskExportEnable", + "SampleShading", "ScratchDwords", "Stage", "StencilExportEnable", "SystemInputBase", "TargetExportFormats", + "TargetExportMappings", "TargetOutputModes"], Names(typeof(PixelInputInfo))); + Assert.Equal(["CallArguments", "CallRecordRanges", "CallRecords", "CallTargets", "MeshDraw", "Program", "Resources", "ShaderBase", + "TessellationData", "ThreadLimits"], Names(typeof(ShaderStageResources))); + // Origin and BindingPacket are the snapshot's bookkeeping, not what the draw binds. + Assert.Equal(["BindingPacket", "BindlessImages", "Buffers", "DeviceAddressRanges", "FlattenedResourceTable", "Images", + "MipStatistics", "Origin", "Samplers", "UserData"], Names(typeof(ResourceSnapshot))); + } +} diff --git a/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/KeptStageInputsTests.cs b/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/KeptStageInputsTests.cs index 92c093e0a..35d02f20e 100644 --- a/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/KeptStageInputsTests.cs +++ b/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/KeptStageInputsTests.cs @@ -16,7 +16,7 @@ namespace SharpEmu.Libs.Tests.Gpu.Pipelines; [Collection(SchedulingStateCollection.Name)] -public sealed class KeptStageInputsTests : IDisposable +public sealed partial class KeptStageInputsTests : IDisposable { private const ulong VertexAddress = PipelineTestGuest.MemoryBase + 0x1000; private const ulong VertexHeader = PipelineTestGuest.MemoryBase + 0x8000; @@ -46,7 +46,8 @@ public sealed class KeptStageInputsTests : IDisposable public KeptStageInputsTests() { - _cache = new ShaderPipelineCache(_guest.Context, _guest.Host, _guest.Compiler, _guest.Registry); + // The kept programs of the last draw are what these tests check; the resolve memo replaces them when on. + _cache = new ShaderPipelineCache(_guest.Context, _guest.Host, _guest.Compiler, _guest.Registry) { ResolveMemoMode = ResolveMemoMode.Off }; WriteQword(UserDataBlock, DirectOffsets); WriteHalf(UserDataBlock + 0x2C, (ushort)DirectResourceCount); for (uint type = 0; type < DirectResourceCount; type++) From 4d6cef4fbc8ebbe1be81ea53637e7327084022a6 Mon Sep 17 00:00:00 2001 From: kuba Date: Sun, 15 Nov 2026 10:36:10 +0000 Subject: [PATCH 057/178] [GPU] Spin the idle program resolver briefly before it sleeps The next draw is usually submitted within microseconds; 32 SpinOnce before the queue wait save the submitter a kernel wake per job. idle_spin_takes counts the spins that found work. SHARPEMU_RESOLVER_IDLE_SPIN=0 sleeps at once as before. The DS-shaped bench records the kept programs and resolve memo report. --- .../Gpu/Rendering/ParallelProgramPrefetch.cs | 33 ++++++++++++++++++- .../Scenes/DsDrawCostBenchTests.cs | 13 +++++++- 2 files changed, 44 insertions(+), 2 deletions(-) diff --git a/src/SharpEmu.Libs/Gpu/Rendering/ParallelProgramPrefetch.cs b/src/SharpEmu.Libs/Gpu/Rendering/ParallelProgramPrefetch.cs index 02704cb09..4f279f4de 100644 --- a/src/SharpEmu.Libs/Gpu/Rendering/ParallelProgramPrefetch.cs +++ b/src/SharpEmu.Libs/Gpu/Rendering/ParallelProgramPrefetch.cs @@ -407,7 +407,13 @@ private void NoteUnresolvedTake(Job job) // The resolving thread's idle time in its queue wait and its wakes from it, its time spinning and sleeping on job // gates, the bytes it allocated per job (sampled every AllocationSamplePeriod jobs), and its CPU time. - private long _idleTicks, _gateTicks, _idleWakes, _sampledBytes, _sampledJobs, _resolverJobs; + private long _idleTicks, _gateTicks, _idleWakes, _idleSpinTakes, _sampledBytes, _sampledJobs, _resolverJobs; + + // SHARPEMU_RESOLVER_IDLE_SPIN=0: the idle worker sleeps at once, as before. + private static readonly bool IdleSpin = SharpEmu.ShaderCompiler.PerfSwitches.Enabled("SHARPEMU_RESOLVER_IDLE_SPIN"); + private const int IdleSpins = 32; + + private bool WorkReadyHint() => Volatile.Read(ref _stopping) || (_queue.Count != 0 && !Volatile.Read(ref _running)); private const int AllocationSamplePeriod = 64; private ulong _resolverThreadId; private long _lastResolverCpu = -1; @@ -425,6 +431,7 @@ public string TakeResolverReport() $"queued={Interlocked.Exchange(ref _unresolvedQueued, 0)}) resolver_jobs={Interlocked.Exchange(ref _resolverJobs, 0)} " + $"resolver_idle_ms={Milliseconds(Interlocked.Exchange(ref _idleTicks, 0)).ToString("F1", culture)} " + $"gate_sleep_ms={Milliseconds(Interlocked.Exchange(ref _gateTicks, 0)).ToString("F1", culture)} idle_wakes={Interlocked.Exchange(ref _idleWakes, 0)} " + + $"idle_spin_takes={Interlocked.Exchange(ref _idleSpinTakes, 0)} " + $"alloc_b_per_job={(sampledJobs == 0 ? 0 : sampledBytes / (double)sampledJobs).ToString("F0", culture)} " + $"resolver_cpu_ms={cpuMs.ToString("F1", culture)}"; } @@ -592,6 +599,30 @@ private void Run() if ((_queue.Count == 0 || _running) && !_stopping) { var idleStarted = System.Diagnostics.Stopwatch.GetTimestamp(); + if (IdleSpin) + { + // The next draw is usually submitted within microseconds: spin a little before sleeping, which + // costs the submitter a kernel wake per job. The checks outside the lock are hints only. + Monitor.Exit(_lock); + try + { + var spinner = new SpinWait(); + for (var spin = 0; spin < IdleSpins && !WorkReadyHint(); spin++) + { + spinner.SpinOnce(sleep1Threshold: -1); + } + } + finally + { + Monitor.Enter(_lock); + } + + if ((_queue.Count != 0 && !_running) || _stopping) + { + _idleSpinTakes++; + } + } + while ((_queue.Count == 0 || _running) && !_stopping) { _idleForJobs = true; diff --git a/tests/SharpEmu.Gpu.Metal.Tests/Scenes/DsDrawCostBenchTests.cs b/tests/SharpEmu.Gpu.Metal.Tests/Scenes/DsDrawCostBenchTests.cs index 71ab5cbc2..2ca95dae2 100644 --- a/tests/SharpEmu.Gpu.Metal.Tests/Scenes/DsDrawCostBenchTests.cs +++ b/tests/SharpEmu.Gpu.Metal.Tests/Scenes/DsDrawCostBenchTests.cs @@ -205,6 +205,10 @@ private static uint[] TablePixel(int targets) private static readonly MethodInfo PrefetchCounters = typeof(MetalRenderHost).GetMethod("FormatPrefetchCounters", BindingFlags.Instance | BindingFlags.NonPublic)!; + private static readonly MethodInfo KeptProgramsReport = + typeof(SharpEmu.Libs.Gpu.Rendering.GraphicsPrograms).Assembly.GetType("SharpEmu.Libs.Gpu.Pipelines.ShaderPipelineCache")! + .GetMethod("TakeKeptProgramsReport", BindingFlags.Static | BindingFlags.Public)!; + private static readonly MethodInfo ReadBindingCounters = typeof(MetalRenderHost).GetMethod("TakeReadBindingCounters", BindingFlags.Instance | BindingFlags.NonPublic)!; @@ -596,7 +600,11 @@ ulong DispatchTable(int dispatch, ulong writeBuffer) var collections = 0; for (var round = 0; round < warm + rounds; round++) { - if (round == warm) _ = PrefetchCounters.Invoke(rig.Host, null); + if (round == warm) + { + _ = PrefetchCounters.Invoke(rig.Host, null); + _ = KeptProgramsReport.Invoke(null, null); + } RenderPasses.SetValue(rig.Host, 0L); var before = profiling ? phases.Select(phase => PhaseTicks(phase)).ToArray() : null; if (gameStreams is null) rig.Host.CommandStream.EnqueueGraphics(streamAddress, (uint)words.Length, ++submissionId, null); @@ -648,6 +656,8 @@ ulong DispatchTable(int dispatch, ulong writeBuffer) } var prefetch = (string)PrefetchCounters.Invoke(rig.Host, null)!; + // The kept programs and resolve memo of the measured rounds ([PERF][KEPT_PROGRAMS]). + var kept = (string)KeptProgramsReport.Invoke(null, null)!; // Read-only bindings answered from the one before (MetalReadBindingMemo) over every round, warm-up included. var bindings = (string)ReadBindingCounters.Invoke(rig.Host, null)!; var checksum = 0xCBF29CE484222325UL; @@ -691,6 +701,7 @@ void Fold(ulong address, int count) gen0CollectionsPerThousandItems = collections * 1000.0 / (rounds * items), checksum = $"{checksum:X16}", counters = prefetch, + kept, bindings, phaseMicroseconds = phaseTotals.Where(pair => pair.Value / rounds >= 0.005) .OrderByDescending(pair => pair.Value).ToDictionary(pair => pair.Key, pair => Math.Round(pair.Value / rounds, 3)), From bbb6b3205409e81f722aaa4ecbfa0326d7c5266e Mon Sep 17 00:00:00 2001 From: kuba Date: Sun, 15 Nov 2026 10:54:28 +0000 Subject: [PATCH 058/178] [Metal] Read-binding memo v2: free an entry that can never answer again A retired window, a renewed window buffer or an image-set change over the range is permanent for the entry: left in its way it kept the window and the images it held alive until the way was evicted. The entry is freed where the miss is counted (released= on the PERF line), and a store takes a free way before it evicts. --- .../V2/MetalReadBindingMemoV2.cs | 29 ++++++++++++++++--- .../MetalRenderHost.ReadBindingMemoRanges.cs | 4 +++ 2 files changed, 29 insertions(+), 4 deletions(-) diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalReadBindingMemoV2.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalReadBindingMemoV2.cs index a2bbc224f..752583356 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalReadBindingMemoV2.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalReadBindingMemoV2.cs @@ -72,7 +72,7 @@ public MetalReadBindingMemoV2(int sets = 0) _sides = new Side[sets * Ways]; } - public long Hits, Misses, Stores, Verified, Evictions; + public long Hits, Misses, Stores, Verified, Evictions, Released; // One per miss, the first check that failed (they add up to Misses). public long MissEmpty, MissOtherKey, MissAlias, MissWindowRetired, MissWindowBuffer, MissTrap; @@ -90,6 +90,18 @@ public MetalReadBindingMemoV2(int sets = 0) private static byte FlagsOf(bool compute) => (byte)(FlagValid | (compute ? FlagCompute : 0)); + /// + /// Frees an entry that can never answer again (its window left the partition or changed its buffer, the images + /// over its range changed): left in place it would keep the window and the images it holds alive until its way + /// was evicted. + /// + public void Release(int index) + { + _entries[index] = default; + _sides[index] = default; + Released++; + } + /// The entry at an index or returned. public ref Entry At(int index) => ref _entries[index]; @@ -151,9 +163,18 @@ public int Insert(ulong address, uint size, bool compute) } } + // A free way first (never filled, or released), otherwise the set's least recently used entry. + for (var way = 0; way < Ways && found < 0; way++) + { + if (_entries[first + way].Flags == 0) + { + found = way; + } + } + if (found < 0) { - Evictions += _entries[first + Ways - 1].Flags != 0 ? 1 : 0; + Evictions++; found = Ways - 1; } @@ -181,7 +202,7 @@ private void MoveToFront(int first, int way) /// The counters since the last call (the PERF line's read_binding_memo); resets them. public string TakeCounters() { - var text = $"ranges=1 hits={Hits} misses={Misses} stores={Stores} verified={Verified} evictions={Evictions} " + + var text = $"ranges=1 hits={Hits} misses={Misses} stores={Stores} verified={Verified} evictions={Evictions} released={Released} " + $"miss_by=(empty={MissEmpty},other_key={MissOtherKey},alias={MissAlias},window_retired={MissWindowRetired}," + $"window_buffer={MissWindowBuffer},trap={MissTrap},image_pages={MissImagePages},image_set={MissImageSet}," + $"image_gpu_modified={MissImageGpuModified}) " + @@ -191,7 +212,7 @@ public string TakeCounters() $"hits_new_cb={HitsNewCommandBuffer} hits_with_pending={HitsWithPending} " + $"store_skip=(flushed={StoreSkipFlushed},image_many={StoreSkipImageMany},not_in_place={StoreSkipNotInPlace}," + $"retired_after={StoreSkipRetiredAfter},large={StoreSkipLarge})"; - Hits = Misses = Stores = Verified = Evictions = 0; + Hits = Misses = Stores = Verified = Evictions = Released = 0; MissEmpty = MissOtherKey = MissAlias = MissWindowRetired = MissWindowBuffer = MissTrap = 0; MissImagePages = MissImageSet = MissImageGpuModified = 0; RefusedTrace = RefusedUnmapped = RefusedWindow = RefusedFill = RefusedLabel = RefusedStaged = 0; diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.ReadBindingMemoRanges.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.ReadBindingMemoRanges.cs index 4aa0e20b7..69faaadde 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.ReadBindingMemoRanges.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.ReadBindingMemoRanges.cs @@ -66,11 +66,13 @@ private bool TryReadBindingMemoRanges(ulong address, ulong size, bool computeSta var window = entry.Window!; if (Volatile.Read(ref window.Retired)) { + memo.Release(index); return MissReadBinding(ref memo.MissWindowRetired); } if (window.Buffer != entry.Buffer) { + memo.Release(index); return MissReadBinding(ref memo.MissWindowBuffer); } @@ -108,6 +110,7 @@ private bool TryReadBindingMemoRanges(ulong address, ulong size, bool computeSta { if (!_imageCache.ImageSetUnchangedOver(entry.ImageSet, address, size, out var now)) { + memo.Release(index); return MissReadBinding(ref memo.MissImageSet); } @@ -145,6 +148,7 @@ private bool TryReadBindingMemoRanges(ulong address, ulong size, bool computeSta if (!_guestMemory.UseWindowForHit(window, out var touched)) { + memo.Release(index); return MissReadBinding(ref memo.MissWindowRetired); } From 4ef42bc4460d5940d3fd081ccf3d2982f3af67c9 Mon Sep 17 00:00:00 2001 From: kuba Date: Sun, 15 Nov 2026 12:50:00 +0000 Subject: [PATCH 059/178] [GPU] Resolve memo: a store whose key was refilled by a nested resolution is dropped, not stored under the other draw's key --- src/SharpEmu.Libs/Gpu/Pipelines/GraphicsResolveMemo.cs | 9 +++++++-- src/SharpEmu.Libs/Gpu/Pipelines/ShaderPipelineCache.cs | 9 ++++++++- 2 files changed, 15 insertions(+), 3 deletions(-) diff --git a/src/SharpEmu.Libs/Gpu/Pipelines/GraphicsResolveMemo.cs b/src/SharpEmu.Libs/Gpu/Pipelines/GraphicsResolveMemo.cs index 0efff5420..b8b5846d5 100644 --- a/src/SharpEmu.Libs/Gpu/Pipelines/GraphicsResolveMemo.cs +++ b/src/SharpEmu.Libs/Gpu/Pipelines/GraphicsResolveMemo.cs @@ -57,8 +57,8 @@ internal enum ResolveMemoUncacheable Origin, // A user data count over the bank (the full resolution stops on it). Key, - // A program entry, the device data loads or the vertex table metadata changed while the draw resolved, or its - // vertex source is not the draw's. + // A program entry, the device data loads or the vertex table metadata changed while the draw resolved, its vertex + // source is not the draw's, or another draw's key was filled while it resolved. Changed, Count, } @@ -137,11 +137,16 @@ public GraphicsResolveMemo(ResolveMemoMode mode, int capacity) public ReadOnlySpan Key => _key.AsSpan(0, _keyLength); + // How many keys were filled: a store belongs to the key filled before its resolution only while this has not moved + // (a guest read inside a resolution can resolve another draw on the same thread, which fills its own key). + public long FillSerial { get; private set; } + // The draw's key: every register and draw input the resolution reads, the user data words last. False when the user // data count is over the bank (the full resolution stops there). public bool Fill(RegisterBanks banks, ReadOnlySpan targetExportMapping, in KeptGraphicsFlags flags, PixelOutputBlendBits blendBits) { + FillSerial++; var key = _key.AsSpan(); var at = 0; var vertex = banks.Shader.Vertex; diff --git a/src/SharpEmu.Libs/Gpu/Pipelines/ShaderPipelineCache.cs b/src/SharpEmu.Libs/Gpu/Pipelines/ShaderPipelineCache.cs index 4e549df48..4308f2673 100644 --- a/src/SharpEmu.Libs/Gpu/Pipelines/ShaderPipelineCache.cs +++ b/src/SharpEmu.Libs/Gpu/Pipelines/ShaderPipelineCache.cs @@ -396,6 +396,7 @@ private GraphicsPrograms ResolveThroughMemo(GraphicsResolveMemo memo, RegisterBa in KeptGraphicsFlags flags) { var cacheable = false; + var fillSerial = 0L; if (_registry.HasFrontend) { GraphicsResolveMemo.NoteUncacheable(ResolveMemoUncacheable.Frontend); @@ -411,6 +412,7 @@ private GraphicsPrograms ResolveThroughMemo(GraphicsResolveMemo memo, RegisterBa else { cacheable = true; + fillSerial = memo.FillSerial; if (memo.Find() is { } entry) { if (TryTakeResolveMemo(entry, flags.PixelActive) is not { } miss) @@ -439,7 +441,12 @@ private GraphicsPrograms ResolveThroughMemo(GraphicsResolveMemo memo, RegisterBa var linkedLookups = _programs.LinkedLookups; var tablesGeneration = _vertexTables.Generation; var programs = ResolveFull(banks, targetExportMapping, flags); - if (cacheable) + if (cacheable && memo.FillSerial != fillSerial) + { + // The memo holds another draw's key now: this result has no key to be stored under. + GraphicsResolveMemo.NoteUncacheable(ResolveMemoUncacheable.Changed); + } + else if (cacheable) { StoreResolveMemo(memo, banks, programs, flags.PixelActive, deviceDataGeneration, contentEpoch, linkedLookups, tablesGeneration); } From 5c9e38feb56c6b0b1d57336d2940aaad367f725b Mon Sep 17 00:00:00 2001 From: kuba Date: Sun, 15 Nov 2026 13:07:16 +0000 Subject: [PATCH 060/178] [Metal] Layered deferral: an array target whose stale layers are not under its view does not wait for its pass A GPU-written array stale over some layers left its upload to the pass on every target acquire, also when no stale byte was under the view's layers. A waiting attachment cannot continue a pass, so every draw into a Demon's Souls shadow cascade ended the pass before it while a later cascade was still stale: ~525 extra passes a frame (run r3-hle: end_target 362 -> 9032 per 2 s, GPU busy 70 -> 92 ms/frame). Those layers now stay stale at the acquire, as the pass would have left them, and nothing waits. --- .../SharpEmu.Gpu.Metal/V2/MetalCachedImage.cs | 23 ++++++- .../V2/MetalImageCache.AliasTransitions.cs | 2 +- .../V2/MetalImageCache.DeferredRefresh.cs | 51 +++++++++++--- .../SharpEmu.Gpu.Metal/V2/MetalImageCache.cs | 30 +++++++-- .../MetalDeferredRefreshTests.cs | 67 +++++++++++++++++++ 5 files changed, 157 insertions(+), 16 deletions(-) diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalCachedImage.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalCachedImage.cs index ba392381e..9d60b117d 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalCachedImage.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalCachedImage.cs @@ -1001,7 +1001,16 @@ public void RefreshComplete(ulong start, ulong end) /// /// False for a depth-stencil target the GPU writes only the stencil of. /// - public void MarkGpuModified(bool depthPlaneChanged = true) + public void MarkGpuModified(bool depthPlaneChanged = true) => MarkGpuModified(depthPlaneChanged, keepStale: false); + + /// + /// As for a write that touches no stale byte: every stale run stays as it + /// is (MetalImageCache.TryKeepOtherLayersStaleLocked), so nothing about how the image binds moves with it. + /// + public void MarkGpuModifiedKeepingStale(bool depthPlaneChanged = true) => + MarkGpuModified(depthPlaneChanged, keepStale: true); + + private void MarkGpuModified(bool depthPlaneChanged, bool keepStale) { // Every write path gives a texture held from a later level the whole chain first // (MetalImageCache.PromoteLinearView): a writeback of a cut texture would retile its @@ -1030,8 +1039,16 @@ public void MarkGpuModified(bool depthPlaneChanged = true) // after this (MetalImageCache.CompleteDeferredLocked). ClaimPendingWriteback(); _gpuModified = true; - _cpuDirty = false; - _staleCount = 0; + if (keepStale) + { + wasDirty = false; + } + else + { + _cpuDirty = false; + _staleCount = 0; + } + _publishedCount = 0; GpuWriteSequence = Interlocked.Increment(ref _gpuWriteCounter); if (!wasModified) diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.AliasTransitions.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.AliasTransitions.cs index b4d812114..be1487295 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.AliasTransitions.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.AliasTransitions.cs @@ -75,7 +75,7 @@ internal string TakeAliasTransitionText() $"alias_moved_mib=[wb:{Mb(Interlocked.Exchange(ref _aliasMovedWritebackBytes, 0))}," + $"blit:{Mb(Interlocked.Exchange(ref _aliasMovedBlitBytes, 0))}] " + $"alias_run_refresh_refused={Interlocked.Exchange(ref _aliasRunRefreshRefused, 0)} {TakeAliasRunText()} " + - $"layer_refresh_skipped=[{layerSkips.Layers},{Mb(layerSkips.Bytes)}] " + + $"layer_refresh_skipped=[{layerSkips.Layers},{Mb(layerSkips.Bytes)}] layer_stale_kept={TakeLayerStaleKept()} " + $"alias_subset_verify=[checked:{Interlocked.Exchange(ref _aliasSubsetVerified, 0)}," + $"mismatch:{Interlocked.Read(ref _aliasSubsetMismatches)},unverified:{Interlocked.Exchange(ref _aliasSubsetUnverified, 0)}] " + $"alias_transition_refused=[{refusals}] alias_cpu_read_runs={readRuns} " + diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.DeferredRefresh.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.DeferredRefresh.cs index 7b7789b88..895919215 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.DeferredRefresh.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.DeferredRefresh.cs @@ -376,15 +376,9 @@ private bool TryLeaveOtherLayersStale( // What stays stale is refreshed later by TryRefreshDirtyRun alone (a GPU-written image is never uploaded // whole): each run must be one that refresh makes exactly, and one it can read in place. Anything else uploads // now, as before, rather than leave the stale keep in RefreshFromGuestCore runs it did not have. - foreach (var (start, end) in left[..count]) + if (!StaleRunsCanWait(image, left[..count])) { - if (!SubRangeTransfersEnabled || - !TryCoveringRun(in image.Description, start, end, out var runStart, out var runEnd) || - runStart != start || runEnd != end || - !_guestMemory.TryResolveInPlace(image.Description.Data.Address + start, end - start, out _)) - { - return false; - } + return false; } if (overlaps) @@ -411,6 +405,47 @@ private bool TryLeaveOtherLayersStale( return true; } + // Whether each of these runs is one TryRefreshDirtyRun makes exactly and can read in place. + private bool StaleRunsCanWait(MetalCachedImage image, ReadOnlySpan<(ulong Start, ulong End)> runs) + { + foreach (var (start, end) in runs) + { + if (!SubRangeTransfersEnabled || + !TryCoveringRun(in image.Description, start, end, out var runStart, out var runEnd) || + runStart != start || runEnd != end || + !_guestMemory.TryResolveInPlace(image.Description.Data.Address + start, end - start, out _)) + { + return false; + } + } + + return true; + } + + private long _layerStaleKept; + + /// Target acquires that left an array's other layers stale without waiting for the pass. + internal long TakeLayerStaleKept() => Interlocked.Exchange(ref _layerStaleKept, 0); + + // A GPU-written array target none of whose stale runs is over the view's layers has nothing for its pass to + // decide: the pass can neither overwrite nor read those bytes, so they stay stale under the write exactly as + // CompleteDeferredLocked would leave them, and nothing waits. Waiting here made every draw into a Demon's Souls + // shadow cascade end the pass before it (a pass is not continued while an attachment waits for its upload) for + // as long as a later cascade was still stale. Caller holds the lock and marks the image written with + // MarkGpuModifiedKeepingStale. + private bool TryKeepOtherLayersStaleLocked(MetalCachedImage image, uint baseLayer, uint layerCount) + { + if (!CanDeferLayerRefresh(image) || + !_transfer.TryLayerBytes(in image.Description, baseLayer, layerCount, out var viewStart, out var viewEnd) || + image.StaleOverlaps(viewStart, viewEnd) || !StaleRunsCanWait(image, image.StaleRuns)) + { + return false; + } + + Interlocked.Increment(ref _layerStaleKept); + return true; + } + // A released image's upload no longer has a texture to land in. Caller holds the lock. private void ForgetDeferredRefreshesLocked(MetalCachedImage image) { diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.cs index cb1825cfd..128838ef9 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.cs @@ -1815,7 +1815,10 @@ public nint AcquireColorTargetView( // The pass about to begin may clear or overwrite all of it; BeginRendering decides // whether the upload is worth making (MetalImageCache.DeferredRefresh). var defer = deferRefresh && (CanDeferRefresh(image) || CanDeferLayerRefresh(image)); - if (!defer) + // Stale layers the view does not name need no pass to decide them: they stay stale and nothing waits. + var keepStale = defer && TryKeepOtherLayersStaleLocked(image, request.View.BaseLayer, request.View.LayerCount); + defer &= !keepStale; + if (!defer && !keepStale) { RefreshFromGuest(image); } @@ -1845,7 +1848,15 @@ public nint AcquireColorTargetView( return deferredView; } - image.MarkGpuModified(); + if (keepStale) + { + image.MarkGpuModifiedKeepingStale(); + } + else + { + image.MarkGpuModified(); + } + NoteLinearGpuWrite(image); image.GpuWriteSerial = _owner.CurrentSerial; image.NoteUse(image.GpuWriteSerial); @@ -1895,7 +1906,10 @@ public nint AcquireDepthTargetView( // refreshes now, before the description changes. var defer = deferRefresh && writes && (CanDeferRefresh(image) || CanDeferLayerRefresh(image)) && (!request.Description.HasStencil || stencil == image.Description.Stencil); - if (!defer) + // As for a colour target: stale layers the view does not name stay stale and nothing waits. + var keepStale = defer && TryKeepOtherLayersStaleLocked(image, request.View.BaseLayer, request.View.LayerCount); + defer &= !keepStale; + if (!defer && !keepStale) { RefreshFromGuest(image); } @@ -1936,7 +1950,15 @@ public nint AcquireDepthTargetView( if (writes) { - image.MarkGpuModified(depthPlaneChanged: !stencilOnly); + if (keepStale) + { + image.MarkGpuModifiedKeepingStale(depthPlaneChanged: !stencilOnly); + } + else + { + image.MarkGpuModified(depthPlaneChanged: !stencilOnly); + } + NoteLinearGpuWrite(image); image.GpuWriteSerial = _owner.CurrentSerial; } diff --git a/tests/SharpEmu.Gpu.Metal.Tests/MetalDeferredRefreshTests.cs b/tests/SharpEmu.Gpu.Metal.Tests/MetalDeferredRefreshTests.cs index e67ab5aae..34139b9ad 100644 --- a/tests/SharpEmu.Gpu.Metal.Tests/MetalDeferredRefreshTests.cs +++ b/tests/SharpEmu.Gpu.Metal.Tests/MetalDeferredRefreshTests.cs @@ -186,6 +186,73 @@ public void ALayerSampledBeforeItsClearIsUploadedFirst() Assert.Equal(2, on.Dropped); } + // Layer 0 is cleared with layers 1-3 stale, then drawn into again, as each draw into a shadow cascade is: the + // second acquire has nothing for a pass to decide (no stale byte is under its layer), so nothing waits - a + // waiting attachment ends the open pass - the other layers stay stale, and nothing is uploaded. + [Fact] + public void ADrawIntoAClearedLayerDoesNotWaitWhileOtherLayersAreStale() + { + if (!RequireDevice()) return; + if (!MetalV2Diagnostics.SkipOverwrittenRefresh) return; + using var rig = new Rig(Device.Value); + var host = rig.Host; + var size = ArrayLayerBytes() * ArrayLayers; + ResourceSlotIdentifier image; + using (host.BeginPreparation()) + { + var request = DepthArrayRequest(0, ImageRole.DepthTarget); + image = host.ImageCache.FindImage(ref request); + } + + // Round one makes the array GPU-written; the guest then rewrites all of it. + foreach (var layer in new uint[] { 0, 1, 2, 3 }) + { + using (host.BeginPreparation()) + { + var acquisition = ((IRenderHost)host).AcquireDepthAttachment(DepthArrayTarget(image, layer, clear: true)); + host.BeginRendering(DepthPass(acquisition.View, FirstClear)); + host.EndRendering(); + } + } + + _ = rig.Read(ArrayAddress, size); + rig.FillBacking(ArrayAddress, size, LaterPattern); + host.ImageCache.InvalidateMemory(ArrayAddress, size); + var uploads = host.ImageCache.Counters.Uploads; + _ = host.ImageCache.TakeLayerStaleKept(); + var layerBytes = ArrayLayerBytes(); + using (host.BeginPreparation()) + { + var acquisition = ((IRenderHost)host).AcquireDepthAttachment(DepthArrayTarget(image, 0, clear: true)); + Assert.True(host.ImageCache.HasDeferredRefreshes); + host.BeginRendering(DepthPass(acquisition.View, SecondClear)); + Assert.False(host.ImageCache.HasDeferredRefreshes); + + var cached = host.ImageCache.GetImage(image); + Assert.True(cached.IsCpuDirty); + var stale = cached.StaleRuns.ToArray(); + var binding = cached.BindingVersion; + for (var draw = 0; draw < 3; draw++) + { + var again = ((IRenderHost)host).AcquireDepthAttachment(DepthArrayTarget(image, 0, clear: false)); + Assert.Equal(acquisition.View, again.View); + Assert.False(host.ImageCache.HasDeferredRefreshes); + Assert.True(cached.IsGpuModified); + Assert.Equal(stale, cached.StaleRuns.ToArray()); + Assert.Equal(binding, cached.BindingVersion); + } + + Assert.False(cached.StaleOverlaps(0, layerBytes)); + Assert.True(cached.IsStaleOver(layerBytes, size)); + host.EndRendering(); + } + + Assert.Equal(3, host.ImageCache.TakeLayerStaleKept()); + Assert.Equal(uploads, host.ImageCache.Counters.Uploads); + // Layer 0 holds the clear; the layers no pass touched are the guest's later bytes, uploaded only by the read. + AssertLayers(rig.Read(ArrayAddress, size), [0], SecondClear); + } + private sealed record LayerOutcome(byte[] Round1, byte[] Round2, long Uploads, long Dropped, List Sampled); private LayerOutcome RunLayerClears(uint[] order, bool layerDefer, uint? sampleBeforeClear) From 218f56a428da5376e1ef65207366c2ec0cd71333 Mon Sep 17 00:00:00 2001 From: kuba Date: Sun, 15 Nov 2026 13:17:44 +0000 Subject: [PATCH 061/178] [GPU] Graphics resolve counters (kept, resolved, resolve memo) on the always-on prefetch counter line --- src/SharpEmu.Libs/Gpu/Pipelines/GraphicsResolveMemo.cs | 2 +- src/SharpEmu.Libs/Gpu/Pipelines/ShaderPipelineCache.cs | 10 ++++++++-- .../Gpu/Rendering/ParallelProgramPrefetch.cs | 3 ++- .../Scenes/DsDrawCostBenchTests.cs | 2 +- 4 files changed, 12 insertions(+), 5 deletions(-) diff --git a/src/SharpEmu.Libs/Gpu/Pipelines/GraphicsResolveMemo.cs b/src/SharpEmu.Libs/Gpu/Pipelines/GraphicsResolveMemo.cs index b8b5846d5..b746703a6 100644 --- a/src/SharpEmu.Libs/Gpu/Pipelines/GraphicsResolveMemo.cs +++ b/src/SharpEmu.Libs/Gpu/Pipelines/GraphicsResolveMemo.cs @@ -386,7 +386,7 @@ public Entry Store() private static string Take(ThreadCounter[] counters, params string[] names) => string.Join(",", names.Select((name, index) => FormattableString.Invariant($"{name}={counters[index].Take()}"))); - // The resolve_memo=(...) part of [PERF][KEPT_PROGRAMS]; entries counts every live memo. + // The resolve_memo=(...) part of the prefetch counters (ShaderPipelineCache.TakeGraphicsResolveReport); entries counts every live memo. public static string TakeReport() => FormattableString.Invariant( $"resolve_memo=(mode={DefaultMode.ToString().ToLowerInvariant()},hits={_hits.Take()},would_hit={_shadowWouldHit.Take()},") + "miss_by=(" + Take(_misses, "new", "epoch", "header", "identity", "tables", "semantics", "words", "generation") + ")," + diff --git a/src/SharpEmu.Libs/Gpu/Pipelines/ShaderPipelineCache.cs b/src/SharpEmu.Libs/Gpu/Pipelines/ShaderPipelineCache.cs index 4308f2673..13e679003 100644 --- a/src/SharpEmu.Libs/Gpu/Pipelines/ShaderPipelineCache.cs +++ b/src/SharpEmu.Libs/Gpu/Pipelines/ShaderPipelineCache.cs @@ -745,8 +745,14 @@ private void ClaimKeptPrograms() private static readonly ThreadCounter _computeResolved = new(); public static string TakeKeptProgramsReport() => - FormattableString.Invariant($"[PERF][KEPT_PROGRAMS] graphics_kept={_graphicsKept.Take()} graphics_resolved={_graphicsResolved.Take()} ") + - FormattableString.Invariant($"compute_kept={_computeKept.Take()} compute_rebound={_computeRebound.Take()} compute_resolved={_computeResolved.Take()} ") + + FormattableString.Invariant($"[PERF][KEPT_PROGRAMS] compute_kept={_computeKept.Take()} compute_rebound={_computeRebound.Take()} compute_resolved={_computeResolved.Take()}"); + + /// + /// How graphics resolutions were answered since the last call, for the backend's always-on counter line (the + /// prefetch report): by the draw's own kept programs, by a full resolution, and what the resolve memo did. + /// + public static string TakeGraphicsResolveReport() => + FormattableString.Invariant($"graphics_kept={_graphicsKept.Take()} graphics_resolved={_graphicsResolved.Take()} ") + GraphicsResolveMemo.TakeReport(); // Besides upstream's register stamps, the fork's resolution reads the host viewport transform (dynamic diff --git a/src/SharpEmu.Libs/Gpu/Rendering/ParallelProgramPrefetch.cs b/src/SharpEmu.Libs/Gpu/Rendering/ParallelProgramPrefetch.cs index 4f279f4de..3ac5acd53 100644 --- a/src/SharpEmu.Libs/Gpu/Rendering/ParallelProgramPrefetch.cs +++ b/src/SharpEmu.Libs/Gpu/Rendering/ParallelProgramPrefetch.cs @@ -433,7 +433,8 @@ public string TakeResolverReport() $"gate_sleep_ms={Milliseconds(Interlocked.Exchange(ref _gateTicks, 0)).ToString("F1", culture)} idle_wakes={Interlocked.Exchange(ref _idleWakes, 0)} " + $"idle_spin_takes={Interlocked.Exchange(ref _idleSpinTakes, 0)} " + $"alloc_b_per_job={(sampledJobs == 0 ? 0 : sampledBytes / (double)sampledJobs).ToString("F0", culture)} " + - $"resolver_cpu_ms={cpuMs.ToString("F1", culture)}"; + $"resolver_cpu_ms={cpuMs.ToString("F1", culture)} " + + SharpEmu.Libs.Gpu.Pipelines.ShaderPipelineCache.TakeGraphicsResolveReport(); } // The resolving thread's CPU time (user and system), or -1 where it cannot be read. diff --git a/tests/SharpEmu.Gpu.Metal.Tests/Scenes/DsDrawCostBenchTests.cs b/tests/SharpEmu.Gpu.Metal.Tests/Scenes/DsDrawCostBenchTests.cs index 2ca95dae2..c0a5510d0 100644 --- a/tests/SharpEmu.Gpu.Metal.Tests/Scenes/DsDrawCostBenchTests.cs +++ b/tests/SharpEmu.Gpu.Metal.Tests/Scenes/DsDrawCostBenchTests.cs @@ -656,7 +656,7 @@ ulong DispatchTable(int dispatch, ulong writeBuffer) } var prefetch = (string)PrefetchCounters.Invoke(rig.Host, null)!; - // The kept programs and resolve memo of the measured rounds ([PERF][KEPT_PROGRAMS]). + // The compute kept programs of the measured rounds; the graphics ones and the resolve memo are in the prefetch counters. var kept = (string)KeptProgramsReport.Invoke(null, null)!; // Read-only bindings answered from the one before (MetalReadBindingMemo) over every round, warm-up included. var bindings = (string)ReadBindingCounters.Invoke(rig.Host, null)!; From 94977e2991b7b32bf4c887b02a155c1c46e9362c Mon Sep 17 00:00:00 2001 From: kuba Date: Sun, 15 Nov 2026 13:39:35 +0000 Subject: [PATCH 062/178] [Tests] DS draw bench: GameWords variation with descriptor words and user-data keys changing between rounds --- .../Scenes/DsDrawCostBenchTests.cs | 46 ++++++++++++++++--- 1 file changed, 39 insertions(+), 7 deletions(-) diff --git a/tests/SharpEmu.Gpu.Metal.Tests/Scenes/DsDrawCostBenchTests.cs b/tests/SharpEmu.Gpu.Metal.Tests/Scenes/DsDrawCostBenchTests.cs index c0a5510d0..c64e45a6f 100644 --- a/tests/SharpEmu.Gpu.Metal.Tests/Scenes/DsDrawCostBenchTests.cs +++ b/tests/SharpEmu.Gpu.Metal.Tests/Scenes/DsDrawCostBenchTests.cs @@ -218,7 +218,7 @@ private static uint[] TablePixel(int targets) // CLOCK_THREAD_CPUTIME_ID: the recording thread's own CPU time. private static ulong ThreadCpuNanoseconds() => clock_gettime_nsec_np(16); - private enum Variation { Draws, Dispatches, GameShaped } + private enum Variation { Draws, Dispatches, GameShaped, GameWords } // GameShaped: the draw stream split into this many submissions a round, a command buffer committed about every // SubmissionsPerCommit of them (Demon's Souls: ~39 submissions and ~17.5 command buffers a frame). @@ -319,12 +319,14 @@ .. Descriptors.Buffer(color, 16, 6), .. Descriptors.Buffer(constants, 16, 2), Enumerable.Range(0, 4).Select(count => rig.Program(WithNops(TablePixel(attachments), count))).ToArray()).ToArray(); // One draw as DrawStream records it: a pass's first draw (or a submission's) sets the targets and depth. - void EmitDraw(ScenePm4 pm4, int draw, int pass, bool fullState, (ulong table, ulong indices, ulong arguments) mesh, ulong material) + void EmitDraw(ScenePm4 pm4, int draw, int pass, bool fullState, (ulong table, ulong indices, ulong arguments) mesh, ulong material, + ulong pixelConstantsAt = 0) { var attachments = pass % 2 == 0 ? 5 : 6; var set = pass % TargetSets; uint[] vertexData = [Descriptors.Lo(mesh.table), Descriptors.Hi(mesh.table), 0, 0, .. Descriptors.Buffer(objectConstants, 16, 4)]; - uint[] pixelData = [Descriptors.Lo(material), Descriptors.Hi(material), 0, 0, .. Descriptors.Buffer(pixelConstants, 16, 2)]; + uint[] pixelData = [Descriptors.Lo(material), Descriptors.Hi(material), 0, 0, + .. Descriptors.Buffer(pixelConstantsAt != 0 ? pixelConstantsAt : pixelConstants, 16, 2)]; var vertexProgram = vertexPrograms[(draw / 3) % vertexPrograms.Length]; var pixelProgram = pixelPrograms[attachments - 5][(draw / 2) % 4]; SceneState state; @@ -495,9 +497,19 @@ ulong DispatchTable(int dispatch, ulong writeBuffer) // four dispatches at the start of each pass storing four buffers that // the draws of four meshes read as their normals; and a texture on far pages dropped every third submission and // made again when sampled next (image-set changes). + // GameWords: GameShaped whose descriptor words change between rounds under unchanged keys, as Demon's Souls' + // per-frame constants do (resolve memo miss_by words ~32% of its draws, key_miss user_data_only ~8.5%): every + // third mesh's table points its constants V# at one of two zero buffers in turn, and every 32nd draw's pixel + // constants V# (user data) at a copy of the pixel constants that changes every round. Same image as GameShaped. var gameMeshCount = Setting("MESHES", 3000); var gameDrawCount = Setting("GAME_DRAWS", 7300); - (uint[][] Streams, ulong[] Written, ulong[] Churn) GameStreams() + const int PixelConstantCopies = 256; + var alternateConstants = rig.Memory.Upload(new float[8], 256); + var pixelConstantCopies = Enumerable.Range(0, PixelConstantCopies) + .Select(_ => rig.Memory.Upload([0.0625f, 0, 0, 0, 0, 0, 0, 0], 256)).ToArray(); + Assert.All(pixelConstantCopies, copy => Assert.Equal(Descriptors.Hi(pixelConstantCopies[0]), Descriptors.Hi(copy))); + (uint[][] Streams, ulong[] Written, ulong[] Churn, (ulong Address, uint[] Even, uint[] Odd)[] WordChurn, (int Stream, int Word)[] KeyChurn) + GameStreams(bool churnWords) { var gameMeshes = Enumerable.Range(0, gameMeshCount).Select(mesh => Mesh(mesh)).ToArray(); var written = Enumerable.Range(0, 4).Select(_ => rig.Memory.Upload(new uint[StorageEdge * StorageEdge], 256)).ToArray(); @@ -521,6 +533,12 @@ ulong DispatchTable(int dispatch, ulong writeBuffer) var streams = new uint[GameSubmissions][]; var passLength = (gameDrawCount + Passes - 1) / Passes; var labelWrites = 0; + var wordChurn = churnWords + ? gameMeshes.Where((_, index) => index % 3 == 0).Select(mesh => + (mesh.table + 0x40, rig.Read(mesh.table + 0x40, 4), Descriptors.Buffer(alternateConstants, 16, 2))).ToArray() + : []; + var keyChurn = new List<(int Stream, int Word)>(); + var keyChurnStarts = new List<(int Stream, int Start, int End)>(); ScenePm4? pm4 = null; var submission = -1; for (var draw = 0; draw <= gameDrawCount; draw++) @@ -557,7 +575,10 @@ ulong DispatchTable(int dispatch, ulong writeBuffer) var material = firstOfSubmission ? churnMaterials[submission % ChurnTextures] : materials[(draw * 11 + pass * 3) % Materials]; - EmitDraw(pm4!, draw, pass, passStart || firstOfSubmission, mesh, material); + var newKey = churnWords && draw % 32 == 7; + var emittedFrom = pm4!.Count; + EmitDraw(pm4!, draw, pass, passStart || firstOfSubmission, mesh, material, newKey ? pixelConstantCopies[0] : 0); + if (newKey) keyChurnStarts.Add((submission, emittedFrom, pm4!.Count)); var commitFollows = (int)((submission + 1) / SubmissionsPerCommit) != (int)(submission / SubmissionsPerCommit); if (commitFollows && draw % 6 == 5) { @@ -568,7 +589,15 @@ ulong DispatchTable(int dispatch, ulong writeBuffer) } } - return (streams, written, churn); + // The word of each such draw that holds its pixel constants' low address bits (found once in its packets). + foreach (var (stream, start, end) in keyChurnStarts) + { + var found = Enumerable.Range(start, end - start).Where(word => streams[stream][word] == Descriptors.Lo(pixelConstantCopies[0])).ToArray(); + Assert.Single(found); + keyChurn.Add((stream, found[0])); + } + + return (streams, written, churn, wordChurn, [.. keyChurn]); } var phases = Enum.GetValues().Where(phase => phase != RenderPhaseProfile.Phase.Count).ToArray(); @@ -577,7 +606,7 @@ ulong DispatchTable(int dispatch, ulong writeBuffer) ulong submissionId = 1000; foreach (var variation in Enum.GetValues().Where(variation => only is null || variation.ToString() == only)) { - var game = variation == Variation.GameShaped ? GameStreams() : default; + var game = variation is Variation.GameShaped or Variation.GameWords ? GameStreams(variation == Variation.GameWords) : default; var words = variation switch { Variation.Draws => DrawStream(), @@ -605,6 +634,9 @@ ulong DispatchTable(int dispatch, ulong writeBuffer) _ = PrefetchCounters.Invoke(rig.Host, null); _ = KeptProgramsReport.Invoke(null, null); } + foreach (var (address, even, odd) in game.WordChurn ?? []) rig.Memory.Write(address, round % 2 == 0 ? even : odd); + foreach (var (stream, word) in game.KeyChurn ?? []) + rig.Memory.Write32(gameStreams![stream].Address + (ulong)word * 4, Descriptors.Lo(pixelConstantCopies[round % PixelConstantCopies])); RenderPasses.SetValue(rig.Host, 0L); var before = profiling ? phases.Select(phase => PhaseTicks(phase)).ToArray() : null; if (gameStreams is null) rig.Host.CommandStream.EnqueueGraphics(streamAddress, (uint)words.Length, ++submissionId, null); From c65b5303ba1b049bdc35fa0ecc921cfd4f3a7f37 Mon Sep 17 00:00:00 2001 From: kuba Date: Sun, 15 Nov 2026 13:44:52 +0000 Subject: [PATCH 063/178] [GPU] Resolve memo: rebuild a words miss from its revalidation instead of resolving the draw again A memo entry whose key, header, identity, tables, semantics and generations match but whose descriptor words changed now takes the snapshot the full resolution would materialize, built from the revalidation's own evaluation (ResourceMaterializer.RevalidateOrRebuildFast), when the words keep the stage's specialization (so the permutation and program stay the entry's). Counters words_rebuilt= and rebuild_refused_by=(...) on the resolve_memo report; SHARPEMU_RESOLVE_MEMO_REBUILD=0 resolves every words miss in full. --- .../Gpu/Pipelines/GraphicsResolveMemo.cs | 33 +++++ .../Gpu/Pipelines/ShaderPipelineCache.cs | 112 +++++++++++++++- .../Gpu/Pipelines/ShaderProgramCache.cs | 38 ++++++ .../Resources/ResourceMaterializer.cs | 121 +++++++++++++++++- .../KeptStageInputsTests.ResolveMemo.cs | 58 +++++++++ 5 files changed, 348 insertions(+), 14 deletions(-) diff --git a/src/SharpEmu.Libs/Gpu/Pipelines/GraphicsResolveMemo.cs b/src/SharpEmu.Libs/Gpu/Pipelines/GraphicsResolveMemo.cs index b746703a6..d3d6c1746 100644 --- a/src/SharpEmu.Libs/Gpu/Pipelines/GraphicsResolveMemo.cs +++ b/src/SharpEmu.Libs/Gpu/Pipelines/GraphicsResolveMemo.cs @@ -63,6 +63,24 @@ internal enum ResolveMemoUncacheable Count, } +// Why a words miss was not rebuilt from its revalidation (ShaderPipelineCache.TryTakeResolveMemo) and resolved in full. +internal enum ResolveMemoRebuildRefusal +{ + // A snapshot of the materialization cache, which is revalidated only. + Origin, + // A reader that tells table words apart, or no program to evaluate. + Refused, + // The program could not evaluate the words. + Evaluate, + // The materialization from the evaluated words failed. + Failed, + // The words specialize the program otherwise. + Specialization, + // Device data loads were learned while the words were read. + Generation, + Count, +} + // The graphics programs of draws already resolved, keyed by everything their resolution reads from the registers and // the draw (ResolveKey), many per frame: a draw whose key matches an entry takes its programs once every guest read the // full resolution makes still gives the same answer (ShaderPipelineCache.TryTakeResolveMemo). Used under the pipeline @@ -75,6 +93,10 @@ internal sealed class GraphicsResolveMemo internal static readonly int DefaultCapacity = int.TryParse(Environment.GetEnvironmentVariable("SHARPEMU_RESOLVE_MEMO_ENTRIES"), out var entries) && entries >= 2 ? entries : 16384; + // SHARPEMU_RESOLVE_MEMO_REBUILD=0: an entry whose descriptor words changed resolves in full again instead of taking the + // snapshot its revalidation evaluated (ShaderPipelineCache.TryTakeResolveMemo). + internal static readonly bool DefaultRebuild = Environment.GetEnvironmentVariable("SHARPEMU_RESOLVE_MEMO_REBUILD") != "0"; + internal static ResolveMemoMode ParseMode(string? value) => value?.Trim().ToLowerInvariant() switch { "0" or "off" => ResolveMemoMode.Off, @@ -131,6 +153,9 @@ public GraphicsResolveMemo(ResolveMemoMode mode, int capacity) public ResolveMemoMode Mode { get; } + // Whether a words miss is rebuilt from its revalidation (DefaultRebuild; tests set it). + public bool Rebuild { get; set; } = DefaultRebuild; + public int Count => _count; public ulong Hash { get; private set; } @@ -358,6 +383,8 @@ public Entry Store() } private static readonly ThreadCounter _hits = new(); + private static readonly ThreadCounter _rebuilt = new(); + private static readonly ThreadCounter[] _rebuildRefused = NewCounters((int)ResolveMemoRebuildRefusal.Count); private static readonly ThreadCounter _evictions = new(); private static readonly ThreadCounter _entries = new(); private static readonly ThreadCounter _verifyChecked = new(); @@ -371,6 +398,10 @@ public Entry Store() public static void NoteHit() => _hits.Increment(); + public static void NoteRebuilt() => _rebuilt.Increment(); + + public static void NoteRebuildRefused(ResolveMemoRebuildRefusal cause) => _rebuildRefused[(int)cause].Increment(); + public static void NoteShadowHit() => _shadowWouldHit.Increment(); public static void NoteMiss(ResolveMemoMiss cause) => _misses[(int)cause].Increment(); @@ -390,6 +421,8 @@ private static string Take(ThreadCounter[] counters, params string[] names) => public static string TakeReport() => FormattableString.Invariant( $"resolve_memo=(mode={DefaultMode.ToString().ToLowerInvariant()},hits={_hits.Take()},would_hit={_shadowWouldHit.Take()},") + "miss_by=(" + Take(_misses, "new", "epoch", "header", "identity", "tables", "semantics", "words", "generation") + ")," + + FormattableString.Invariant($"words_rebuilt={_rebuilt.Take()},rebuild={(DefaultRebuild ? 1 : 0)},") + + "rebuild_refused_by=(" + Take(_rebuildRefused, "origin", "refused", "evaluate", "failed", "specialization", "generation") + ")," + "key_miss=(" + Take(_keyMisses, "new", "user_data_only", "regs_only") + ")," + "uncacheable_by=(" + Take(_uncacheable, "frontend", "mesh", "tess", "calls", "unavailable", "tables", "trace", "origin", "key", "changed") + ")," + FormattableString.Invariant($"evictions={_evictions.Take()},entries={_entries.Total},verify_checked={_verifyChecked.Take()},") + diff --git a/src/SharpEmu.Libs/Gpu/Pipelines/ShaderPipelineCache.cs b/src/SharpEmu.Libs/Gpu/Pipelines/ShaderPipelineCache.cs index 13e679003..6e0cedbe7 100644 --- a/src/SharpEmu.Libs/Gpu/Pipelines/ShaderPipelineCache.cs +++ b/src/SharpEmu.Libs/Gpu/Pipelines/ShaderPipelineCache.cs @@ -359,6 +359,19 @@ internal ResolveMemoMode ResolveMemoMode } } + // For tests: whether this cache's memo rebuilds a words miss from its revalidation (GraphicsResolveMemo.Rebuild). + internal bool ResolveMemoRebuild + { + get => _resolveMemo?.Rebuild ?? false; + set + { + lock (_resolveGate) + { + if (_resolveMemo is { } memo) memo.Rebuild = value; + } + } + } + // Shadow mode: counts whether the memo would have the draw's key; true when it has not and the key is to be stored // once the draw resolved. private bool ShadowResolveMemo(RegisterBanks banks, ReadOnlySpan targetExportMapping, in KeptGraphicsFlags flags) @@ -415,9 +428,19 @@ private GraphicsPrograms ResolveThroughMemo(GraphicsResolveMemo memo, RegisterBa fillSerial = memo.FillSerial; if (memo.Find() is { } entry) { - if (TryTakeResolveMemo(entry, flags.PixelActive) is not { } miss) + if (TryTakeResolveMemo(memo, entry, flags.PixelActive, out var rebuilt) is not { } miss) { - GraphicsResolveMemo.NoteHit(); + if (rebuilt) + { + // A words miss answered from its revalidation: counted as the miss it is, not resolved again. + GraphicsResolveMemo.NoteMiss(ResolveMemoMiss.Words); + GraphicsResolveMemo.NoteRebuilt(); + } + else + { + GraphicsResolveMemo.NoteHit(); + } + if (memo.Mode == ResolveMemoMode.Verify) { VerifyResolveMemo(entry, banks, targetExportMapping, flags); @@ -463,8 +486,9 @@ private GraphicsPrograms ResolveFull(RegisterBanks banks, ReadOnlySpan ResolveMemoRebuildRefusal.Evaluate, + ResourceMaterializer.RebuildRefusal.Failed => ResolveMemoRebuildRefusal.Failed, + ResourceMaterializer.RebuildRefusal.Specialization => ResolveMemoRebuildRefusal.Specialization, + _ => ResolveMemoRebuildRefusal.Refused, + }); + } + + return false; + } } finally { @@ -533,6 +604,33 @@ private bool RevalidateMemoStage(in ShaderStageResources stage) } } + // The programs with these stage resources in place of their own; the input descriptions are copied, never written: + // the result held before may still be on its way to the worker. + private static GraphicsPrograms WithStages(GraphicsPrograms programs, in ShaderStageResources vertexStage, ShaderStageResources? pixelStage) + { + var vertexInput = programs.VertexInput.WithoutStage(); + vertexInput.Stage = vertexStage; + var pixelInput = programs.PixelInput; + if (pixelStage is { } pixel) + { + pixelInput = pixelInput.WithoutStage(); + pixelInput.Stage = pixel; + } + + return new GraphicsPrograms(vertexInput, pixelInput) + { + Tessellation = programs.Tessellation, + Vertex = programs.Vertex, + Pixel = programs.Pixel, + MeshInput = programs.MeshInput, + Available = programs.Available, + SolidClear = programs.SolidClear, + PositionStream = programs.PositionStream, + DisableBlending = programs.DisableBlending, + DropUnwrittenColorTargets = programs.DropUnwrittenColorTargets, + }; + } + // Keeps a full resolution under the filled key, with what a hit re-checks, when it can be repeated from them: one // vertex and pixel program pair with no tessellation, mesh or shader calls, nothing changed while it resolved, and // vertex tables read back to the inputs it decoded (the guest may have written them since). diff --git a/src/SharpEmu.Libs/Gpu/Pipelines/ShaderProgramCache.cs b/src/SharpEmu.Libs/Gpu/Pipelines/ShaderProgramCache.cs index a308e6760..06eae3919 100644 --- a/src/SharpEmu.Libs/Gpu/Pipelines/ShaderProgramCache.cs +++ b/src/SharpEmu.Libs/Gpu/Pipelines/ShaderProgramCache.cs @@ -370,6 +370,44 @@ public bool Revalidate(in ShaderStageResources stage) return current; } + // Revalidate; and with rebuild, a fast stage whose own draw values evaluate to other descriptor words gets the stage + // a lookup of that draw makes now (ResourceMaterializer.RevalidateOrRebuildFast): the same program, since the + // specialization that picks its permutation is unchanged, and the snapshot materialized from that one evaluation. + // The caller has established that everything else the lookup reads is unchanged (ShaderPipelineCache's memo). + public ResourceMaterializer.FastRevalidation RevalidateOrRebuild(in ShaderStageResources stage, bool rebuild, out ShaderStageResources rebuilt) + { + rebuilt = stage; + if (!rebuild || stage.Program is null) + { + return Revalidate(stage) ? ResourceMaterializer.FastRevalidation.Current : ResourceMaterializer.FastRevalidation.Stale; + } + + var started = MaterializationTally.StartTiming(); + var fast = ResourceMaterializer.RevalidateOrRebuildFast(stage.Resources, out var snapshot); + if (fast == ResourceMaterializer.FastRevalidation.NotFast) + { + // A cached materialization: revalidated as before, never rebuilt here. + var current = Materializations is { } materializations && materializations.Revalidate(stage.Resources, _readResidentGuestBytes); + MaterializationTally.Note(current ? MaterializationTally.Outcome.KeptRevalidated : MaterializationTally.Outcome.KeptStale, + MaterializationTally.ElapsedTicks(started), stage.Resources); + return current ? ResourceMaterializer.FastRevalidation.Current : ResourceMaterializer.FastRevalidation.NotFast; + } + + var outcome = fast switch + { + ResourceMaterializer.FastRevalidation.Current => MaterializationTally.Outcome.KeptRevalidated, + ResourceMaterializer.FastRevalidation.Rebuilt => ResourceMaterializer.LastFastOutcome, + _ => ResourceMaterializer.LastRevalidateRefused ? MaterializationTally.Outcome.RevalidateRefused : MaterializationTally.Outcome.KeptStale, + }; + MaterializationTally.Note(outcome, MaterializationTally.ElapsedTicks(started), snapshot ?? stage.Resources); + if (fast == ResourceMaterializer.FastRevalidation.Rebuilt) + { + rebuilt = stage with { Resources = snapshot! }; + } + + return fast; + } + // Read once: the draw path asked the environment on every draw and dispatch // (~4 % of the Demon's Souls render thread) for a debug dump that is almost never on. // A counted loop's record whose texture is of another class than its table's reads as null: the program is not diff --git a/src/SharpEmu.ShaderCompiler/Resources/ResourceMaterializer.cs b/src/SharpEmu.ShaderCompiler/Resources/ResourceMaterializer.cs index dded13e67..2a2fdea11 100644 --- a/src/SharpEmu.ShaderCompiler/Resources/ResourceMaterializer.cs +++ b/src/SharpEmu.ShaderCompiler/Resources/ResourceMaterializer.cs @@ -368,16 +368,123 @@ public static string TakeFastReport() => FormattableString.Invariant( // The plan a fast snapshot came from and the draw inputs it was evaluated with. The inputs object is refilled for // every lookup (ShaderProgramCache), so the draw's own user data, shader base and compute state are kept beside it: - // revalidating with whatever the object held last evaluated another stage's or another draw's words. + // revalidating with whatever the object held last evaluated another stage's or another draw's words. The + // specialization the snapshot was materialized with is kept to tell whether a rebuild keeps its program. private sealed record FastOrigin(ShaderResourcePlan Plan, ResourceRuntimeInputs Inputs, IReadOnlyList UserData, ulong ShaderBase, - ComputeSelectorState? ComputeState) + ComputeSelectorState? ComputeState, ResourceSpecialization Specialization) { - public FastOrigin(ShaderResourcePlan plan, ResourceRuntimeInputs inputs) - : this(plan, inputs, inputs.UserData, inputs.ShaderBase, inputs.ComputeState) + public FastOrigin(ShaderResourcePlan plan, ResourceRuntimeInputs inputs, ResourceSpecialization specialization) + : this(plan, inputs, inputs.UserData, inputs.ShaderBase, inputs.ComputeState, specialization) { } } + // RevalidateOrRebuildFast's answer. + public enum FastRevalidation + { + // The snapshot did not come from the fast path. + NotFast, + // The plan evaluates to the snapshot's words again. + Current, + // Neither current nor rebuilt (LastRebuildRefusal says why). + Stale, + // The words changed; the rebuilt snapshot is the one a fast materialization of the draw makes now, with the + // same specialization. + Rebuilt, + } + + // Why RevalidateOrRebuildFast left a stale snapshot stale. + public enum RebuildRefusal + { + None, + // A reader that tells table words apart, or a plan with no program to evaluate (as Revalidate refuses). + Refused, + // The program could not evaluate the draw's words (MaterializeFast falls to the general evaluator). + Evaluate, + // The materialization from the evaluated words failed. + Failed, + // The words specialize the program otherwise: another permutation may be the draw's. + Specialization, + } + + [ThreadStatic] + private static RebuildRefusal _lastRebuildRefusal; + + public static RebuildRefusal LastRebuildRefusal => _lastRebuildRefusal; + + // RevalidateFast; and when the snapshot's own draw values evaluate to other words, the snapshot MaterializeFast + // makes for that draw now, built from this one evaluation instead of reading the words again, when it keeps the + // snapshot's specialization (so the permutation, and the program a lookup hands out, stay the snapshot's). + public static FastRevalidation RevalidateOrRebuildFast(ResourceSnapshot snapshot, out ResourceSnapshot? rebuilt) + { + rebuilt = null; + _lastRebuildRefusal = RebuildRefusal.None; + if (snapshot.Origin is not FastOrigin origin) + { + return FastRevalidation.NotFast; + } + + var plan = origin.Plan; + _lastRevalidateRefused = origin.Inputs.TablePhase is not null || plan.MaterializationProgram is null; + if (_lastRevalidateRefused) + { + _lastRebuildRefusal = RebuildRefusal.Refused; + return FastRevalidation.Stale; + } + + var inputs = TakeRevalidationInputs(origin.Inputs); + inputs.UserData = origin.UserData; + inputs.ShaderBase = origin.ShaderBase; + inputs.ComputeState = origin.ComputeState; + var output = TakeOutput(); + try + { + if (!EvaluateInto(plan, inputs, output)) + { + _lastRebuildRefusal = RebuildRefusal.Evaluate; + return FastRevalidation.Stale; + } + + if (SameAsOutput(plan, snapshot, output)) + { + return FastRevalidation.Current; + } + + // As MaterializeFast after its own evaluation. + if (plan.RequiresSpecializationMemory && inputs.ReadCleanMemory is null) + { + _lastRebuildRefusal = RebuildRefusal.Failed; + return FastRevalidation.Stale; + } + + _programRuns.Increment(); + _fastMaterializations.Increment(); + _lastFastOutcome = MaterializationTally.Outcome.FastMiss; + ResourceSnapshot next = null!; + ResourceSpecialization specialization = null!; + if (!MaterializeFromOutput(plan, inputs, output, ref next, ref specialization, out _)) + { + _lastRebuildRefusal = RebuildRefusal.Failed; + return FastRevalidation.Stale; + } + + if (!ReferenceEquals(specialization, origin.Specialization) && !specialization.Equals(origin.Specialization)) + { + _lastRebuildRefusal = RebuildRefusal.Specialization; + return FastRevalidation.Stale; + } + + rebuilt = next; + return FastRevalidation.Rebuilt; + } + finally + { + _programOutput = output; + inputs.UserData = []; + _revalidationInputs = inputs; + } + } + [ThreadStatic] private static MaterializationTally.Outcome _lastFastOutcome; @@ -687,7 +794,7 @@ private static bool MaterializeFromOutput(ShaderResourcePlan plan, ResourceRunti UserData = userData, DeviceAddressRanges = ranges, MipStatistics = statistics, - Origin = new FastOrigin(plan, inputs), + Origin = new FastOrigin(plan, inputs, memo.Specialization), }; specialization = memo.Specialization; failure = ResourceMaterializationFailure.None; @@ -844,7 +951,7 @@ private static bool MaterializeFastFromSnapshot( UserData = materialized.UserData, DeviceAddressRanges = ranges, MipStatistics = statistics, - Origin = new FastOrigin(plan, inputs), + Origin = new FastOrigin(plan, inputs, memo.Specialization), }; specialization = memo.Specialization; failure = ResourceMaterializationFailure.None; @@ -917,7 +1024,7 @@ private static bool SpecializeAndRemember(ShaderResourcePlan plan, ResourceRunti FlattenedResourceTable = nextSnapshot.FlattenedTable, UserData = nextSnapshot.UserData, DeviceAddressRanges = ranges, - Origin = new FastOrigin(plan, inputs), + Origin = new FastOrigin(plan, inputs, nextSpecialization), }; specialization = nextSpecialization; failure = ResourceMaterializationFailure.None; diff --git a/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/KeptStageInputsTests.ResolveMemo.cs b/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/KeptStageInputsTests.ResolveMemo.cs index fc63d4ff1..973b797d5 100644 --- a/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/KeptStageInputsTests.ResolveMemo.cs +++ b/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/KeptStageInputsTests.ResolveMemo.cs @@ -96,6 +96,64 @@ public void ResolveMemo_MissesWhenAStagesDescriptorWordChanges() Assert.Same(changed, Programs(cache, pixelActive: true)); } + // A words miss whose new words keep the stage's specialization (another buffer base) is rebuilt from its revalidation: + // verify mode resolves the same draw in full and finds no difference; the result held before is left as it was. + [Fact] + public void ResolveMemo_RebuildsAWordsMissFromItsRevalidationAsTheFullResolutionWould() + { + var cache = MemoCache(); + Assert.True(cache.ResolveMemoRebuild); + UseLoadingPixelProgram(Descriptor); + var first = Programs(cache, pixelActive: true); + var firstBuffers = first.PixelInput.Stage.Resources.Buffers.Select(words => words.ToArray()).ToArray(); + var firstVertexStage = first.VertexInput.Stage; + Report(); + _guest.WriteWords(Descriptor, PipelineTestGuest.BufferDescriptor(StreamBase + 0x100, 16, 4, Format32x4Float)); + var rebuilt = Programs(cache, pixelActive: true); + var report = Report(); + Assert.Contains("words=1", report); + Assert.Contains("words_rebuilt=1,", report); + Assert.Contains("verify_checked=1,", report); + Assert.Contains("verify_failed=0)", report); + Assert.NotSame(first, rebuilt); + Assert.NotSame(first.PixelInput, rebuilt.PixelInput); + Assert.Same(first.PixelInput.Stage.Program, rebuilt.PixelInput.Stage.Program); + Assert.Equal(first.Pixel, rebuilt.Pixel); + Assert.Equal(first.Vertex, rebuilt.Vertex); + Assert.Contains(rebuilt.PixelInput.Stage.Resources.Buffers, words => words[0] == unchecked((uint)(StreamBase + 0x100))); + // The earlier result is untouched (a worker may still hold it), and the unchanged vertex stage is kept as it was. + Assert.Equal(firstBuffers, first.PixelInput.Stage.Resources.Buffers); + Assert.Equal(firstVertexStage, rebuilt.VertexInput.Stage); + // The rebuilt entry is the one the next draw takes. + Assert.Same(rebuilt, Programs(cache, pixelActive: true)); + Assert.Contains("hits=1,", Report()); + } + + // Words that specialize the program otherwise (another stride) may pick another permutation: not rebuilt, resolved in + // full (and counted); with rebuild off every words miss resolves in full. + [Theory] + [InlineData(true)] + [InlineData(false)] + public void ResolveMemo_ResolvesAWordsMissInFullWhenItsSpecializationChangesOrRebuildIsOff(bool rebuild) + { + var cache = MemoCache(); + cache.ResolveMemoRebuild = rebuild; + UseLoadingPixelProgram(Descriptor); + var first = Programs(cache, pixelActive: true); + Report(); + _guest.WriteWords(Descriptor, rebuild + ? PipelineTestGuest.BufferDescriptor(StreamBase, 32, 4, Format32x4Float) + : PipelineTestGuest.BufferDescriptor(StreamBase + 0x100, 16, 4, Format32x4Float)); + var changed = Programs(cache, pixelActive: true); + var report = Report(); + Assert.NotSame(first, changed); + Assert.Contains("words=1", report); + Assert.Contains("words_rebuilt=0,", report); + Assert.Contains(rebuild ? "specialization=1" : "specialization=0", report); + Assert.Same(changed, Programs(cache, pixelActive: true)); + Assert.Contains("verify_failed=0)", Report()); + } + [Fact] public void ResolveMemo_MissesWhenTheVertexTableWordsChange() { From 548bb641a6a00e0ba6216404820fc2b81bb94686 Mon Sep 17 00:00:00 2001 From: kuba Date: Sun, 15 Nov 2026 13:46:55 +0000 Subject: [PATCH 064/178] [GPU] Resolve memo: eight ways per set instead of two A frame's draws repeat in the same order, so a 2-way set holding three of a frame's keys missed all of them every frame: on the DS bench every user_data_only miss was such an eviction (GameShaped 23% of draws). Eight ways at the same capacity (SHARPEMU_RESOLVE_MEMO_ENTRIES) leave few. --- .../Gpu/Pipelines/GraphicsResolveMemo.cs | 18 +++++++++------ .../Pipelines/GraphicsResolveMemoKeyTests.cs | 22 +++++++++++++------ 2 files changed, 26 insertions(+), 14 deletions(-) diff --git a/src/SharpEmu.Libs/Gpu/Pipelines/GraphicsResolveMemo.cs b/src/SharpEmu.Libs/Gpu/Pipelines/GraphicsResolveMemo.cs index d3d6c1746..538ed9c84 100644 --- a/src/SharpEmu.Libs/Gpu/Pipelines/GraphicsResolveMemo.cs +++ b/src/SharpEmu.Libs/Gpu/Pipelines/GraphicsResolveMemo.cs @@ -131,6 +131,10 @@ internal sealed class Entry } private const int MaxKeyBytes = 4096; + // Ways per set. A frame's draws come back in the same order every frame, so a set holding more of a frame's keys + // than it has ways misses all of them every frame (LRU): at two ways ~23% of the bench's GameShaped draws (and the + // evictions ~= miss_by new of Demon's Souls) missed so; eight ways at the same capacity leave few such sets. + internal const int Ways = 8; private readonly byte[] _key = new byte[MaxKeyBytes]; private int _keyLength; private int _userDataStart; @@ -146,9 +150,9 @@ public GraphicsResolveMemo(ResolveMemoMode mode, int capacity) { Mode = mode; var sets = 1; - while (sets * 2 < capacity) sets <<= 1; + while (sets * Ways < capacity) sets <<= 1; _setMask = sets - 1; - _ways = new Entry?[sets * 2]; + _ways = new Entry?[sets * Ways]; } public ResolveMemoMode Mode { get; } @@ -305,9 +309,9 @@ private static void PutSpan(Span key, ref int at, ReadOnlySpan value // The entry with the filled key, or null. public Entry? Find() { - var set = (int)(Hash & (ulong)_setMask) * 2; + var set = (int)(Hash & (ulong)_setMask) * Ways; var key = Key; - for (var way = set; way < set + 2; way++) + for (var way = set; way < set + Ways; way++) { if (_ways[way] is { } entry && entry.Hash == Hash && key.SequenceEqual(entry.Key)) { @@ -330,13 +334,13 @@ public ResolveMemoKeyMiss ClassifyMiss() : ResolveMemoKeyMiss.New; } - // A new entry for the filled key, in place of the set's older way; the caller fills it. + // A new entry for the filled key, in place of the set's least recently used way; the caller fills it. public Entry Store() { var key = Key; - var set = (int)(Hash & (ulong)_setMask) * 2; + var set = (int)(Hash & (ulong)_setMask) * Ways; var way = set; - for (var candidate = set; candidate < set + 2; candidate++) + for (var candidate = set; candidate < set + Ways; candidate++) { if (_ways[candidate] is not { } held) { diff --git a/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/GraphicsResolveMemoKeyTests.cs b/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/GraphicsResolveMemoKeyTests.cs index 439e1f3ee..7d8b9bc27 100644 --- a/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/GraphicsResolveMemoKeyTests.cs +++ b/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/GraphicsResolveMemoKeyTests.cs @@ -73,26 +73,34 @@ public void AUserDataWordOnlyMissIsToldApartAndAnUnreadWordIsNotInTheKey() Assert.False(Fill(memo, over)); } + // One set (capacity = ways) keeps that many keys and replaces the least recently used one. [Fact] - public void ASetKeepsTwoKeysAndReplacesTheOlder() + public void ASetKeepsItsWaysAndReplacesTheLeastRecentlyUsedKey() { - var memo = new GraphicsResolveMemo(ResolveMemoMode.Shadow, 2); - var keys = Enumerable.Range(0, 3).Select(index => + var memo = new GraphicsResolveMemo(ResolveMemoMode.Shadow, GraphicsResolveMemo.Ways); + var keys = Enumerable.Range(0, GraphicsResolveMemo.Ways + 1).Select(index => { var banks = Banks(); banks.Shader.Vertex.ExportAddress = 0x1000 + (ulong)index * 0x100; return banks; }).ToArray(); - foreach (var banks in keys) + foreach (var banks in keys[..^1]) { Assert.True(Fill(memo, banks)); memo.Store(); } - Assert.Equal(2, memo.Count); Assert.True(Fill(memo, keys[0])); - Assert.Null(memo.Find()); - Assert.True(Fill(memo, keys[2])); Assert.NotNull(memo.Find()); + Assert.True(Fill(memo, keys[^1])); + memo.Store(); + Assert.Equal(GraphicsResolveMemo.Ways, memo.Count); + Assert.True(Fill(memo, keys[1])); + Assert.Null(memo.Find()); + foreach (var banks in keys.Where((_, index) => index != 1)) + { + Assert.True(Fill(memo, banks)); + Assert.NotNull(memo.Find()); + } } } From 1a2ab1f56e44ab54337d75bdcd06680e76a889e3 Mon Sep 17 00:00:00 2001 From: kuba Date: Sun, 15 Nov 2026 13:49:23 +0000 Subject: [PATCH 065/178] [Shader] Remember a level's read order per program, not per thread and level index ReadOrder kept the last order of each level index in the thread's scratch, shared by every program the thread evaluates: a draw's pixel and vertex plans (and every other program) overwrote each other's orders, so the check rarely fit and the level fell to the packed-key sort. The order now lives on the program's level, published as a new array and checked in one pass as before, so it stays exact under concurrent evaluation. --- .../Resources/MaterializationProgram.cs | 49 +++++++++++-------- .../MaterializationReadOrderTests.cs | 42 +++++++++++++++- 2 files changed, 70 insertions(+), 21 deletions(-) diff --git a/src/SharpEmu.ShaderCompiler/Resources/MaterializationProgram.cs b/src/SharpEmu.ShaderCompiler/Resources/MaterializationProgram.cs index 76f92c107..664183ed1 100644 --- a/src/SharpEmu.ShaderCompiler/Resources/MaterializationProgram.cs +++ b/src/SharpEmu.ShaderCompiler/Resources/MaterializationProgram.cs @@ -30,6 +30,10 @@ private sealed class Level public Step[] Steps = []; // Set when every read loads a word at a constant offset from one base (FixedReads). public FixedReads? Fixed; + // The address order this level's reads took last (ReadOrder.Sort), kept per program: one per thread and level + // index was overwritten by every other program the thread evaluated (a draw's pixel and vertex plans in turn), + // so it rarely fit and the level sorted again. Never written once published; threads may race to replace it. + public int[]? Order; } /// @@ -525,7 +529,7 @@ private void Evaluate(ResourceRuntimeInputs inputs, Scratch scratch) var level = _levels[levelIndex]; if (level.Reads.Length != 0 && (level.Fixed is not { } fixedReads || !TryReadFixed(level.Reads, fixedReads, inputs, scratch))) { - ReadLevel(level.Reads, inputs, scratch, levelIndex); + ReadLevel(level, inputs, scratch); } foreach (var step in level.Steps) @@ -801,8 +805,9 @@ private static bool TryReadFixed(ReadStep[] reads, FixedReads plan, ResourceRunt return true; } - private static void ReadLevel(ReadStep[] reads, ResourceRuntimeInputs inputs, Scratch scratch, int levelIndex) + private static void ReadLevel(Level level, ResourceRuntimeInputs inputs, Scratch scratch) { + var reads = level.Reads; var values = scratch.Values; var valid = scratch.Valid; scratch.Count = 0; @@ -842,7 +847,7 @@ private static void ReadLevel(ReadStep[] reads, ResourceRuntimeInputs inputs, Sc var targets = scratch.Targets; var bases = scratch.NullBases; var absolute = scratch.Absolute; - scratch.Order.Sort(addresses, targets, bases, absolute, count, levelIndex); + scratch.Order.Sort(addresses, targets, bases, absolute, count, ref level.Order); var resident = inputs.ReadResidentMemory; var start = 0; @@ -880,8 +885,8 @@ private static void ReadLevel(ReadStep[] reads, ResourceRuntimeInputs inputs, Sc /// Puts a level's reads in address order, equal addresses in the order they were added (a stable sort). A /// table of descriptors interleaves its words across the reads, so they rarely arrive in order: one sort of /// packed (address, position) keys replaces moving every out-of-order read past each read before it. A level's - /// reads mostly come back in the order they took last time, so that order is tried first: the keys are unique, - /// so an order that leaves them increasing is the sorted one. + /// reads mostly come back in the order they took last time, so that order (the caller's, one per program level) + /// is tried first: the keys are unique, so an order that leaves them increasing is the sorted one. /// internal sealed class ReadOrder { @@ -890,10 +895,19 @@ internal sealed class ReadOrder private int[] _targets = new int[64]; private ulong[] _bases = new ulong[64]; private bool[] _absolute = new bool[64]; - private int[]?[] _levelOrders = []; - private int[] _levelCounts = []; + private int[] _order = new int[64]; - public void Sort(ulong[] addresses, int[] targets, ulong[] bases, bool[] absolute, int count, int level = -1) + public void Sort(ulong[] addresses, int[] targets, ulong[] bases, bool[] absolute, int count) + { + int[]? none = null; + Sort(addresses, targets, bases, absolute, count, ref none, remember: false); + } + + // With the order these reads took last time in remembered, replaced by this sort's order when it does not fit. + public void Sort(ulong[] addresses, int[] targets, ulong[] bases, bool[] absolute, int count, ref int[]? remembered) => + Sort(addresses, targets, bases, absolute, count, ref remembered, remember: true); + + private void Sort(ulong[] addresses, int[] targets, ulong[] bases, bool[] absolute, int count, ref int[]? remembered, bool remember) { var ordered = true; var packable = count <= 1 << 16; @@ -922,16 +936,11 @@ public void Sort(ulong[] addresses, int[] targets, ulong[] bases, bool[] absolut _targets = new int[length]; _bases = new ulong[length]; _absolute = new bool[length]; + _order = new int[length]; } - if (level >= _levelOrders.Length) - { - Array.Resize(ref _levelOrders, level + 1); - Array.Resize(ref _levelCounts, level + 1); - } - - var known = level >= 0 ? _levelOrders[level] : null; - if (known is not null && _levelCounts[level] == count && Orders(known, addresses, count)) + var known = remember ? Volatile.Read(ref remembered) : null; + if (known is not null && known.Length == count && Orders(known, addresses, count)) { Permute(known, addresses, targets, bases, absolute, count); return; @@ -944,16 +953,16 @@ public void Sort(ulong[] addresses, int[] targets, ulong[] bases, bool[] absolut } keys.Sort(); - var order = known is not null && known.Length >= count ? known : new int[Math.Max(count, 16)]; + // A new array to remember: another thread may be checking the one published before. + var order = remember ? new int[count] : _order; for (var index = 0; index < count; index++) { order[index] = (int)(keys[index] & 0xFFFF); } - if (level >= 0) + if (remember) { - _levelOrders[level] = order; - _levelCounts[level] = count; + Volatile.Write(ref remembered, order); } Permute(order, addresses, targets, bases, absolute, count); diff --git a/tests/SharpEmu.ShaderCompiler.Tests/Resources/MaterializationReadOrderTests.cs b/tests/SharpEmu.ShaderCompiler.Tests/Resources/MaterializationReadOrderTests.cs index e2e1e4e22..260d451fd 100644 --- a/tests/SharpEmu.ShaderCompiler.Tests/Resources/MaterializationReadOrderTests.cs +++ b/tests/SharpEmu.ShaderCompiler.Tests/Resources/MaterializationReadOrderTests.cs @@ -20,6 +20,8 @@ public void ReadsSortAsTheInsertionSortLeftThem(int seed, int count) { var random = new System.Random(seed); var order = new MaterializationProgram.ReadOrder(); + var remembered = new int[]?[3]; + remembered[2] = Enumerable.Range(0, count).Reverse().ToArray(); for (var trial = 0; trial < 50; trial++) { var addresses = new ulong[count]; @@ -49,7 +51,10 @@ public void ReadsSortAsTheInsertionSortLeftThem(int seed, int count) { var (sortedAddresses, sortedTargets, sortedBases, sortedAbsolute) = ((ulong[])addresses.Clone(), (int[])targets.Clone(), (ulong[])bases.Clone(), (bool[])absolute.Clone()); - order.Sort(sortedAddresses, sortedTargets, sortedBases, sortedAbsolute, count, level); + if (level < 0) + order.Sort(sortedAddresses, sortedTargets, sortedBases, sortedAbsolute, count); + else + order.Sort(sortedAddresses, sortedTargets, sortedBases, sortedAbsolute, count, ref remembered[level]); Assert.Equal(expectedAddresses, sortedAddresses); Assert.Equal(expectedTargets, sortedTargets); Assert.Equal(expectedBases, sortedBases); @@ -57,4 +62,39 @@ public void ReadsSortAsTheInsertionSortLeftThem(int seed, int count) } } } + + // Two programs' levels evaluated in turn on one thread (a draw's pixel and vertex plans) each keep their own order: + // after the first sort neither sorts again, and each still comes out in address order. + [Fact] + public void LevelsEvaluatedInTurnKeepTheirOwnOrders() + { + var order = new MaterializationProgram.ReadOrder(); + ulong[] pixel = [0x2_0000_1010, 0x2_0000_1000, 0x2_0000_1014, 0x2_0000_1004]; + ulong[] vertex = [0x3_0000_0040, 0x3_0000_0000, 0x3_0000_0044, 0x3_0000_0004, 0x3_0000_0048]; + int[]? pixelOrder = null, vertexOrder = null; + int[]? firstPixelOrder = null, firstVertexOrder = null; + for (var draw = 0; draw < 4; draw++) + { + // Each draw its own table base, the same layout. + var shift = (ulong)draw * 0x100; + foreach (var (reads, isPixel) in new[] { (pixel, true), (vertex, false) }) + { + var addresses = reads.Select(address => address + shift).ToArray(); + var targets = Enumerable.Range(0, addresses.Length).ToArray(); + var bases = new ulong[addresses.Length]; + var absolute = new bool[addresses.Length]; + if (isPixel) + order.Sort(addresses, targets, bases, absolute, addresses.Length, ref pixelOrder); + else + order.Sort(addresses, targets, bases, absolute, addresses.Length, ref vertexOrder); + Assert.Equal(addresses.Order().ToArray(), addresses); + Assert.Equal(reads.Select((address, index) => (address, index)).OrderBy(pair => pair.address).Select(pair => pair.index), targets); + } + + firstPixelOrder ??= pixelOrder; + firstVertexOrder ??= vertexOrder; + Assert.Same(firstPixelOrder, pixelOrder); + Assert.Same(firstVertexOrder, vertexOrder); + } + } } From 4e607f1b768f3f3f83dee495542e1044fc511fb6 Mon Sep 17 00:00:00 2001 From: kuba Date: Sun, 15 Nov 2026 13:52:00 +0000 Subject: [PATCH 066/178] [Tests] Cached-draw allocation bound: the specialization a fast origin keeps (+8 bytes a stage) --- .../Gpu/Pipelines/ShaderPipelineCacheAllocationTests.cs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/ShaderPipelineCacheAllocationTests.cs b/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/ShaderPipelineCacheAllocationTests.cs index 4ec3e220f..cad87c469 100644 --- a/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/ShaderPipelineCacheAllocationTests.cs +++ b/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/ShaderPipelineCacheAllocationTests.cs @@ -51,8 +51,9 @@ long Draw() // input's stage, whose shader-call fields (ShaderStageResources.CallArguments and the rest) stay null for a draw. // The upstream merge (tessellation, frontend and kept-pipeline fields) grew these to 520 and 880 bytes, and the binding // packet slot on each stage's resource snapshot (ResourceSnapshot.BindingPacket) to 528 and 896, and the draw's own - // user data, shader base and compute state on each fast snapshot's origin (ResourceMaterializer.FastOrigin) to 576 and 992. - Assert.True(perDraw[^1] <= (pixelActive ? 992 : 576), $"bytes={perDraw[^1]}"); + // user data, shader base and compute state on each fast snapshot's origin (ResourceMaterializer.FastOrigin) to 576 and 992, + // and the specialization that origin keeps (whether a resolve memo rebuild keeps the program) to 584 and 1008. + Assert.True(perDraw[^1] <= (pixelActive ? 1008 : 584), $"bytes={perDraw[^1]}"); var first = cache.GetGraphicsPrograms(banks.Shader.Vertex, banks.Shader.Pixel, banks.Context.ShaderInterface, banks.Context, mappings, pixelActive, depthBound: false, depthAspectBound: false); var second = cache.GetGraphicsPrograms(banks.Shader.Vertex, banks.Shader.Pixel, banks.Context.ShaderInterface, From 0ba46f1ba19797b000d7e375670508d3ab37edc4 Mon Sep 17 00:00:00 2001 From: kuba Date: Sun, 15 Nov 2026 14:02:01 +0000 Subject: [PATCH 067/178] [Tests] DS draw bench: SHARPEMU_DS_DRAW_BENCH_COPIED_TABLES=1 puts the GameShaped mesh tables under a pending copy Demon's Souls' draws read a table its copy kernel writes every frame, so off the worker each table word is owned by the copy's pending write and read through it (~20 word tests a job in game). With the knob the bench's 3000 vertex tables lie in a refused copy's destination, armed again for every command buffer: 12 word tests a job (0.1 without), same checksum. --- .../Scenes/DsDrawCostBenchTests.cs | 49 +++++++++++++++++-- 1 file changed, 44 insertions(+), 5 deletions(-) diff --git a/tests/SharpEmu.Gpu.Metal.Tests/Scenes/DsDrawCostBenchTests.cs b/tests/SharpEmu.Gpu.Metal.Tests/Scenes/DsDrawCostBenchTests.cs index c0a5510d0..465feeeb6 100644 --- a/tests/SharpEmu.Gpu.Metal.Tests/Scenes/DsDrawCostBenchTests.cs +++ b/tests/SharpEmu.Gpu.Metal.Tests/Scenes/DsDrawCostBenchTests.cs @@ -290,7 +290,7 @@ int Setting(string name, int fallback) => // Each mesh a quad over one cell of a 6x4 grid, four 16-byte-record vertex buffers and a constants buffer; // indices 0-5 and an indexed-indirect argument record. var objectConstants = rig.Memory.Upload(new float[16], 256); - (ulong table, ulong indices, ulong arguments) Mesh(int mesh, ulong normalBuffer = 0) + (ulong table, ulong indices, ulong arguments) Mesh(int mesh, ulong normalBuffer = 0, ulong tableAt = 0) { var (column, row) = (mesh % 6, mesh / 6 % 4); var (left, right) = (-1f + column / 3f, -1f + (column + 1) / 3f); @@ -302,11 +302,13 @@ int Setting(string name, int fallback) => var normal = normalBuffer != 0 ? normalBuffer : rig.Memory.Upload(new float[24]); var color = rig.Memory.Upload(Enumerable.Range(0, 24).Select(index => index % 4 == 3 ? 0f : mesh % 512 / 512f).ToArray()); var constants = rig.Memory.Upload(new float[8], 256); - var table = rig.Memory.Upload( + uint[] tableWords = [ .. Descriptors.Buffer(position, 16, 6), .. Descriptors.Buffer(uv, 16, 6), .. Descriptors.Buffer(normal, 16, 6), .. Descriptors.Buffer(color, 16, 6), .. Descriptors.Buffer(constants, 16, 2), - ], 256); + ]; + if (tableAt != 0) rig.Memory.Write(tableAt, tableWords); + var table = tableAt != 0 ? tableAt : rig.Memory.Upload(tableWords, 256); var indices = rig.Memory.Upload([0, 1, 2, 3, 4, 5, 0, 0], 256); var arguments = rig.Memory.Upload([6, 1, 0, 0, 0, 0, 0, 0], 256); return (table, indices, arguments); @@ -497,9 +499,40 @@ ulong DispatchTable(int dispatch, ulong writeBuffer) // made again when sampled next (image-set changes). var gameMeshCount = Setting("MESHES", 3000); var gameDrawCount = Setting("GAME_DRAWS", 7300); + // SHARPEMU_DS_DRAW_BENCH_COPIED_TABLES=1: the game meshes' vertex tables (one per 128 bytes) lie in the + // destination of a copy kernel the host refuses, armed again for every command buffer, as Demon's Souls' draws + // read a table its copy kernel writes every frame: off the worker each table word is owned by the copy's pending + // write and answered from its source (~20 word tests a draw, as in game). The destination holds the copy's result. + var copiedTables = Environment.GetEnvironmentVariable("SHARPEMU_DS_DRAW_BENCH_COPIED_TABLES") == "1"; + ulong copyDestination = 0, copySource = 0, copyWords = 0; + void ArmCopiedTables() + { + if (copyWords == 0) return; + Assert.False(rig.Host.TryCopyWordsOnHost(copyDestination, copySource, copyWords - 1, copyWords)); + rig.Host.NoteGuestMemoryWrite(copyDestination, copyWords * sizeof(uint), MetalGpuWriteOrigin.StorageBuffer); + } + (uint[][] Streams, ulong[] Written, ulong[] Churn) GameStreams() { - var gameMeshes = Enumerable.Range(0, gameMeshCount).Select(mesh => Mesh(mesh)).ToArray(); + if (copiedTables) + { + copyWords = (ulong)gameMeshCount * 32; + copyDestination = rig.Memory.Allocate(copyWords * sizeof(uint), 0x10000); + copySource = rig.Memory.Allocate(copyWords * sizeof(uint), 0x10000); + rig.Host.HostKernelCopyMode = MetalHostKernelCopyMode.Off; + rig.Host.HostKernelCopyDryRun = false; + } + + var gameMeshes = Enumerable.Range(0, gameMeshCount) + .Select(mesh => Mesh(mesh, tableAt: copiedTables ? copyDestination + (ulong)mesh * 128 : 0)).ToArray(); + if (copiedTables) + { + // dst[i] = src[i % (words - 1)]: the source is the destination, and the destination's last word (padding) its first. + var copied = rig.Read(copyDestination, (int)copyWords); + rig.Memory.Write(copySource, copied); + rig.Memory.Write32(copyDestination + (copyWords - 1) * sizeof(uint), copied[0]); + } + var written = Enumerable.Range(0, 4).Select(_ => rig.Memory.Upload(new uint[StorageEdge * StorageEdge], 256)).ToArray(); var dynamicMeshes = written.Select((buffer, index) => Mesh(index, normalBuffer: buffer)).ToArray(); var dispatchTables = written.Select((buffer, index) => DispatchTable(index, buffer)).ToArray(); @@ -619,11 +652,17 @@ ulong DispatchTable(int dispatch, ulong writeBuffer) } else { + ArmCopiedTables(); for (var index = 0; index < gameStreams.Length; index++) { rig.Host.CommandStream.EnqueueGraphics(gameStreams[index].Address, gameStreams[index].Length, ++submissionId, null); rig.RecordPending(); - if ((int)((index + 1) / SubmissionsPerCommit) != (int)(index / SubmissionsPerCommit)) rig.Host.FlushCommandBuffer(); + if ((int)((index + 1) / SubmissionsPerCommit) != (int)(index / SubmissionsPerCommit)) + { + rig.Host.FlushCommandBuffer(); + ArmCopiedTables(); + } + if (index % 3 == 2) { var churn = game.Churn[index % ChurnTextures]; From 00b07fe0a476d338dfa8739643612200678ef125 Mon Sep 17 00:00:00 2001 From: kuba Date: Sun, 15 Nov 2026 14:02:01 +0000 Subject: [PATCH 068/178] [Metal] Answer the words of an owned line from its pending-write mask, and read a pending copy's line once Off the worker every word read in an owned line of an owned page took its own ownership test (a walk of the GPU write records), and a word a pending copy writes then the read-through path, its owned answer recorded and dropped again. Demon's Souls: ~167k word tests a frame, ~11 ms of the resolver's ~52. The line test now takes each owner apart (queued, image, overlays, and the pending GPU writes as a 64-word mask read at one record mutation stamp), and a word of a line only GPU writes own is answered from the mask while the stamp and the ownership versions read before the line's tests stand; the answer is recorded at the word exactly as before, so the worker's re-check is unchanged. A word read through a pending copy with its owner from a mask fills the copy line: the line's other words the same verified copy writes, from sources in pages this resolution found clean, read through it at that moment (nothing is recorded for them, as before). The concurrency argument is in the comments at ConcurrentLineMasks and FillCopyLine. SHARPEMU_CONCURRENT_LINE_MASKS=0 off, =verify answers each word both ways and is fatal on a difference. owner_tests gains mask_words, mask_stale, mask_refused, mask_verified, copy_line_words, mask_verify_failed. DS bench GameShaped with copied tables (ABBA, 4 runs each): resolver 3.71 -> 3.20-3.37 us/job, word tests 12.2 -> 0.14 a job, checksum unchanged. --- .../V2/MetalGpuWriteRanges.cs | 74 +++++ .../V2/MetalRenderHost.ConcurrentResolve.cs | 306 +++++++++++++++++- .../V2/MetalRenderHost.CopyReads.cs | 90 ++++++ ...alClearFoldingTests.CrossDrawCleanPages.cs | 2 + .../MetalClearFoldingTests.LineMasks.cs | 161 +++++++++ .../MetalGpuWriteRangesTests.cs | 41 +++ 6 files changed, 660 insertions(+), 14 deletions(-) create mode 100644 tests/SharpEmu.Gpu.Metal.Tests/MetalClearFoldingTests.LineMasks.cs diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalGpuWriteRanges.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalGpuWriteRanges.cs index 7917a2e86..1b6cb3aea 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalGpuWriteRanges.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalGpuWriteRanges.cs @@ -602,6 +602,80 @@ public bool TryPendingSerialSnapshot( return Volatile.Read(ref _mutation) == before; } + /// + /// for every 4-byte word of the 256-byte line at + /// at once: bit k of is set when a write that has not completed by + /// overlaps bytes [line + 4k, line + 4k + 4). For a 4-byte-aligned range of whole + /// words inside the line, TryPendingSerialSnapshot(range) pending != 0 exactly when one of its words' bits + /// is set (both are byte-overlap tests over the same records and the same serial). is the + /// (even) the records were read at: while it stands, the records and so the mask are the + /// same. False when the worker changed the records meanwhile. + /// + public bool TryPendingWordMask(ulong line, ulong completed, out ulong mask, out int stamp) + { + const ulong LineBytes = 256; + mask = 0; + stamp = Volatile.Read(ref _mutation); + if ((stamp & 1) != 0 || line > ulong.MaxValue - LineBytes) + { + return false; + } + + try + { + var end = line + LineBytes; + if (_unboundedSerial > completed) + { + mask = ulong.MaxValue; + } + else + { + var records = _records; + var count = Volatile.Read(ref _wideRecordCount) == 0 && + !HashedMayCover(_bucketHashCounts, line >> RecordBucketShift, (end - 1) >> RecordBucketShift, MaxRecordBucketLookups) + ? 0 + : Math.Min(_count, records.Length); + for (var index = 0; index < count; index++) + { + var record = records[index]; + if (record.Serial > completed && record.End > line && record.Start < end) + { + mask |= LineWordBits(line, record.Start, record.End); + } + } + + var labels = _labels; + var labelCount = HashedMayCover(_labelPageHashCounts, line >> LabelPageShift, (end - 1) >> LabelPageShift, MaxLabelPageLookups) + ? Math.Min(_labelCount, labels.Length) + : 0; + for (var index = 0; index < labelCount; index++) + { + var label = labels[index]; + if (label.Serial > completed && label.End > line && label.Start < end) + { + mask |= LineWordBits(line, label.Start, label.End); + } + } + } + } + catch (IndexOutOfRangeException) + { + return false; + } + + Interlocked.MemoryBarrier(); + return Volatile.Read(ref _mutation) == stamp; + } + + // The words of the 256-byte line at `line` that bytes [start, end) overlap (end > line, start < line + 256). + private static ulong LineWordBits(ulong line, ulong start, ulong end) + { + var first = (int)((Math.Max(start, line) - line) >> 2); + var last = (int)((Math.Min(end, line + 256) - 1 - line) >> 2); + var span = last - first + 1; + return (span >= 64 ? ulong.MaxValue : (1UL << span) - 1) << first; + } + /// /// read from another thread, like : /// false when the worker changed the records meanwhile (the answer is then unknown). diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.ConcurrentResolve.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.ConcurrentResolve.cs index 36a5f40d3..f7d8b48ef 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.ConcurrentResolve.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.ConcurrentResolve.cs @@ -214,6 +214,65 @@ internal enum ConcurrentQuery : byte internal bool ConcurrentScopedSerial { get; set; } = ConcurrentScopedSerialDefault; + // SHARPEMU_CONCURRENT_LINE_MASKS=0 tests every word read in an owned line of an owned page on its own, as before; + // =verify answers each such word both ways and fails (fatal, mask_verify_failed) where they differ. + // + // With it on (and ConcurrentScopedSerial, which fixes the completed serial for the resolution), the line's test + // (ConcurrentLineOwner) takes each owner apart instead of stopping at the first: queued command writes, GPU-modified + // images, the two overlays, and the pending GPU writes as a mask of the line's 64 words read from the write + // records at one mutation stamp. A line only GPU writes own keeps that mask, and a word in it is answered from the + // mask instead of its own ConcurrentOwner: GpuWrite where its bits are set, None elsewhere, recorded exactly as the + // word's own test is (same query, range and answer), so the worker re-checks the same answers at the take. + // Demon's Souls' draws read ~20 words a job out of lines a pending copy writes (~167k word tests a frame, each a + // walk of the write records). + // + // Why the mask's answer is the word's own test's answer at the time of the read: what the worker (and the command + // thread) can change while the resolver reads, and what tells the resolver it did: + // - queued command writes ahead of the job (PendingCommandWriteHolds): only ever released for a job, never added + // (a range queued after the job was submitted is not ahead of it), so none over the line then means none over + // the word now; + // - GPU-modified images and the two overlays: anything that makes bytes newly owned moves OwnershipVersions (the + // argument CrossDrawCleanPages rests on); the versions are read before the line's tests and compared at the + // word, so none over the line then means none over the word now; + // - the write records: every change (a write noted, records retired, folded or cleared, and the bounds MayCover + // reads) happens inside one mutation of MetalGpuWriteRanges; the mask is read between two equal even stamps and + // the stamp is compared at the word, so the records the word's own walk would read are the mask's records, and + // the serial is the same scoped serial. + // A word whose line moved a version or the stamp, an unaligned word, or a line some other owner holds, takes its own + // test as before (mask_stale, mask_refused). The answer is recorded at the word as before, so the take's re-check + // (IsConcurrentResolveStillCurrent) is unchanged. + internal enum LineMaskMode : byte + { + Off, + On, + Verify, + } + + private static readonly LineMaskMode ConcurrentLineMasksDefault = + Environment.GetEnvironmentVariable("SHARPEMU_CONCURRENT_LINE_MASKS") switch + { + "0" => LineMaskMode.Off, + "verify" => LineMaskMode.Verify, + _ => LineMaskMode.On, + }; + + internal LineMaskMode ConcurrentLineMasks { get; set; } = ConcurrentLineMasksDefault; + + private long _lineMaskVerifyFailed; + + /// + /// What a line test found for each owner (ConcurrentLineOwner): usable when only pending GPU writes own bytes of + /// the line, and then their words () as of write-record stamp and the + /// ownership versions read before any of the line's tests. + /// + internal struct LineSummary + { + public bool Usable; + public int Stamp; + public ulong Mask; + public (long Overlay, long Labels, ulong GpuWrites, long Images, long GpuModified) Versions; + } + // What an ownership test costs, counted where it runs (a resolution, a re-check) and added to the host's // totals once per resolution or re-check, for the PERF line: owner_tests=(...). internal enum OwnerTestCounter @@ -225,9 +284,19 @@ internal enum OwnerTestCounter ImageLock, SerialRead, OverlayCall, + // Words of an owned line answered from its mask (ConcurrentLineMasks); words of a masked line that took + // their own test because a version or the record stamp moved (stale) or the word is unaligned (refused, + // with the words of lines some other owner holds); words verified both ways. + MaskWord, + MaskStale, + MaskRefused, + MaskVerified, + // Words a pending copy writes, answered from the copy line (TryReadGuestWordConcurrent). + CopyLineWord, } - private static readonly string[] OwnerTestCounterNames = ["page", "line", "word", "recheck", "image_locks", "serial_reads", "overlay_calls"]; + private static readonly string[] OwnerTestCounterNames = + ["page", "line", "word", "recheck", "image_locks", "serial_reads", "overlay_calls", "mask_words", "mask_stale", "mask_refused", "mask_verified", "copy_line_words"]; private readonly long[] _ownerTests = new long[OwnerTestCounterNames.Length]; @@ -297,7 +366,8 @@ internal string TakeOwnerTestCounters() .Append(Interlocked.Exchange(ref _ownerTests[index], 0)); } - return builder.Append(')').ToString(); + // Not reset: one is a bug. + return builder.Append(",mask_verify_failed=").Append(Interlocked.Read(ref _lineMaskVerifyFailed)).Append(')').ToString(); } internal sealed class ConcurrentAssumptions( @@ -333,6 +403,17 @@ internal sealed class ConcurrentAssumptions( public ulong WordLine = ulong.MaxValue; public readonly byte[] WordLineBytes = new byte[ConcurrentWordLineBytes]; + // The line of the last word read through a pending copy with its owner from a line mask, and the words of it + // (CopyLineWords) read through the same copy then (FillCopyLine), with the stamp and versions they stand for. + public ulong CopyLine = ulong.MaxValue; + public ulong CopyLineWords; + public int CopyLineStamp; + public (long Overlay, long Labels, ulong GpuWrites, long Images, long GpuModified) CopyLineVersions; + public readonly byte[] CopyLineBytes = new byte[ConcurrentWordLineBytes]; + + // The ring slot whose mask answered IsOwnedRecorded's last test, or -1. + public int LastMaskSlot = -1; + // Taken again from the pool for a new resolution. public void Reset((long Overlay, long Labels, ulong GpuWrites, long Images, long GpuModified) versions) { @@ -345,6 +426,8 @@ public void Reset((long Overlay, long Labels, ulong GpuWrites, long Images, long Array.Fill(_lines, ulong.MaxValue); _nextLine = 0; WordLine = ulong.MaxValue; + CopyLine = ulong.MaxValue; + LastMaskSlot = -1; ForgetSerial(); } @@ -356,25 +439,42 @@ public void NoteOwnedPage(ConcurrentQuery query, ulong page) _nextOwnedPage = (_nextOwnedPage + 1) & (_ownedPages.Length - 1); } + // Beside each line, what its test found per owner (ConcurrentLineMasks); not usable when not taken. + private readonly LineSummary[] _lineSummaries = new LineSummary[8]; + // Null when the line has not been tested in this resolution (or has left the ring). public bool? LineOwned(ConcurrentQuery query, ulong line) + { + var slot = FindLine(query, line); + return slot < 0 ? null : LineIsOwned(slot); + } + + // The line's slot in the ring, or -1. + public int FindLine(ConcurrentQuery query, ulong line) { var key = line | (ulong)query; - foreach (var entry in _lines) + for (var slot = 0; slot < _lines.Length; slot++) { - if ((entry & ~LineOwnedBit) == key) + if ((_lines[slot] & ~LineOwnedBit) == key) { - return (entry & LineOwnedBit) != 0; + return slot; } } - return null; + return -1; } - public void NoteLine(ConcurrentQuery query, ulong line, bool owned) + public bool LineIsOwned(int slot) => (_lines[slot] & LineOwnedBit) != 0; + + public ref readonly LineSummary Summary(int slot) => ref _lineSummaries[slot]; + + public int NoteLine(ConcurrentQuery query, ulong line, bool owned, in LineSummary summary = default) { - _lines[_nextLine] = line | (ulong)query | (owned ? LineOwnedBit : 0); + var slot = _nextLine; + _lines[slot] = line | (ulong)query | (owned ? LineOwnedBit : 0); + _lineSummaries[slot] = summary; _nextLine = (_nextLine + 1) & (_lines.Length - 1); + return slot; } public bool IsCleanPage(ConcurrentQuery query, ulong page) @@ -489,6 +589,12 @@ internal object EndConcurrentResolve() { var assumptions = _concurrentAssumptions ?? throw new InvalidOperationException("No concurrent resolution is open."); _concurrentAssumptions = null; + var copyLineWords = assumptions.Counters[(int)OwnerTestCounter.CopyLineWord]; + if (copyLineWords != 0) + { + Interlocked.Add(ref _concurrentCopyReads, copyLineWords); + } + FlushOwnerTests(assumptions); return assumptions; } @@ -678,6 +784,7 @@ private bool PendingCommandWriteHolds(ulong address, ulong size) => // otherwise for the range itself. private bool IsOwnedRecorded(ConcurrentQuery query, ulong address, ulong size, ConcurrentAssumptions assumptions) { + assumptions.LastMaskSlot = -1; var page = address & ~(ConcurrentPageBytes - 1); var withinPage = size != 0 && size <= ConcurrentPageBytes && address - page <= ConcurrentPageBytes - size; if (withinPage) @@ -725,22 +832,39 @@ private bool IsOwnedRecorded(ConcurrentQuery query, ulong address, ulong size, C var line = address & ~((ulong)ConcurrentWordLineBytes - 1); if (ownedLines && size <= ConcurrentWordLineBytes && address - line <= ConcurrentWordLineBytes - size) { - var lineOwned = assumptions.LineOwned(query, line); - if (lineOwned is null) + var slot = assumptions.FindLine(query, line); + bool lineOwned; + if (slot < 0) { assumptions.Count(OwnerTestCounter.Line); - lineOwned = ConcurrentOwner(line, ConcurrentWordLineBytes, assumptions) != AbandonCause.None; - assumptions.NoteLine(query, line, lineOwned.Value); - if (!lineOwned.Value) + LineSummary summary = default; + lineOwned = ConcurrentLineMasks != LineMaskMode.Off && assumptions.Scoped + ? ConcurrentLineOwner(line, assumptions, out summary) + : ConcurrentOwner(line, ConcurrentWordLineBytes, assumptions) != AbandonCause.None; + slot = assumptions.NoteLine(query, line, lineOwned, summary); + if (!lineOwned) { assumptions.Record(query, line, ConcurrentWordLineBytes, false); } } + else + { + lineOwned = assumptions.LineIsOwned(slot); + } - if (!lineOwned.Value) + if (!lineOwned) { return false; } + + if (TryLineMaskOwner(assumptions, slot, line, address, size, out var maskOwner)) + { + _lastConcurrentOwner = maskOwner; + assumptions.LastMaskSlot = slot; + var maskOwned = maskOwner != AbandonCause.None; + assumptions.Record(query, address, size, maskOwned); + return maskOwned; + } } } @@ -751,6 +875,132 @@ private bool IsOwnedRecorded(ConcurrentQuery query, ulong address, ulong size, C return owned; } + // ConcurrentOwner(line, 256) != None, with each owner tested (ConcurrentLineMasks): the same tests in the same + // order, the pending GPU writes as a word mask, and the overlays asked even when a GPU write already owns the line. + // The summary is usable when the mask is known and nothing but GPU writes owns bytes of the line. + private bool ConcurrentLineOwner(ulong line, ConcurrentOwnerScope scope, out LineSummary summary) + { + const ulong size = ConcurrentWordLineBytes; + summary = default; + // Read before any test below: a change after this that could make a word of the line owned moves one of them. + var versions = OwnershipVersions(); + if (PendingCommandWriteHolds(line, size)) + { + return true; + } + + if (_imageCache.MayOwn(line, size)) + { + scope.Count(OwnerTestCounter.ImageLock); + if (_imageCache.HasGpuModifiedImageBytes(line, size)) + { + return true; + } + } + + // MayCover reads bounds the records' mutations change, so an even stamp read before it stands for its answer too. + ulong mask = 0; + var stamp = _gpuWrites.MutationStamp; + var known = (stamp & 1) == 0; + if (_gpuWrites.MayCover(line, size)) + { + var completed = scope.Serial(); + known = false; + for (var attempt = 0; attempt < 4 && !known; attempt++) + { + known = _gpuWrites.TryPendingWordMask(line, completed, out mask, out stamp); + if (!known) + { + Thread.SpinWait(8); + } + } + + if (!known) + { + // IsGpuWritePendingConcurrent's answer when the records keep changing: pending. + return true; + } + } + + var cp = false; + if (_cpOverlay.Count != 0) + { + scope.Count(OwnerTestCounter.OverlayCall); + cp = _cpOverlay.Coverage(line, size, scope.Serial) != MetalOverlayCoverage.None; + } + + var label = false; + if (_labelOverlay.Count != 0) + { + scope.Count(OwnerTestCounter.OverlayCall); + label = _labelOverlay.Coverage(line, size, scope.Serial) != MetalOverlayCoverage.None; + } + + summary = new LineSummary { Usable = known && !cp && !label, Stamp = stamp, Mask = mask, Versions = versions }; + return mask != 0 || cp || label; + } + + // The owner of a word of a line tested with ConcurrentLineOwner, from its mask, while the versions and the record + // stamp the mask was taken at stand (see ConcurrentLineMasks). False: the word takes its own test. + private bool TryLineMaskOwner(ConcurrentAssumptions assumptions, int slot, ulong line, ulong address, ulong size, out AbandonCause owner) + { + owner = AbandonCause.None; + var mode = ConcurrentLineMasks; + if (mode == LineMaskMode.Off) + { + return false; + } + + ref readonly var summary = ref assumptions.Summary(slot); + if (!summary.Usable || ((address | size) & 3) != 0) + { + assumptions.Count(OwnerTestCounter.MaskRefused); + return false; + } + + if (_gpuWrites.MutationStamp != summary.Stamp || OwnershipVersions() != summary.Versions) + { + assumptions.Count(OwnerTestCounter.MaskStale); + return false; + } + + // Inside the line (IsOwnedRecorded's test), whole words: bits first .. first + words - 1. + var first = (int)((address - line) >> 2); + var words = (int)(size >> 2); + var bits = (words >= 64 ? ulong.MaxValue : (1UL << words) - 1) << first; + owner = (summary.Mask & bits) != 0 ? AbandonCause.GpuWrite : AbandonCause.None; + assumptions.Count(OwnerTestCounter.MaskWord); + if (mode == LineMaskMode.Verify) + { + VerifyLineMaskOwner(assumptions, summary, address, size, owner); + } + + return true; + } + + // SHARPEMU_CONCURRENT_LINE_MASKS=verify: the word's own test as well. Only a difference while the versions and the + // stamp still stand is a wrong answer (one moved, both answers may be right at their times). + private void VerifyLineMaskOwner(ConcurrentAssumptions assumptions, in LineSummary summary, ulong address, ulong size, AbandonCause maskOwner) + { + var own = ConcurrentOwner(address, size, assumptions); + if (_gpuWrites.MutationStamp != summary.Stamp || OwnershipVersions() != summary.Versions) + { + return; + } + + if (own == maskOwner) + { + assumptions.Count(OwnerTestCounter.MaskVerified); + return; + } + + Interlocked.Increment(ref _lineMaskVerifyFailed); + var message = $"[METAL-V2][LINE_MASK] verify mismatch address=0x{address:X16} size={size} mask=0x{summary.Mask:X16} " + + $"mask_owner={maskOwner} own_owner={own}."; + Console.Error.WriteLine(message); + throw GpuFatal.Fatal(message); + } + // SHARPEMU_CONCURRENT_CROSS_CLEAN=0 tests every page of every resolution again. A page found clean stays // clean while the ownership versions stand: only a new recorded GPU write, overlay entry or image change // makes a clean page owned, and each of those moves a version (a write finishing only makes one clean). So @@ -841,6 +1091,28 @@ private bool TryReadGuestWordConcurrent(ulong address, out uint word, Concurrent return true; } + if ((address & ~lineMask) == assumptions.CopyLine && (address & 3) == 0 && + ((assumptions.CopyLineWords >> (int)((address & lineMask) >> 2)) & 1) != 0) + { + var copied = System.Buffers.Binary.BinaryPrimitives.ReadUInt32LittleEndian( + assumptions.CopyLineBytes.AsSpan((int)(address & lineMask), sizeof(uint))); + assumptions.Count(OwnerTestCounter.CopyLineWord); + if (ConcurrentLineMasks != LineMaskMode.Verify) + { + word = copied; + return true; + } + + return VerifyCopyLineWord(address, copied, out word, assumptions); + } + + return TryReadGuestWordConcurrentTested(address, out word, assumptions); + } + + // A word read with its own ownership test (or its line's mask), and through a pending copy where one writes it. + private bool TryReadGuestWordConcurrentTested(ulong address, out uint word, ConcurrentAssumptions assumptions) + { + const ulong lineMask = ConcurrentWordLineBytes - 1; word = 0; Span bytes = stackalloc byte[sizeof(uint)]; if (IsOwnedRecorded(ConcurrentQuery.Word, address, sizeof(uint), assumptions)) @@ -850,11 +1122,17 @@ private bool TryReadGuestWordConcurrent(ulong address, out uint word, Concurrent var owner = _lastConcurrentOwner; if (owner == AbandonCause.GpuWrite) { + var maskSlot = assumptions.LastMaskSlot; var answers = assumptions.Answers.Count; if (TryReadThroughPendingCopyConcurrent(address, bytes, assumptions)) { assumptions.Forget(ConcurrentQuery.Word, address, sizeof(uint), answers); word = System.Buffers.Binary.BinaryPrimitives.ReadUInt32LittleEndian(bytes); + if (maskSlot >= 0 && (address & 3) == 0) + { + FillCopyLine(assumptions, maskSlot, address & ~lineMask); + } + return true; } diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.CopyReads.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.CopyReads.cs index 627fa3cfc..fc1afbdb6 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.CopyReads.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.CopyReads.cs @@ -2,6 +2,7 @@ // SPDX-License-Identifier: GPL-2.0-or-later using System.Collections.Concurrent; +using SharpEmu.Libs.Gpu.Scheduling; namespace SharpEmu.Gpu.Metal.V2; @@ -355,6 +356,95 @@ private bool TryReadCopySourceConcurrent(PendingCopy copy, ulong address, Span + /// Right after a word was read through pending copy _verifiedCopy with its owner from the mask of its line + /// (ConcurrentLineMasks), the other words of the line that copy writes are read through it too, into the + /// resolution's copy line, and later reads of them take the bytes from there (TryReadGuestWordConcurrent). Each is + /// what TryReadGuestWordConcurrentTested returns for that word at this moment, with the same answers left recorded: + /// - its owner: the mask's bit (GpuWrite), while the stamp and the versions the mask stands for stand, which is + /// checked here, at the same moment as the read; + /// - TryReadThroughPendingCopyConcurrent: no GPU-modified image over the line (its summary, at these versions), + /// and the verified copy, which covers the word and was verified at the current record stamp, so its fast path + /// takes this same copy; + /// - TryReadCopySourceConcurrent: a source word in a page this resolution found clean answers unowned with + /// nothing recorded (a source word anywhere else is left out, for its own read to test and record), then the + /// source bytes are read; + /// - the owned answer the word's test records is dropped again by the read-through: nothing is left for it. + /// So the copy line holds those reads done now, as the clean word line holds a clean line read whole: the later + /// read of a word takes the answer it would have got here, and the worker's re-check at the take sees the same + /// recorded answers (the source pages' clean answers, recorded when they were tested) as before. + /// + private void FillCopyLine(ConcurrentAssumptions assumptions, int slot, ulong line) + { + assumptions.CopyLine = ulong.MaxValue; + ref readonly var summary = ref assumptions.Summary(slot); + var stamp = _gpuWrites.MutationStamp; + if (!summary.Usable || stamp != summary.Stamp || OwnershipVersions() != summary.Versions || + _verifiedCopy is not { } copy || _verifiedCopyHost != this || _verifiedCopyStamp != stamp) + { + return; + } + + var lineEnd = line + ConcurrentWordLineBytes; + var start = Math.Max(line, copy.Destination); + var end = Math.Min(lineEnd, copy.DestinationEnd); + ulong words = 0; + var at = start; + while (at < end) + { + // A run of words whose source words follow each other, up to the end of the copy's period. + var index = (at - copy.Destination) / sizeof(uint) % copy.Period; + var runWords = Math.Min((end - at) / sizeof(uint), copy.Period - index); + var runBytes = runWords * sizeof(uint); + var source = copy.Source + index * sizeof(uint); + if (assumptions.IsCleanPage(ConcurrentQuery.Word, source & ~(ConcurrentPageBytes - 1)) && + assumptions.IsCleanPage(ConcurrentQuery.Word, (source + runBytes - 1) & ~(ConcurrentPageBytes - 1)) && + _backing.TryReadBacking(source, assumptions.CopyLineBytes.AsSpan((int)(at - line), (int)runBytes))) + { + var first = (int)((at - line) / sizeof(uint)); + words |= (runWords >= 64 ? ulong.MaxValue : (1UL << (int)runWords) - 1) << first; + } + + at += runBytes; + } + + // Only words the mask gives to a GPU write: another word of the line answers None and reads guest memory. + words &= summary.Mask; + if (words != 0) + { + assumptions.CopyLine = line; + assumptions.CopyLineWords = words; + assumptions.CopyLineStamp = stamp; + assumptions.CopyLineVersions = summary.Versions; + } + } + + // SHARPEMU_CONCURRENT_LINE_MASKS=verify: a copy-line word read again with its own test, which must give the same + // bytes while the stamp and versions the copy line was filled at stand. + private bool VerifyCopyLineWord(ulong address, uint copied, out uint word, ConcurrentAssumptions assumptions) + { + var line = assumptions.CopyLine; + var stamp = assumptions.CopyLineStamp; + var versions = assumptions.CopyLineVersions; + var read = TryReadGuestWordConcurrentTested(address, out word, assumptions); + if (_gpuWrites.MutationStamp != stamp || OwnershipVersions() != versions || _verifiedCopyStamp != stamp) + { + return read; + } + + if (read && word == copied) + { + assumptions.Count(OwnerTestCounter.MaskVerified); + return true; + } + + Interlocked.Increment(ref _lineMaskVerifyFailed); + var message = $"[METAL-V2][LINE_MASK] copy line verify mismatch address=0x{address:X16} line=0x{line:X16} " + + $"copied=0x{copied:X8} read={read} word=0x{word:X8}."; + Console.Error.WriteLine(message); + throw GpuFatal.Fatal(message); + } + /// /// Answers a read the GPU is still writing from the source of the pending copy that /// writes it, without waiting. False leaves the read to wait as before. diff --git a/tests/SharpEmu.Gpu.Metal.Tests/MetalClearFoldingTests.CrossDrawCleanPages.cs b/tests/SharpEmu.Gpu.Metal.Tests/MetalClearFoldingTests.CrossDrawCleanPages.cs index e01eb08f2..47d95c3ea 100644 --- a/tests/SharpEmu.Gpu.Metal.Tests/MetalClearFoldingTests.CrossDrawCleanPages.cs +++ b/tests/SharpEmu.Gpu.Metal.Tests/MetalClearFoldingTests.CrossDrawCleanPages.cs @@ -178,6 +178,8 @@ public void TheWordsOfAnOwnedLineAreTestedOneByOneAndAnOwnedWordAbandons() using var rig = new Rig(Device.Value); var host = rig.Host; host.ConcurrentOwnedLines = true; + // Answered from the line's mask otherwise (MetalClearFoldingTests.LineMasks). + host.ConcurrentLineMasks = MetalRenderHost.LineMaskMode.Off; WriteOwnedPage(rig); _ = host.TakeOwnerTestCounters(); var concurrent = (IConcurrentResolveHost)host; diff --git a/tests/SharpEmu.Gpu.Metal.Tests/MetalClearFoldingTests.LineMasks.cs b/tests/SharpEmu.Gpu.Metal.Tests/MetalClearFoldingTests.LineMasks.cs new file mode 100644 index 000000000..e5fd8caa6 --- /dev/null +++ b/tests/SharpEmu.Gpu.Metal.Tests/MetalClearFoldingTests.LineMasks.cs @@ -0,0 +1,161 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using SharpEmu.Gpu.Metal.V2; +using SharpEmu.Libs.Gpu.Abstractions; +using SharpEmu.Libs.Gpu.GpuCommands; +using SharpEmu.Libs.Gpu.Rendering; +using SharpEmu.Libs.Gpu.Scheduling; +using Xunit; + +namespace SharpEmu.Gpu.Metal.Tests; + +/// +/// The words of an owned line answered from the line's mask, and the words a pending copy writes read from the copy +/// line (MetalRenderHost.ConcurrentLineMasks), against the same resolution with every word tested on its own: one +/// owned word among free ones in the line (a pending GPU write, a pending copy, a pending label), the same bytes or +/// the same abandon for every read, the same recorded answers, and the worker's re-check deciding the same way +/// before and after the owner's source changes. +/// +public sealed unsafe partial class MetalClearFoldingTests +{ + private const ulong MaskLine = OwnedPage + 0x400; + private const ulong MaskCopySource = GuestBase + 0x68000; + + private sealed record MaskOutcome( + string Reads, string Answers, bool CurrentAtTake, bool CurrentAfterSourceWrite, string Abandons, string Counters); + + private static MaskOutcome ResolveAroundAnOwnedWord(string owner, MetalRenderHost.LineMaskMode mode) + { + using var rig = new Rig(Device.Value); + var host = rig.Host; + host.ConcurrentOwnedLines = true; + host.ConcurrentScopedSerial = true; + host.ConcurrentLineMasks = mode; + host.ConcurrentCopyReads = true; + for (var word = 0UL; word < ConcurrentPageWords; word++) + { + rig.WriteBacking32(OwnedPage + word * sizeof(uint), 0xD000u + (uint)word); + rig.WriteBacking32(MaskCopySource + word * sizeof(uint), 0xC000u + (uint)word); + } + + // The owned bytes sit at MaskLine + 0x40 .. 0x80 (copy) or at the word MaskLine + 0x80. + ulong[] reads; + switch (owner) + { + case "gpu_write": + host.NoteGuestMemoryWrite(MaskLine + 0x80, sizeof(uint), MetalGpuWriteOrigin.StorageBuffer); + reads = [MaskLine, MaskLine + 0x7C, MaskLine + 0x84, MaskLine + 0xFC, MaskLine + 0x80]; + break; + case "copy": + Assert.False(host.TryCopyWordsOnHost(MaskLine + 0x40, MaskCopySource, 4, 16)); + host.NoteGuestMemoryWrite(MaskLine + 0x40, 16 * sizeof(uint), MetalGpuWriteOrigin.StorageBuffer); + host.ResetBindings(); + reads = [MaskLine, MaskLine + 0x44, MaskLine + 0x48, MaskLine + 0x7C, MaskLine + 0x40, MaskLine + 0x80, MaskLine + 0x3C]; + break; + case "label": + host.LabelOverlayEnabled = true; + host.RecordEndOfPipe(new EndOfPipeWrite(EndOfPipeWriteKind.Write32, 1, MaskLine + 0x80, 0x1234)); + reads = [MaskLine, MaskLine + 0x84, MaskLine + 0x80]; + break; + default: + throw new ArgumentOutOfRangeException(nameof(owner)); + } + + _ = host.TakeOwnerTestCounters(); + _ = host.TakeAbandonCauses(); + var concurrent = (IConcurrentResolveHost)host; + var log = new System.Text.StringBuilder(); + concurrent.BeginConcurrentResolve(); + object assumptions; + try + { + foreach (var address in reads) + { + log.Append($"0x{address - MaskLine:X}="); + try + { + log.Append(host.TryReadGuestWord(address, out var word) ? $"0x{word:X}" : "refused"); + } + catch (GpuFatal.AbandonedWorkException) + { + log.Append("abandoned"); + break; + } + finally + { + log.Append(' '); + } + + // A run over the owned bytes, through the resident reader. + if (address == MaskLine + 0x7C) + { + log.Append($"run={host.TryReadResidentGuestBytes(MaskLine + 0x78, new byte[16], clean: false)} "); + } + } + } + finally + { + assumptions = concurrent.EndConcurrentResolve(); + } + + var answers = string.Join(' ', ((MetalRenderHost.ConcurrentAssumptions)assumptions).Answers + .Select(answer => $"{answer.Query}:0x{answer.Address:X}+{answer.Size}:{answer.Owned}")); + var counters = host.TakeOwnerTestCounters(); + var abandons = host.TakeAbandonCauses(); + var current = concurrent.IsStillCurrent(assumptions); + // A write on the copy's source (and on a clean line of the owned page) moves a version: every answer is checked again. + host.NoteGuestMemoryWrite(MaskCopySource + 4, sizeof(uint), MetalGpuWriteOrigin.StorageBuffer); + host.NoteGuestMemoryWrite(MaskLine + 0x100, sizeof(uint), MetalGpuWriteOrigin.StorageBuffer); + var currentAfter = concurrent.IsStillCurrent(assumptions); + concurrent.ReleaseAssumptions(assumptions); + return new MaskOutcome(log.ToString(), answers, current, currentAfter, abandons, counters); + } + + [Theory] + [InlineData("gpu_write")] + [InlineData("copy")] + [InlineData("label")] + public void AnOwnedWordAmongFreeOnesIsAnsweredAndCheckedAgainAsWithoutTheLineMask(string owner) + { + if (!RequireDevice()) return; + var tested = ResolveAroundAnOwnedWord(owner, MetalRenderHost.LineMaskMode.Off); + var masked = ResolveAroundAnOwnedWord(owner, MetalRenderHost.LineMaskMode.On); + var verified = ResolveAroundAnOwnedWord(owner, MetalRenderHost.LineMaskMode.Verify); + + Assert.Equal(tested.Reads, masked.Reads); + Assert.Equal(tested.Answers, masked.Answers); + Assert.Equal(tested.CurrentAtTake, masked.CurrentAtTake); + Assert.Equal(tested.CurrentAfterSourceWrite, masked.CurrentAfterSourceWrite); + Assert.Equal(tested.Abandons, masked.Abandons); + Assert.Equal((tested.Reads, tested.Answers, tested.CurrentAtTake, tested.CurrentAfterSourceWrite, tested.Abandons), + (verified.Reads, verified.Answers, verified.CurrentAtTake, verified.CurrentAfterSourceWrite, verified.Abandons)); + Assert.Equal(0, OwnerTestCount(verified.Counters, "mask_verify_failed")); + Assert.Equal(0, OwnerTestCount(masked.Counters, "word") - (owner == "label" ? OwnerTestCount(masked.Counters, "mask_refused") : 0)); + + switch (owner) + { + case "gpu_write": + // Free words read as the backing holds them, the run over the write refused, the written word abandons. + Assert.Equal("0x0=0xD100 0x7C=0xD11F run=False 0x84=0xD121 0xFC=0xD13F 0x80=abandoned ", tested.Reads); + Assert.True(OwnerTestCount(masked.Counters, "mask_words") >= 5, masked.Counters); + Assert.True(OwnerTestCount(verified.Counters, "mask_verified") >= 5, verified.Counters); + break; + case "copy": + // Copied words read as the copy's source (period 4), the words around the copy as the backing. + Assert.Equal("0x0=0xD100 0x44=0xC001 0x48=0xC002 0x7C=0xC003 run=False 0x40=0xC000 0x80=0xD120 0x3C=0xD10F ", tested.Reads); + Assert.True(tested.CurrentAtTake); + Assert.False(tested.CurrentAfterSourceWrite); + // 0x44 read through the copy fills the copy line; 0x48, 0x7C and 0x40 come from it. + Assert.Equal(3, OwnerTestCount(masked.Counters, "copy_line_words")); + Assert.True(OwnerTestCount(verified.Counters, "mask_verified") >= 3, verified.Counters); + break; + case "label": + // A line a label owns has no usable mask: its words take their own tests. + Assert.EndsWith("0x80=abandoned ", tested.Reads); + Assert.Equal(0, OwnerTestCount(masked.Counters, "mask_words")); + Assert.True(OwnerTestCount(masked.Counters, "mask_refused") >= 2, masked.Counters); + break; + } + } +} diff --git a/tests/SharpEmu.Gpu.Metal.Tests/MetalGpuWriteRangesTests.cs b/tests/SharpEmu.Gpu.Metal.Tests/MetalGpuWriteRangesTests.cs index 20a36357b..5bd851786 100644 --- a/tests/SharpEmu.Gpu.Metal.Tests/MetalGpuWriteRangesTests.cs +++ b/tests/SharpEmu.Gpu.Metal.Tests/MetalGpuWriteRangesTests.cs @@ -712,4 +712,45 @@ public void MeasurePendingSerialWhenRequested() cleanMemo = Environment.GetEnvironmentVariable("SHARPEMU_METAL_V2_WRITE_CLEAN_MEMO") != "0", rounds }, new JsonSerializerOptions { WriteIndented = true })); } + // The line mask a resolution answers the words of an owned line from (MetalRenderHost.ConcurrentLineMasks): for every + // whole-word range of a line, a set bit exactly where TryPendingSerialSnapshot finds a pending write, over records + // and labels at byte offsets that do not fall on word boundaries, completed and pending serials, and an unbounded write. + [Fact] + public void ALineMaskAnswersEveryWholeWordRangeAsThePendingSnapshotDoes() + { + var random = new Random(7); + for (var trial = 0; trial < 40; trial++) + { + var ranges = new MetalGpuWriteRanges(); + const ulong Base = 0x40_0000; + for (var write = 0; write < 1 + trial % 6; write++) + { + var start = Base + (ulong)random.Next(0, 0x400); + var size = (ulong)random.Next(1, trial % 3 == 0 ? 8 : 0x180); + var origin = random.Next(4) == 0 ? MetalGpuWriteOrigin.EndOfPipeLabel : MetalGpuWriteOrigin.StorageBuffer; + ranges.Note(start, size, serial: (ulong)random.Next(1, 6), origin); + } + + if (trial == 39) + { + ranges.NoteUnbounded(serial: 9); + } + + var completed = (ulong)random.Next(0, 4); + for (var line = Base; line < Base + 0x600; line += 256) + { + Assert.True(ranges.TryPendingWordMask(line, completed, out var mask, out var stamp)); + Assert.Equal(ranges.MutationStamp, stamp); + for (var first = 0; first < 64; first++) + for (var words = 1; first + words <= 64; words += 1 + words / 4) + { + var address = line + (ulong)first * 4; + var size = (ulong)words * 4; + Assert.True(ranges.TryPendingSerialSnapshot(address, size, completed, out var pending)); + var bits = (words == 64 ? ulong.MaxValue : (1UL << words) - 1) << first; + Assert.True((pending != 0) == ((mask & bits) != 0), $"trial {trial} line 0x{line:X} words {first}+{words}"); + } + } + } + } } From bfe3bbcbfb2abb25c2df69d4d4fc72c1b359b10b Mon Sep 17 00:00:00 2001 From: kuba Date: Sun, 15 Nov 2026 14:21:57 +0000 Subject: [PATCH 069/178] [VideoOut] Overlay: restating an unchanged capture demand does not resume a paused phase capture The overlay states its demand with every snapshot (OverlayTelemetry.Touch), and SetOverlayCapture resumed the capture each time, so the render thread's one-frame-in-four sampling never applied: every frame read the clock twice per scope (about 10% of the Metal worker's CPU in a Demon's Souls sample). --- .../VideoOut/RenderPhaseProfile.cs | 13 ++++++-- .../VideoOut/Overlay/OverlayTelemetryTests.cs | 30 +++++++++++++++++++ 2 files changed, 41 insertions(+), 2 deletions(-) diff --git a/src/SharpEmu.Libs/VideoOut/RenderPhaseProfile.cs b/src/SharpEmu.Libs/VideoOut/RenderPhaseProfile.cs index 81be4ee48..fb7c59bf6 100644 --- a/src/SharpEmu.Libs/VideoOut/RenderPhaseProfile.cs +++ b/src/SharpEmu.Libs/VideoOut/RenderPhaseProfile.cs @@ -269,8 +269,17 @@ public enum Phase internal static void SetOverlayCapture(bool phases, bool timeline) { + timeline &= phases; + if (phases == _overlayPhasesWanted && timeline == _overlayTimelineWanted) + { + // The overlay states its demand again with every snapshot it takes. What it wants has not changed, so + // the render thread's sampling stands: resuming the capture here put every frame back under the clock + // (a paused capture lasted only until the overlay's next snapshot, a few milliseconds). + return; + } + _overlayPhasesWanted = phases; - _overlayTimelineWanted = phases && timeline; + _overlayTimelineWanted = timeline; _overlaySkip = 0; if (phases) { @@ -278,7 +287,7 @@ internal static void SetOverlayCapture(bool phases, bool timeline) Volatile.Write(ref _overlayCaptureStart, Stopwatch.GetTimestamp()); } - _overlayTimeline = phases && timeline; + _overlayTimeline = timeline; _overlayPhases = phases; } diff --git a/tests/SharpEmu.Libs.Tests/VideoOut/Overlay/OverlayTelemetryTests.cs b/tests/SharpEmu.Libs.Tests/VideoOut/Overlay/OverlayTelemetryTests.cs index a9cb77815..4f3dfcc1c 100644 --- a/tests/SharpEmu.Libs.Tests/VideoOut/Overlay/OverlayTelemetryTests.cs +++ b/tests/SharpEmu.Libs.Tests/VideoOut/Overlay/OverlayTelemetryTests.cs @@ -121,6 +121,36 @@ public void FramesCarryRenderPhasesTimelineAndGpuUnion() Assert.Equal(4f, OverlayTelemetry.DataSource.Capture().Frames[^1].GpuMs, 2); } + // The overlay states its demand with every snapshot. That must not resume a capture the render thread paused + // until its next sampled frame: it did, so every frame was timed and the sampling never applied. + [Fact] + public void AnOverlaySnapshotDoesNotResumeAPausedCapture() + { + if (RenderPhaseProfile.OverlayPhaseSample == 1 || RenderPhaseProfile.Enabled) + { + return; + } + + OverlayTelemetry.DataSource.SetCaptureDemand(OverlayCaptureDemand.RenderPhases | OverlayCaptureDemand.Timeline); + Assert.True(RenderPhaseProfile.Measuring); + RenderPhaseProfile.RecordFrame(); + Assert.False(RenderPhaseProfile.Measuring); + for (var frame = 1; frame < RenderPhaseProfile.OverlayPhaseSample; frame++) + { + _ = OverlayTelemetry.DataSource.Capture(); + OverlayTelemetry.DataSource.SetCaptureDemand(OverlayCaptureDemand.RenderPhases | OverlayCaptureDemand.Timeline); + Assert.False(RenderPhaseProfile.Measuring); + RenderPhaseProfile.RecordFrame(); + } + + // The sampled frame, and a changed demand still takes effect at once. + Assert.True(RenderPhaseProfile.Measuring); + RenderPhaseProfile.RecordFrame(); + Assert.False(RenderPhaseProfile.Measuring); + OverlayTelemetry.DataSource.SetCaptureDemand(OverlayCaptureDemand.RenderPhases); + Assert.True(RenderPhaseProfile.Measuring); + } + [Fact] public void FramesBetweenCapturedOnesShowTheLastCapturedRenderBreakdown() { From a6965c3d9e1a75fa63a9ad5731bd764a944a5808 Mon Sep 17 00:00:00 2001 From: kuba Date: Sun, 15 Nov 2026 14:51:27 +0000 Subject: [PATCH 070/178] [Metal] Stamp an image's last use with the collection's clock, not a clock read per use With SHARPEMU_LOG_MEMORY=1 (every ds.sh run) LastAccessTick read the clock on every texture binding and attachment acquire: ~1.7% of Demon's Souls' GPU worker in the 12 s sample (ReacquireMemoRun, LookUpImageLocked, AcquireDepthAttachment). The census buckets idle images by 1, 10 and 60 s; the clock read once per collection (the end of every guest submission) is fine-grained enough. DsDrawCost bench, SHARPEMU_LOG_MEMORY=1, ABBA: GameShaped 3.305/3.321 -> 3.221/3.240 us/draw thread CPU. --- src/graphics/SharpEmu.Gpu.Metal/V2/MetalCachedImage.cs | 8 +++++++- .../SharpEmu.Gpu.Metal/V2/MetalImageCache.Tracking.cs | 5 +++++ 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalCachedImage.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalCachedImage.cs index 9d60b117d..ea5c4efaf 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalCachedImage.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalCachedImage.cs @@ -420,7 +420,7 @@ public ulong LastAccessTick _lastAccessTick = value; if (SharpEmu.Logging.MemoryTelemetry.Enabled) { - LastAccessTimestamp = System.Diagnostics.Stopwatch.GetTimestamp(); + LastAccessTimestamp = Volatile.Read(ref AccessClock); } } } @@ -428,6 +428,12 @@ public ulong LastAccessTick /// Stopwatch ticks of the last use; kept only with SHARPEMU_LOG_MEMORY=1 (idle-age census). public long LastAccessTimestamp; + // The time a use is stamped with: read once per collection (MetalImageCache.Collect, at the end of every guest + // submission), not per use. Every texture binding and attachment sets LastAccessTick, and a clock read there + // was ~1.7% of Demon's Souls' GPU worker in every SHARPEMU_LOG_MEMORY=1 run; the census buckets idle images by + // a second, ten and sixty, which one submission's lag does not move. + internal static long AccessClock = System.Diagnostics.Stopwatch.GetTimestamp(); + // The submission serial of the command buffer that last wrote the image, so a // writeback knows whether the GPU work it depends on has been recorded. public ulong GpuWriteSerial; diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.Tracking.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.Tracking.cs index de5d7e0a6..d17a93fbc 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.Tracking.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.Tracking.cs @@ -615,6 +615,11 @@ public void Collect() { using var held = _lock.Hold(); _collectionTick++; + if (SharpEmu.Logging.MemoryTelemetry.Enabled) + { + Volatile.Write(ref MetalCachedImage.AccessClock, System.Diagnostics.Stopwatch.GetTimestamp()); + } + DrainRetiredImages(); PruneFencedWritebacks(); var now = _clock(); From 30c717fdb4a17dd820bd917baf75fbd20661aa10 Mon Sep 17 00:00:00 2001 From: kuba Date: Sun, 15 Nov 2026 15:05:56 +0000 Subject: [PATCH 071/178] [GPU] Keep the targets' version when target registers are written again with their values A material or program bind writes the shader interface, depth control and target mask again with every draw; each write moved the target stamps, ResolveTargetLayout resolved the targets again under a new version, and the recorder then found and acquired every attachment again (RepeatsPreviousTargets missed on target_version). The layout now keeps the context fields the colour and depth resolvers read (TargetInputs: colour target words, target mask, depth words, depth clear/bounds bits, stencil clear/control/masks); when the stamps moved but those fields hold the same values, the resolved targets and their version stay, and only the pixel stage is checked again. DrawResolutionInputsTests writes every context register and checks that one the inputs do not cover leaves the resolved targets alone. SHARPEMU_TARGET_VALUE_REUSE=0 resolves on every write as before; =verify resolves again on every kept draw and stops on a difference. Counters on the TBDR line: in_place_miss_by=(dropped,inactive,scope,binding,image_set,target_version,shape, programs,trace), in_place_dropped_by=(...) and target_values=(kept,pixel_stage,resolved). --- .../Gpu/Rendering/DrawResolution.cs | 73 ++++++++++ .../Gpu/Rendering/RenderExecutor.Targets.cs | 125 ++++++++++++++++-- .../RenderRecorder.TessellationEmulation.cs | 2 +- .../Gpu/Rendering/RenderRecorder.cs | 74 +++++++++-- .../Scenes/TargetRebindSceneTests.cs | 99 ++++++++++++++ .../Rendering/DrawResolutionInputsTests.cs | 116 ++++++++++++++++ .../Gpu/Rendering/RenderExecutorDrawTests.cs | 104 ++++++++++++++- .../Rendering/RenderExecutorTestSupport.cs | 4 + 8 files changed, 578 insertions(+), 19 deletions(-) create mode 100644 tests/SharpEmu.Gpu.Metal.Tests/Scenes/TargetRebindSceneTests.cs create mode 100644 tests/SharpEmu.Libs.Tests/Gpu/Rendering/DrawResolutionInputsTests.cs diff --git a/src/SharpEmu.Libs/Gpu/Rendering/DrawResolution.cs b/src/SharpEmu.Libs/Gpu/Rendering/DrawResolution.cs index 748b624df..acd228ede 100644 --- a/src/SharpEmu.Libs/Gpu/Rendering/DrawResolution.cs +++ b/src/SharpEmu.Libs/Gpu/Rendering/DrawResolution.cs @@ -1,6 +1,9 @@ // Copyright (C) 2026 SharpEmu Emulator Project // SPDX-License-Identifier: GPL-2.0-or-later +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using SharpEmu.Libs.Gpu.GpuCommands.Registers; using SharpEmu.Libs.Gpu.Images; using SharpEmu.Libs.Gpu.Pipelines; using SharpEmu.ShaderCompiler; @@ -17,6 +20,8 @@ internal sealed class DrawResolution public readonly uint[] ColorSlots = new uint[RenderingState.ColorAttachmentCapacity]; public DepthTargetState? Depth; public bool PixelActive; + // The context fields the colours and depth above were resolved from (TargetInputs.Matches). + public TargetInputs Inputs; public ulong ValidatedContextStamp; public ulong ValidatedUserConfigStamp; @@ -144,3 +149,71 @@ private static bool SameInterpolators(uint[]? first, uint[]? second) => ReferenceEquals(first, second) || (first is not null && second is not null && first.AsSpan().SequenceEqual(second)); } + +// Everything ColorTargetResolver and DepthTargetResolver read from the context bank (the colour target words, the +// target mask, the depth words and the depth/stencil state fields beside them); the resolvers are pure functions of +// these, so a draw whose target registers were written again with the same values resolves the same targets. Floats +// are compared by their bits (a -0 clear value is not a +0 one). DrawResolutionInputsTests writes every context +// register and checks that one these fields do not cover leaves the resolved targets alone. +internal struct TargetInputs +{ + [InlineArray(ContextRegisters.ColorTargetCount)] + internal struct ColorWords + { + private ColorTargetWords _first; + } + + public ColorWords Colors; + public uint RenderTargetMask; + public DepthTargetWords Depth; + public uint DepthClearBits; + public uint DepthBoundsMinBits; + public uint DepthBoundsMaxBits; + public byte StencilClearValue; + public StencilControlRegisters StencilControl; + public StencilMaskRegisters StencilMask; + public bool Captured; + + public void Capture(ContextRegisters context) + { + context.ColorTargets.AsSpan(0, ContextRegisters.ColorTargetCount).CopyTo(Colors); + RenderTargetMask = context.RenderTargetMask; + Depth = context.DepthTarget; + DepthClearBits = BitConverter.SingleToUInt32Bits(context.DepthClearValue); + DepthBoundsMinBits = BitConverter.SingleToUInt32Bits(context.DepthBoundsMin); + DepthBoundsMaxBits = BitConverter.SingleToUInt32Bits(context.DepthBoundsMax); + StencilClearValue = context.StencilClearValue; + StencilControl = context.StencilControl; + StencilMask = context.StencilMask; + Captured = true; + } + + public readonly bool Matches(ContextRegisters context) + { + if (!Captured || RenderTargetMask != context.RenderTargetMask || Depth != context.DepthTarget || + DepthClearBits != BitConverter.SingleToUInt32Bits(context.DepthClearValue) || + DepthBoundsMinBits != BitConverter.SingleToUInt32Bits(context.DepthBoundsMin) || + DepthBoundsMaxBits != BitConverter.SingleToUInt32Bits(context.DepthBoundsMax) || + StencilClearValue != context.StencilClearValue || + !SameBytes(in StencilControl, in context.StencilControl) || !SameBytes(in StencilMask, in context.StencilMask)) + { + return false; + } + + ReadOnlySpan colors = Colors; + var current = context.ColorTargets; + for (var slot = 0; slot < colors.Length; slot++) + { + if (colors[slot] != current[slot]) + { + return false; + } + } + + return true; + } + + // Both register structs are bytes only: no padding, so their bytes are their value. + private static bool SameBytes(in T left, in T right) where T : unmanaged => + MemoryMarshal.AsBytes(new ReadOnlySpan(in left)).SequenceEqual(MemoryMarshal.AsBytes(new ReadOnlySpan(in right))); +} diff --git a/src/SharpEmu.Libs/Gpu/Rendering/RenderExecutor.Targets.cs b/src/SharpEmu.Libs/Gpu/Rendering/RenderExecutor.Targets.cs index 5dd1f3110..fb81e8f23 100644 --- a/src/SharpEmu.Libs/Gpu/Rendering/RenderExecutor.Targets.cs +++ b/src/SharpEmu.Libs/Gpu/Rendering/RenderExecutor.Targets.cs @@ -1,6 +1,7 @@ // Copyright (C) 2026 SharpEmu Emulator Project // SPDX-License-Identifier: GPL-2.0-or-later +using SharpEmu.HLE.Diagnostics; using SharpEmu.Libs.Gpu.Abstractions; using SharpEmu.Libs.Gpu.Buffers; using SharpEmu.Libs.Gpu.GpuCommands.Registers; @@ -128,24 +129,35 @@ private DrawResolution ResolveTargetLayout(RegisterBanks banks) } var context = banks.Context; - resolution.ColorCount = 0; - for (var slot = 0u; slot < ContextRegisters.ColorTargetCount; slot++) + if (TargetValueReuse && resolution.TargetVersion != 0 && resolution.Inputs.Matches(context)) { - if (slot != 0 && (context.RenderTargetMaskForSlot(slot) == 0 || context.ColorTargets[slot].BaseAddress == 0)) + // Target registers written again with the values they held (a material or program bind rewrites the + // shader interface, the depth control or the target mask with each draw): the same targets, under the + // same version, so the recorder keeps their acquisitions (RenderRecorder.RepeatsPreviousTargets). + if (TargetValueReuseVerify) { - continue; + VerifyTargetLayout(context, resolution); } - if (ColorTargetResolver.Resolve(context, slot, DrawLayerOffset, ignoreTargetMask: false, out var resolvedSlot) is not { } color) + resolution.TargetContextStamp = contextStamp; + resolution.TargetProgramsStamp = programsStamp; + var pixelActive = HasActivePixelShader(banks); + if (pixelActive == resolution.PixelActive) { - continue; + _targetValuesKept.Increment(); + return resolution; } - resolution.Colors[resolution.ColorCount] = color; - resolution.ColorSlots[resolution.ColorCount++] = resolvedSlot; + _targetValuesPixelStage.Increment(); + resolution.PixelActive = pixelActive; + resolution.TargetVersion = (uint)Interlocked.Increment(ref _targetVersions); + return resolution; } + _targetValuesResolved.Increment(); + resolution.ColorCount = ResolveColorTargets(context, resolution.Colors, resolution.ColorSlots); resolution.Depth = DepthTargetResolver.Resolve(context, _host.FormatSupport, HostFatal); + resolution.Inputs.Capture(context); resolution.PixelActive = HasActivePixelShader(banks); resolution.TargetContextStamp = contextStamp; resolution.TargetProgramsStamp = programsStamp; @@ -153,6 +165,103 @@ private DrawResolution ResolveTargetLayout(RegisterBanks banks) return resolution; } + internal static int ResolveColorTargets(ContextRegisters context, ColorTargetResolution[] colors, uint[] slots) + { + var count = 0; + for (var slot = 0u; slot < ContextRegisters.ColorTargetCount; slot++) + { + if (slot != 0 && (context.RenderTargetMaskForSlot(slot) == 0 || context.ColorTargets[slot].BaseAddress == 0)) + { + continue; + } + + if (ColorTargetResolver.Resolve(context, slot, DrawLayerOffset, ignoreTargetMask: false, out var resolvedSlot) is not { } color) + { + continue; + } + + colors[count] = color; + slots[count++] = resolvedSlot; + } + + return count; + } + + // A draw whose target registers changed stamp but not value keeps the resolved targets and their version + // (TargetInputs). SHARPEMU_TARGET_VALUE_REUSE=0 resolves them again and gives them a new version whenever a + // target register is written; =verify (or SHARPEMU_PERF_VERIFY=1) resolves them again on every kept draw as + // well and stops on a difference. + internal static readonly bool TargetValueReuse = Environment.GetEnvironmentVariable("SHARPEMU_TARGET_VALUE_REUSE") != "0"; + + internal static readonly bool TargetValueReuseVerify = + TargetValueReuse && (Environment.GetEnvironmentVariable("SHARPEMU_TARGET_VALUE_REUSE") == "verify" || + Environment.GetEnvironmentVariable("SHARPEMU_PERF_VERIFY") == "1"); + + private static readonly ThreadCounter _targetValuesKept = new(); + private static readonly ThreadCounter _targetValuesPixelStage = new(); + private static readonly ThreadCounter _targetValuesResolved = new(); + + /// Target layouts kept on equal values, kept with only the pixel stage flipped, and resolved again. + internal static string TakeTargetValueReport() => + FormattableString.Invariant( + $"target_values=(kept={_targetValuesKept.Take()},pixel_stage={_targetValuesPixelStage.Take()},resolved={_targetValuesResolved.Take()}) "); + + private readonly ColorTargetResolution[] _verifyColors = new ColorTargetResolution[RenderingState.ColorAttachmentCapacity]; + private readonly uint[] _verifySlots = new uint[RenderingState.ColorAttachmentCapacity]; + + private void VerifyTargetLayout(ContextRegisters context, DrawResolution resolution) + { + var count = ResolveColorTargets(context, _verifyColors, _verifySlots); + var depth = DepthTargetResolver.Resolve(context, _host.FormatSupport, HostFatal); + var same = count == resolution.ColorCount && SameDepth(depth, resolution.Depth); + for (var index = 0; same && index < count; index++) + { + same = _verifySlots[index] == resolution.ColorSlots[index] && SameColor(in _verifyColors[index], in resolution.Colors[index]); + } + + if (!same) + { + throw HostFatal( + $"A target layout kept on equal register values resolves differently: colors={resolution.ColorCount}->{count} " + + $"depth={resolution.Depth.HasValue}->{depth.HasValue} version={resolution.TargetVersion}."); + } + } + + internal static bool SameColor(in ColorTargetResolution left, in ColorTargetResolution right) => + SameRequest(left.Request, right.Request) && left with { Request = default } == right with { Request = default }; + + internal static bool SameDepth(DepthTargetState? left, DepthTargetState? right) + { + if (left is not { } first || right is not { } second) + { + return left.HasValue == right.HasValue; + } + + return SameRequest(first.Target.Request, second.Target.Request) && + first.Target with { Request = default } == second.Target with { Request = default } && first.State == second.State; + } + + // An image request field for field; the mip layouts by their levels, not by the array that holds them. + private static bool SameRequest(ImageRequest left, ImageRequest right) + { + for (var level = 0; level < ImageDescription.MaxLevels; level++) + { + if (!left.Description.MipLayout[level].Equals(right.Description.MipLayout[level])) + { + return false; + } + } + + var first = left; + var second = right; + first.Description.MipLayout = default; + second.Description.MipLayout = default; + return first.Description.Equals(second.Description) && first.View == second.View && first.Role == second.Role && + first.TraceTextureMetadataAddress == second.TraceTextureMetadataAddress && + string.Equals(first.TraceTextureDescriptor, second.TraceTextureDescriptor, StringComparison.Ordinal) && + first.TraceMetadataCompress == second.TraceMetadataCompress && first.TraceWriteCompress == second.TraceWriteCompress; + } + private bool VertexStageWritesMemory(RegisterBanks banks, ref DrawState state) { if (banks.Shader.Vertex.ExportAddress == 0) diff --git a/src/SharpEmu.Libs/Gpu/Rendering/RenderRecorder.TessellationEmulation.cs b/src/SharpEmu.Libs/Gpu/Rendering/RenderRecorder.TessellationEmulation.cs index bca5625ea..9e897ea68 100644 --- a/src/SharpEmu.Libs/Gpu/Rendering/RenderRecorder.TessellationEmulation.cs +++ b/src/SharpEmu.Libs/Gpu/Rendering/RenderRecorder.TessellationEmulation.cs @@ -31,7 +31,7 @@ internal bool RunTessellationHull(TessellationHullLaunch launch) return false; } - _inPlace.Valid = false; + DropInPlace(InPlaceDrop.Tessellation); ReleaseFragmentWrites(); _host.EndRendering("tessellation"); using (_host.BeginPreparation()) diff --git a/src/SharpEmu.Libs/Gpu/Rendering/RenderRecorder.cs b/src/SharpEmu.Libs/Gpu/Rendering/RenderRecorder.cs index cb168b6c1..c8fe8d2cb 100644 --- a/src/SharpEmu.Libs/Gpu/Rendering/RenderRecorder.cs +++ b/src/SharpEmu.Libs/Gpu/Rendering/RenderRecorder.cs @@ -44,12 +44,61 @@ internal sealed partial class RenderRecorder : IResolvedCommandSink public static string TakeInPlaceReport() => FormattableString.Invariant($"in_place={_inPlaceDraws.Take()} in_place_refused={_inPlaceRefused.Take()} ") + + TakeInPlaceMissReport() + RenderExecutor.TakeTargetValueReport() + FormattableString.Invariant($"pipe_kept={_pipelineKept.Take()} ") + FormattableString.Invariant($"pipe_missed={_pipelineMissed.Take()} pipe_same={_pipelineSame.Take()}"); + // Why a draw did not get the previous draw's targets (RepeatsPreviousTargets): the previous draw left none + // kept (dropped_by, what dropped them), no pass open or refreshes owed now (inactive), another pass (scope), + // the image cache's binding epoch or image set moved (binding, image_set), other target registers + // (target_version), or the same registers with another shape (pixel stage, counts) or programs. + private enum InPlaceMiss { Dropped, Inactive, Scope, Binding, ImageSet, TargetVersion, Shape, Programs, Trace, Count } + + private enum InPlaceDrop { None, Kind, Refound, Compiling, Stores, FragmentStores, Tessellation, Clear, NoPass, Count } + + private static readonly string[] InPlaceMissNames = ["dropped", "inactive", "scope", "binding", "image_set", "target_version", "shape", "programs", "trace"]; + private static readonly string[] InPlaceDropNames = ["none", "kind", "refound", "compiling", "stores", "fragment_stores", "tessellation", "clear", "no_pass"]; + private static readonly ThreadCounter[] _inPlaceMisses = Enumerable.Range(0, (int)InPlaceMiss.Count).Select(static _ => new ThreadCounter()).ToArray(); + private static readonly ThreadCounter[] _inPlaceDrops = Enumerable.Range(0, (int)InPlaceDrop.Count).Select(static _ => new ThreadCounter()).ToArray(); + + private static string TakeInPlaceMissReport() + { + var builder = new System.Text.StringBuilder("in_place_miss_by=("); + for (var index = 0; index < (int)InPlaceMiss.Count; index++) + { + builder.Append(index == 0 ? "" : ",").Append(InPlaceMissNames[index]).Append('=').Append(_inPlaceMisses[index].Take()); + } + + builder.Append(") in_place_dropped_by=("); + for (var index = 0; index < (int)InPlaceDrop.Count; index++) + { + builder.Append(index == 0 ? "" : ",").Append(InPlaceDropNames[index]).Append('=').Append(_inPlaceDrops[index].Take()); + } + + return builder.Append(") ").ToString(); + } + + private bool NoteInPlaceMiss(InPlaceMiss miss) + { + _inPlaceMisses[(int)miss].Increment(); + if (miss == InPlaceMiss.Dropped) + { + _inPlaceDrops[(int)_inPlace.DroppedBy].Increment(); + } + + return false; + } + + private void DropInPlace(InPlaceDrop reason) + { + _inPlace.Valid = false; + _inPlace.DroppedBy = reason; + } + private sealed class InPlaceDraw { public bool Valid; + public InPlaceDrop DroppedBy; public DrawScopeToken Token; public ulong ContextStamp; public ulong DynamicStamp; @@ -79,12 +128,20 @@ private bool RepeatsPreviousTargets(ResolvedDraw record, in DrawState state, Dra if (!kept.Valid || !token.IsActive || token != kept.Token || ImageClearTrace.Enabled || record.TargetVersion != kept.TargetVersion || state.PixelActive != kept.PixelActive || state.ColorCount != kept.FoundCount || state.DepthResolved != kept.DepthResolved) { - return false; + return NoteInPlaceMiss( + !kept.Valid ? InPlaceMiss.Dropped : + !token.IsActive ? InPlaceMiss.Inactive : + token.Scope != kept.Token.Scope ? InPlaceMiss.Scope : + token.Lookups != kept.Token.Lookups ? InPlaceMiss.Binding : + token.Metadata != kept.Token.Metadata ? InPlaceMiss.ImageSet : + ImageClearTrace.Enabled ? InPlaceMiss.Trace : + record.TargetVersion != kept.TargetVersion ? InPlaceMiss.TargetVersion : InPlaceMiss.Shape); } return (RenderExecutor.WideTargetReuse && _host.ReusesTargetsAcrossPrograms) || (record.ContextStamp == kept.ContextStamp && record.DynamicStamp == kept.DynamicStamp && - state.Programs.Vertex.Id == kept.VertexProgram && state.Programs.Pixel.Id == kept.PixelProgram); + state.Programs.Vertex.Id == kept.VertexProgram && state.Programs.Pixel.Id == kept.PixelProgram) || + NoteInPlaceMiss(InPlaceMiss.Programs); } private void RestoreFoundTargets(ref DrawState state) @@ -157,6 +214,7 @@ private void KeepTargets(ResolvedDraw record, ref DrawState state) // and the next draw acquiring the same targets finds it consumed. Handing that draw the clear // again restarted the pass with it (Metal: GTA V's render passes doubled). kept.Valid = kept.Token.IsActive && !CarriesClear(in state.Rendering); + kept.DroppedBy = kept.Valid ? InPlaceDrop.None : kept.Token.IsActive ? InPlaceDrop.Clear : InPlaceDrop.NoPass; kept.ContextStamp = record.ContextStamp; kept.DynamicStamp = record.DynamicStamp; kept.TargetVersion = record.TargetVersion; @@ -262,7 +320,7 @@ private void RecordDraw(ResolvedDraw record) ref var state = ref record.State; if (record.Kind != ResolvedDrawKind.Draw) { - _inPlace.Valid = false; + DropInPlace(InPlaceDrop.Kind); } switch (record.Kind) @@ -283,7 +341,7 @@ private void RecordDraw(ResolvedDraw record) case ResolvedDrawKind.Tessellation: FindTargets(ref state); RecordTessellation(record, ref state); - _inPlace.Valid = false; + DropInPlace(InPlaceDrop.Tessellation); break; case ResolvedDrawKind.ClearColorTargets: FindTargets(ref state); @@ -298,7 +356,7 @@ private void RecordDraw(ResolvedDraw record) } else { - _inPlace.Valid = false; + DropInPlace(InPlaceDrop.Refound); FindTargets(ref state); NoteFoundTargets(ref state); } @@ -611,7 +669,7 @@ private void RecordDrawCommands(ResolvedDraw record, ref DrawState state, bool i if (!ResolvePipeline(record, ref state, vertexInput, state.PixelActive ? pixelInput : null, pixelBindings is not null ? pixelInput.Stage : null, indirectMesh is not null, out var pipeline)) { - _inPlace.Valid = false; + DropInPlace(InPlaceDrop.Compiling); IndexedDrawTrace.Write(record.IndexedTrace, "pipeline-compiling", submitId, record.PacketAddress); return; } @@ -735,7 +793,7 @@ private void RecordDrawCommands(ResolvedDraw record, ref DrawState state, bool i if (writeStages != GpuPipelineStage.None) { if (MeshDrawTrace.Active) MeshDrawTrace.Write("write-barrier", $"sourceStages={writeStages}"); - _inPlace.Valid = false; + DropInPlace(InPlaceDrop.Stores); // Vertex-stage stores can be ordered inside the pass by a host that supports it; // ending the pass would store and reload every attachment for each such draw. if ((writeStages & GpuPipelineStage.FragmentShaderBit) != 0 || !_host.OrdersVertexWritesInsidePass) @@ -748,7 +806,7 @@ private void RecordDrawCommands(ResolvedDraw record, ref DrawState state, bool i else if (record.WriteStages != GpuPipelineStage.None) { // Only deferred fragment stores: the pass stays open, but its targets are not kept. - _inPlace.Valid = false; + DropInPlace(InPlaceDrop.FragmentStores); } else { diff --git a/tests/SharpEmu.Gpu.Metal.Tests/Scenes/TargetRebindSceneTests.cs b/tests/SharpEmu.Gpu.Metal.Tests/Scenes/TargetRebindSceneTests.cs new file mode 100644 index 000000000..0b45c5456 --- /dev/null +++ b/tests/SharpEmu.Gpu.Metal.Tests/Scenes/TargetRebindSceneTests.cs @@ -0,0 +1,99 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using System.Reflection; +using SharpEmu.Gpu.Metal.V2; +using Xunit; +using Xunit.Abstractions; + +namespace SharpEmu.Gpu.Metal.Tests.Scenes; + +/// +/// Draws that write their target registers again before each draw (DepthRig.State emits the targets and the depth +/// state every time), as a title's material binds do. With the same values the draws keep the targets' version and +/// the previous draw's attachments (RenderExecutor.ResolveTargetLayout): they must stay in one render pass and draw +/// what acquiring the targets again draws. Another value, or another target, still acquires them again. +/// +public sealed class TargetRebindSceneTests(ITestOutputHelper output) : SceneTestBase(output) +{ + private const uint Size = 64; + private const uint Red = 0xFF0000FF; + private const uint Green = 0xFF00FF00; + private const uint Blue = 0xFFFF0000; + + private static readonly FieldInfo RenderPasses = + typeof(MetalRenderHost).GetField("_renderPasses", BindingFlags.Instance | BindingFlags.NonPublic)!; + + [Fact] + public void DrawsRebindingTheSameTargetsStayInOnePass() + { + using var rig = CreateRig(); + if (rig is null) return; + var d = new DepthRig(rig, Size, Size, zFormat: 3); + // The depth memory starts at zero: the first draw writes 0.5 everywhere. + d.Draw(d.State().DepthControl(true, true, CompareFunc.Always), d.Full(0.5f, 1, 0, 0)); + for (var i = 0; i < 4; i++) + { + // Nearer, then farther: the depth the earlier draws wrote decides. + d.Draw(d.State().DepthControl(true, true, CompareFunc.LessEqual), d.Rect(i % 2 == 0 ? 0.25f : 0.75f, 0, 1, 0, i * 16, 0, (i * 16) + 16, 64)); + } + + var colour = d.QueueColorReadback(); + rig.Submit(d.Pm4); + var colours = colour(); + + Assert.Equal(1L, (long)RenderPasses.GetValue(rig.Host)!); + for (var i = 0; i < 4; i++) + { + Assert.Equal(i % 2 == 0 ? Green : Red, colours[(32 * Size) + (i * 16) + 8]); + } + } + + // Depth writes turned off under the same targets: a value the depth acquisition reads, so the draw acquires the + // depth target again; the pass goes on, and the later draws no longer write depth. + [Fact] + public void ADepthStateChangeUnderTheSameTargetsIsAcquiredAndKeepsThePass() + { + using var rig = CreateRig(); + if (rig is null) return; + var d = new DepthRig(rig, Size, Size, zFormat: 3); + d.Draw(d.State().DepthControl(true, true, CompareFunc.Always), d.Full(0.5f, 1, 0, 0)); + d.Draw(d.State().DepthControl(true, false, CompareFunc.Always), d.Rect(0.25f, 0, 1, 0, 0, 0, 32, 64)); + // Passes only where depth is still 0.5: the read-only draw before it wrote none. + d.Draw(d.State().DepthControl(true, true, CompareFunc.Greater), d.Rect(0.4f, 0, 0, 1, 0, 0, 64, 64)); + + var depth = d.QueueDepthReadback(); + var colour = d.QueueColorReadback(); + rig.Submit(d.Pm4); + var colours = colour(); + var depths = depth(); + + Assert.Equal(Green, colours[(32 * Size) + 8]); + Assert.Equal(Red, colours[(32 * Size) + 40]); + Assert.Equal(0.5f, depths[(32 * Size) + 8]); + Assert.Equal(0.5f, depths[(32 * Size) + 40]); + } + + // Another colour target between two draws into the first: three passes, each target with its own draws. + [Fact] + public void AnotherTargetBetweenRebindsEndsThePass() + { + using var rig = CreateRig(); + if (rig is null) return; + var d = new DepthRig(rig, Size, Size, zFormat: 3); + var other = rig.ColorTarget(Size, Size); + d.Draw(d.State().DepthControl(false, false, CompareFunc.Always), d.Full(0.5f, 1, 0, 0)); + d.Draw(new SceneState(Size, Size).ColorTarget(0, other, Size, Size).DepthControl(false, false, CompareFunc.Always), d.Full(0.5f, 0, 0, 1)); + d.Draw(d.State().DepthControl(false, false, CompareFunc.Always), d.Rect(0.5f, 0, 1, 0, 0, 0, 32, 64)); + + var colour = d.QueueColorReadback(); + rig.Submit(d.Pm4); + var colours = colour(); + var others = rig.ReadImage(other, Size, Size); + + Assert.Equal(3L, (long)RenderPasses.GetValue(rig.Host)!); + Assert.Equal(Green, colours[(32 * Size) + 8]); + Assert.Equal(Red, colours[(32 * Size) + 40]); + Assert.Equal(Blue, others[(32 * Size) + 40]); + } +} diff --git a/tests/SharpEmu.Libs.Tests/Gpu/Rendering/DrawResolutionInputsTests.cs b/tests/SharpEmu.Libs.Tests/Gpu/Rendering/DrawResolutionInputsTests.cs new file mode 100644 index 000000000..b871b89ee --- /dev/null +++ b/tests/SharpEmu.Libs.Tests/Gpu/Rendering/DrawResolutionInputsTests.cs @@ -0,0 +1,116 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using SharpEmu.Libs.Gpu.GpuCommands; +using SharpEmu.Libs.Gpu.GpuCommands.Registers; +using SharpEmu.Libs.Gpu.Images; +using SharpEmu.Libs.Gpu.Rendering; +using SharpEmu.Libs.Tests.Gpu.Images; +using Xunit; +using static SharpEmu.Libs.Tests.Gpu.Rendering.RenderExecutorFixtures; + +namespace SharpEmu.Libs.Tests.Gpu.Rendering; + +// TargetInputs must hold everything the colour and depth target resolvers read: a draw whose inputs match keeps the +// resolved targets and their version (RenderExecutor.ResolveTargetLayout), so a register that moved the resolved +// targets without moving the inputs would hand a draw the previous draw's attachments. +public sealed class DrawResolutionInputsTests +{ + private static readonly AcceptingFormatSupport Formats = new(); + + private static Exception Fatal(string message) => new RenderExecutorFatalException(message); + + [Theory] + [InlineData(0xFFFF_FFFFu)] + [InlineData(0x1234_5678u)] + [InlineData(0x0000_0001u)] + public void EveryContextRegisterThatLeavesTheInputsAloneLeavesTheResolvedTargetsAlone(uint value) + { + var unchanged = 0; + for (var offset = 0u; offset < RegisterBankLayout.ContextRegisterCount; offset++) + { + var banks = Banks(withDepth: true); + banks.Context.ColorTargets[1] = RegisterWords.Color(ColorBase + 0x10_0000, 64, 64); + banks.Context.RenderTargetMask = 0xFF; + var before = Resolve(banks.Context); + var inputs = default(TargetInputs); + inputs.Capture(banks.Context); + try + { + RegisterWriteTable.WriteContextEntry(banks, offset, value, tableAddress: 0); + } + catch (RenderExecutorFatalException) + { + continue; + } + + if (!inputs.Matches(banks.Context)) + { + continue; + } + + unchanged++; + var after = Resolve(banks.Context); + Assert.True(Same(before, after), $"Context register 0x{offset:X3} = 0x{value:X8} moved the resolved targets but not their inputs."); + } + + // Most of the bank is not a target register; the loop must have tested those. + Assert.True(unchanged > 0x300, $"Only {unchanged} registers left the inputs alone."); + } + + [Fact] + public void InputsTellANegativeZeroClearFromAPositiveOne() + { + var banks = Banks(withDepth: true); + var inputs = default(TargetInputs); + inputs.Capture(banks.Context); + Assert.True(inputs.Matches(banks.Context)); + banks.Context.DepthClearValue = -0f; + Assert.False(inputs.Matches(banks.Context)); + } + + [Fact] + public void UncapturedInputsMatchNothing() + { + Assert.False(default(TargetInputs).Matches(Banks().Context)); + } + + private static (int Count, ColorTargetResolution[] Colors, uint[] Slots, DepthTargetState? Depth) Resolve(ContextRegisters context) + { + var colors = new ColorTargetResolution[RenderingState.ColorAttachmentCapacity]; + var slots = new uint[RenderingState.ColorAttachmentCapacity]; + DepthTargetState? depth; + int count; + try + { + count = RenderExecutor.ResolveColorTargets(context, colors, slots); + depth = DepthTargetResolver.Resolve(context, Formats, Fatal); + } + catch (Exception exception) when (exception is RenderExecutorFatalException or ArgumentException or InvalidOperationException) + { + return (-1, colors, slots, null); + } + + return (count, colors, slots, depth); + } + + private static bool Same( + (int Count, ColorTargetResolution[] Colors, uint[] Slots, DepthTargetState? Depth) left, + (int Count, ColorTargetResolution[] Colors, uint[] Slots, DepthTargetState? Depth) right) + { + if (left.Count != right.Count || !RenderExecutor.SameDepth(left.Depth, right.Depth)) + { + return false; + } + + for (var index = 0; index < left.Count; index++) + { + if (left.Slots[index] != right.Slots[index] || !RenderExecutor.SameColor(in left.Colors[index], in right.Colors[index])) + { + return false; + } + } + + return true; + } +} diff --git a/tests/SharpEmu.Libs.Tests/Gpu/Rendering/RenderExecutorDrawTests.cs b/tests/SharpEmu.Libs.Tests/Gpu/Rendering/RenderExecutorDrawTests.cs index 95107a8d6..207de808d 100644 --- a/tests/SharpEmu.Libs.Tests/Gpu/Rendering/RenderExecutorDrawTests.cs +++ b/tests/SharpEmu.Libs.Tests/Gpu/Rendering/RenderExecutorDrawTests.cs @@ -133,6 +133,100 @@ public void ADrawAcquiresItsTargetsAgainOnceTheScopeOrTheRegistersChange() Assert.Contains(_host.Calls, call => call.StartsWith("acquire_color", StringComparison.Ordinal)); } + private const uint TargetStampBits = + (1u << (int)RegisterStamp.ColorTargets) | (1u << (int)RegisterStamp.DepthTargets) | (1u << (int)RegisterStamp.ShaderInterface); + + // A material or program bind writes the target registers again with the values they held: the draw keeps the + // targets' version, so it is given the previous draw's acquisitions (RenderExecutor.ResolveTargetLayout). + [Fact] + public void TargetRegistersWrittenAgainWithTheirValuesKeepTheAcquisitions() + { + _pipelines.Graphics = Programs(vertexBuffers: [new VertexInputBuffer(VertexBase, 16, 4)]); + _host.Scope = new DrawScopeToken(1, 1, 1); + _host.WideTargetReuse = true; + var banks = Banks(withDepth: true); + _executor.DrawIndexed(7, banks, Indexed(6)); + Assert.Contains(_host.Calls, call => call.StartsWith("acquire_depth", StringComparison.Ordinal)); + _host.Calls.Clear(); + banks.Context.ColorTargets[0] = banks.Context.ColorTargets[0] with { }; + banks.Context.DepthTarget = banks.Context.DepthTarget with { }; + banks.MarkWritten(TargetStampBits); + _executor.DrawIndexed(8, banks, Indexed(6)); + + Assert.DoesNotContain(_host.Calls, call => call.StartsWith("find_image", StringComparison.Ordinal) || + call.StartsWith("acquire_color", StringComparison.Ordinal) || call.StartsWith("acquire_depth", StringComparison.Ordinal)); + AssertOrder("bind_target", "prepare_bindings Vertex", "commit Graphics", "begin_rendering", "draw_indexed 6 1 0 0 0"); + } + + // Each change a target acquisition reads, written under the same stamps: the draw acquires its targets again. + [Theory] + [InlineData("color-address")] + [InlineData("target-mask")] + [InlineData("depth-control")] + [InlineData("depth-clear-negative-zero")] + [InlineData("depth-bounds")] + [InlineData("stencil-mask")] + [InlineData("pixel-stage")] + public void ATargetRegisterWrittenWithAnotherValueAcquiresTheTargetsAgain(string change) + { + _pipelines.Graphics = Programs(vertexBuffers: [new VertexInputBuffer(VertexBase, 16, 4)]); + _host.Scope = new DrawScopeToken(1, 1, 1); + _host.WideTargetReuse = true; + var banks = Banks(withDepth: true); + _executor.DrawIndexed(7, banks, Indexed(6)); + _host.Calls.Clear(); + var context = banks.Context; + switch (change) + { + case "color-address": + context.ColorTargets[0] = context.ColorTargets[0] with { BaseAddress = context.ColorTargets[0].BaseAddress + 0x1_0000 }; + break; + case "target-mask": + context.RenderTargetMask = 0x7; + break; + case "depth-control": + context.DepthTarget = context.DepthTarget with { DepthControl = context.DepthTarget.DepthControl ^ 0x4u }; + break; + case "depth-clear-negative-zero": + context.DepthClearValue = -0f; + break; + case "depth-bounds": + context.DepthBoundsMax = 0.5f; + break; + case "stencil-mask": + context.StencilMask = context.StencilMask with { WriteMask = 0x0F }; + break; + case "pixel-stage": + context.ShaderInterface.ColorShaderMask = 0; + break; + } + + banks.MarkWritten(TargetStampBits); + _executor.DrawIndexed(8, banks, Indexed(6)); + + Assert.Contains(_host.Calls, call => call.StartsWith("acquire_depth", StringComparison.Ordinal) || + call.StartsWith("acquire_color", StringComparison.Ordinal)); + } + + // The values hold but the pass does not: the scope token still decides. + [Fact] + public void TargetRegistersWrittenAgainWithTheirValuesInAnotherScopeAcquireAgain() + { + _pipelines.Graphics = Programs(vertexBuffers: [new VertexInputBuffer(VertexBase, 16, 4)]); + _host.Scope = new DrawScopeToken(1, 1, 1); + _host.WideTargetReuse = true; + var banks = Banks(withDepth: true); + _executor.DrawIndexed(7, banks, Indexed(6)); + foreach (var scope in new[] { new DrawScopeToken(2, 1, 1), new DrawScopeToken(2, 2, 1), new DrawScopeToken(2, 2, 2), default }) + { + _host.Scope = scope; + _host.Calls.Clear(); + banks.MarkWritten(TargetStampBits); + _executor.DrawIndexed(8, banks, Indexed(6)); + Assert.Contains(_host.Calls, call => call.StartsWith("acquire_color", StringComparison.Ordinal)); + } + } + [Fact] public void ADrawAfterATwoTargetDrawBindsOnlyItsOwnTarget() { @@ -1393,7 +1487,7 @@ public void SecondColorSlot_NeedsItsMaskNibbleAndAddress() } [Fact] - public void TargetLayout_IsKeptUntilAContextRegisterIsWritten() + public void TargetLayout_IsKeptUntilATargetRegisterChangesValue() { var banks = Banks(withDepth: true); _executor.DrawIndexed(1, banks, Indexed(3)); @@ -1403,9 +1497,15 @@ public void TargetLayout_IsKeptUntilAContextRegisterIsWritten() Assert.Equal(resolved, TargetLayoutVersion()); Assert.Equal(2, _host.Calls.Count(static call => call.StartsWith("begin_rendering 64x64x1 colors=1", StringComparison.Ordinal))); + // Written again with the values they held: the same targets (TargetInputs). + banks.MarkWritten(RegisterStamps.ContextBits); + _executor.DrawIndexed(1, banks, Indexed(3)); + Assert.Equal(resolved, TargetLayoutVersion()); + + banks.Context.DepthClearValue = 0.25f; banks.MarkWritten(RegisterStamps.ContextBits); _executor.DrawIndexed(1, banks, Indexed(3)); - Assert.Equal(resolved + 1, TargetLayoutVersion()); + Assert.True(TargetLayoutVersion() > resolved); } private uint TargetLayoutVersion() => diff --git a/tests/SharpEmu.Libs.Tests/Gpu/Rendering/RenderExecutorTestSupport.cs b/tests/SharpEmu.Libs.Tests/Gpu/Rendering/RenderExecutorTestSupport.cs index b853ef22b..16ce4e9b8 100644 --- a/tests/SharpEmu.Libs.Tests/Gpu/Rendering/RenderExecutorTestSupport.cs +++ b/tests/SharpEmu.Libs.Tests/Gpu/Rendering/RenderExecutorTestSupport.cs @@ -248,6 +248,10 @@ public bool MayLeaveOutWhileCompiling(in RenderingState rendering) public DrawScopeToken DrawScope => Scope; + public bool WideTargetReuse { get; set; } + + public bool ReusesTargetsAcrossPrograms => WideTargetReuse; + public void KeepDepthAttachment(in DepthAttachmentState depth) => Calls.Add($"keep_depth {depth.Image.Index}"); public ColorAttachmentAcquisition AcquireColorAttachment(in ColorTargetState target) From 71f671399cb3bb4a10537f34d6609a7e0859db38 Mon Sep 17 00:00:00 2001 From: kuba Date: Sun, 15 Nov 2026 15:05:58 +0000 Subject: [PATCH 072/178] [Tests] DS draw bench: SHARPEMU_DS_DRAW_BENCH_REBIND=n writes the targets again every nth draw, and reports in-place reuse and passes --- .../Scenes/DsDrawCostBenchTests.cs | 20 +++++++++++++++---- 1 file changed, 16 insertions(+), 4 deletions(-) diff --git a/tests/SharpEmu.Gpu.Metal.Tests/Scenes/DsDrawCostBenchTests.cs b/tests/SharpEmu.Gpu.Metal.Tests/Scenes/DsDrawCostBenchTests.cs index cce8885de..a78f58133 100644 --- a/tests/SharpEmu.Gpu.Metal.Tests/Scenes/DsDrawCostBenchTests.cs +++ b/tests/SharpEmu.Gpu.Metal.Tests/Scenes/DsDrawCostBenchTests.cs @@ -257,6 +257,9 @@ int Setting(string name, int fallback) => var rounds = Setting("ROUNDS", 40); var warm = Setting("WARM", 150); var only = Environment.GetEnvironmentVariable("SHARPEMU_DS_DRAW_BENCH_VARIATION"); + // _REBIND=n: every nth draw of a pass writes its targets and depth state again with the values they hold (no + // flush), as a title's material binds do; 0 (the default) writes them only at a pass's first draw. + var rebind = int.TryParse(Environment.GetEnvironmentVariable("SHARPEMU_DS_DRAW_BENCH_REBIND"), out var rebindEvery) && rebindEvery > 0 ? rebindEvery : 0; using var rig = CreateRig(); Assert.NotNull(rig); @@ -332,7 +335,8 @@ void EmitDraw(ScenePm4 pm4, int draw, int pass, bool fullState, (ulong table, ul var vertexProgram = vertexPrograms[(draw / 3) % vertexPrograms.Length]; var pixelProgram = pixelPrograms[attachments - 5][(draw / 2) % 4]; SceneState state; - if (fullState) + var rebound = !fullState && rebind != 0 && draw % rebind == rebind - 1; + if (fullState || rebound) { state = new SceneState(TargetSize, TargetSize) .DepthTarget(depths[set], TargetSize, TargetSize, zFormat: 3) @@ -343,7 +347,7 @@ void EmitDraw(ScenePm4 pm4, int draw, int pass, bool fullState, (ulong table, ul state.Context[Cx.CbTargetMask] = mask; state.Context[Cx.CbShaderMask] = mask; state.Context[Cx.SpiShaderColFormat] = 0x99999999u & mask; - pm4.Event(ScenePm4.EventCsPartialFlush); + if (!rebound) pm4.Event(ScenePm4.EventCsPartialFlush); } else { @@ -388,7 +392,8 @@ uint[] DrawStream() var vertexProgram = vertexPrograms[(draw / 3) % vertexPrograms.Length]; var pixelProgram = pixelPrograms[attachments - 5][(draw / 2) % 4]; SceneState state; - if (draw % passLength == 0) + var rebound = draw % passLength != 0 && rebind != 0 && draw % rebind == rebind - 1; + if (draw % passLength == 0 || rebound) { state = new SceneState(TargetSize, TargetSize) .DepthTarget(depths[set], TargetSize, TargetSize, zFormat: 3) @@ -399,7 +404,7 @@ uint[] DrawStream() state.Context[Cx.CbTargetMask] = mask; state.Context[Cx.CbShaderMask] = mask; state.Context[Cx.SpiShaderColFormat] = 0x99999999u & mask; - pm4.Event(ScenePm4.EventCsPartialFlush); + if (!rebound) pm4.Event(ScenePm4.EventCsPartialFlush); } else { @@ -659,11 +664,13 @@ void ArmCopiedTables() var phaseTotals = new Dictionary(); long allocated = 0; long allAllocated = 0; + long passes = 0; var collections = 0; for (var round = 0; round < warm + rounds; round++) { if (round == warm) { + _ = SharpEmu.Libs.Gpu.Rendering.RenderRecorderStatistics.TakeInPlaceReport(); _ = PrefetchCounters.Invoke(rig.Host, null); _ = KeptProgramsReport.Invoke(null, null); } @@ -709,6 +716,7 @@ void ArmCopiedTables() var roundAll = GC.GetTotalAllocatedBytes(precise: false) - allBefore; var roundCollections = GC.CollectionCount(0) - collectionsBefore; rig.Drain(); + passes = (long)RenderPasses.GetValue(rig.Host)!; var counters = rig.Host.ReadAndResetPerfCounters(); if (round < warm) continue; wall.Add(elapsed * 1e6 / Stopwatch.Frequency / items); @@ -727,6 +735,8 @@ void ArmCopiedTables() } var prefetch = (string)PrefetchCounters.Invoke(rig.Host, null)!; + // The recorder's target reuse over the measured rounds, and the render passes of the last one. + var inPlace = SharpEmu.Libs.Gpu.Rendering.RenderRecorderStatistics.TakeInPlaceReport(); // The compute kept programs of the measured rounds; the graphics ones and the resolve memo are in the prefetch counters. var kept = (string)KeptProgramsReport.Invoke(null, null)!; // Read-only bindings answered from the one before (MetalReadBindingMemo) over every round, warm-up included. @@ -774,6 +784,8 @@ void Fold(ulong address, int count) counters = prefetch, kept, bindings, + inPlace, + passesLastRound = passes, phaseMicroseconds = phaseTotals.Where(pair => pair.Value / rounds >= 0.005) .OrderByDescending(pair => pair.Value).ToDictionary(pair => pair.Key, pair => Math.Round(pair.Value / rounds, 3)), }); From 5c9dc73fa41c5660b81b83207f6acebaba398480 Mon Sep 17 00:00:00 2001 From: kuba Date: Sun, 15 Nov 2026 15:06:01 +0000 Subject: [PATCH 073/178] [Metal] A read-only compute binding over held labels reads a staged view instead of landing them The dispatch fills a ring view in its own compute encoder (window words after a barrier, then the held copies over it in held order) and the copies stay held to the commit: no encoder split, shared event or copy encoder for the ~39 bind_read landings a Demon's Souls frame paid. Views are reused while nothing can have changed their bytes. Refusals counted (label_staged_refused); SHARPEMU_METAL_V2_LABEL_STAGED_READS=0 off, =verify checks each view against a real landing and each reuse against the window at completion. --- .../V2/MetalCommandStream.cs | 8 + .../V2/MetalRenderHost.Descriptors.cs | 8 + .../V2/MetalRenderHost.LabelLanding.cs | 4 + .../V2/MetalRenderHost.LabelStagedReads.cs | 739 ++++++++++++++++++ .../V2/MetalRenderHost.Rendering.cs | 4 +- .../V2/MetalRenderHost.StagedStorage.cs | 13 +- .../V2/MetalRenderHost.ThreadDispatch.cs | 2 +- .../SharpEmu.Gpu.Metal/V2/MetalRenderHost.cs | 2 + 8 files changed, 776 insertions(+), 4 deletions(-) create mode 100644 src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.LabelStagedReads.cs diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalCommandStream.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalCommandStream.cs index 9c9f97819..40b9aac0d 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalCommandStream.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalCommandStream.cs @@ -79,6 +79,7 @@ public void BeginSubmission(int queueId, ulong submissionId, object? geometrySna // for it (Demon's Souls begins ~190 submissions a frame). PostOrderingToWorker(() => { + NoteLabelStagedReadsSubmission(); NativeOcclusionBeginQueue(queueId); CommitCoalescedIfOverdue(); _ = EnsureCommandBuffer(); @@ -87,6 +88,7 @@ public void BeginSubmission(int queueId, ulong submissionId, object? geometrySna } DrainDraws(); + NoteLabelStagedReadsSubmission(); NativeOcclusionBeginQueue(queueId); _submissionsStarted++; CommitCoalescedIfOverdue(); @@ -1010,6 +1012,12 @@ private ulong EncodeOrderedCopies( bool noteAsOneRange = false) { ulong serial; + foreach (ref readonly var copy in copies) + { + // A staged label read over the same window bytes through another guest address is filled again. + NoteLabelStagedReadsCopy(in copy); + } + // A copy whose source later work in the same encoder may still change (the GDS a // pixel or compute shader appends to) cannot wait for the boundary: it would copy // what that later work left there. diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Descriptors.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Descriptors.cs index 318480642..92a011d10 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Descriptors.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Descriptors.cs @@ -936,6 +936,8 @@ public void BindResources(IPreparedBindings prepared) var info = stage.Program.Resources!.Info; var snapshot = stage.StageResources.Resources; NoteBindShape(stage, snapshot); + // A staged label read checks the stage's other bindings for writes over it (MetalRenderHost.LabelStagedReads.cs). + BeginLabelStagedStage(stage.Program.Stage == ShaderStageKind.Compute ? stage : null); for (var index = 0; index < stage.ImageCount; index++) { if (index == stage.MovieLuma || index == stage.MovieChroma) @@ -2222,6 +2224,12 @@ private void GrowUsedResourceIndex() // the draw touches. The guest windows live in the residency set instead. private void ApplyStageBindings(bool graphics) { + if (!graphics && _labelStagedPending.Count != 0) + { + // Every compute dispatch path fills them first (EncodeStagedLabelReads); one that does not would read the ring. + throw Fatal("A dispatch binds staged label reads that were never filled."); + } + if (graphics) { // A mesh pipeline has no vertex stage: the primitive shader's resources diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.LabelLanding.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.LabelLanding.cs index 76d28d53e..68105ecd6 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.LabelLanding.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.LabelLanding.cs @@ -18,6 +18,9 @@ namespace SharpEmu.Gpu.Metal.V2; /// labels, and the rest (GDS stores, occlusion dumps). /// label_force_by the first held copy a forcing range overlapped, and label_force_range that range's size. /// label_in_encoder_refused why a landing with a compute encoder open did not fold into it. +/// label_staged read-only compute bindings answered by a staged view instead of a landing (binds), views filled before +/// a dispatch (fills), fills skipped as still exact (reuse), KiB filled, and =verify checks and failures; +/// label_staged_refused why a binding over held copies landed them instead (MetalRenderHost.LabelStagedReads.cs). /// internal sealed partial class MetalRenderHost { @@ -200,6 +203,7 @@ private string TakeLabelLandingCounters() Append(text, "label_force_by", LabelForceByNames, _labelForceBy); Append(text, "label_force_range", LabelForceRangeNames, _labelForceRange); Append(text, "label_in_encoder_refused", LabelRefusedNames, _labelInEncoderRefused); + AppendLabelStagedCounters(text); return text.ToString(); static void Append(System.Text.StringBuilder text, string field, string[] names, long[] counts) diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.LabelStagedReads.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.LabelStagedReads.cs new file mode 100644 index 000000000..88914455e --- /dev/null +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.LabelStagedReads.cs @@ -0,0 +1,739 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using SharpEmu.Libs.Gpu.Rendering; + +namespace SharpEmu.Gpu.Metal.V2; + +/// +/// A read-only compute binding over held label copies reads a staged view of its bytes instead of landing the copies. +/// +/// +/// A held copy has two consumers. The guest CPU must not see a CPU-visible label before the stores ahead of it are +/// visible, which is what the shared event of a landing is for (EncodeLabelBarrier). A dispatch that reads the bytes +/// only needs them in device order. Landing the copies for such a dispatch ended the compute encoder, encoded the shared +/// event and a copy encoder, and opened a new compute encoder: Demon's Souls did that ~39 times a frame, each a ~135 us +/// GPU gap. Instead the binding gets a ring range, and right before the dispatch, inside its compute encoder, the range is +/// filled from the guest window (after a memory barrier, so after the earlier dispatches' stores; the encoder waited on +/// the encoder fence when it began, so after the earlier encoders) and then the held copies over it are applied in held +/// order, the last copy into a word winning, as the landing's blits or scatter would leave it. The copies stay held and +/// land at the commit, as before, behind one barrier. That is the bytes the dispatch would read after a landing: the +/// landing would write exactly these copies into exactly these bytes, behind the same earlier work. +/// Only where that holds: a compute stage, the fence chain, at most , a range one +/// window covers (the source), no staged storage copy concerning it, no binding or device-address range of the same +/// dispatch writing it (the dispatch would otherwise read its own stores from another buffer), and every held copy +/// over it holding its final value as host-written words (an end-of-pipe label or a command-processor write; not an +/// occlusion dump or a GDS copy, whose source later GPU work produces). Anything else lands as before, counted by reason +/// (label_staged_refused). +/// A view is filled again at each dispatch that binds it, unless nothing could have changed its bytes since its last +/// fill (label_staged reuse): same command buffer (the ring range is this submission's), same guest submission slice (a +/// later one may follow CPU stores made before its submit), no GPU write noted over it since (every GPU write into guest +/// memory - bindings, transfers, fills, image writebacks, label and command-processor copies - goes through +/// NoteGuestMemoryWriteBeyondOverlays), no held copy added over its window bytes, no unbounded device-address store, +/// and no landing since. +/// SHARPEMU_METAL_V2_LABEL_STAGED_READS=0 lands the copies for every such binding again; =verify also lands them right +/// after filling each view, copies the view and the window after the landing into a buffer of its own, and compares the +/// two at completion: a difference is fatal on the worker. +/// +internal sealed partial class MetalRenderHost +{ + private static readonly string? LabelStagedReadsMode = Environment.GetEnvironmentVariable("SHARPEMU_METAL_V2_LABEL_STAGED_READS"); + + internal bool LabelStagedReads { get; set; } = LabelStagedReadsMode != "0"; + + internal bool LabelStagedReadsVerify { get; set; } = LabelStagedReadsMode == "verify"; + + /// Tests: a range the dispatch being bound writes, as another of its bindings would (no stage to read it from). + internal (ulong Address, ulong Size) LabelStagedDispatchWriteForTest { get; set; } + + // Demon's Souls' forcing ranges are all below 64 KiB; a larger copy per dispatch could cost what the gap does. + internal const ulong LabelStagedReadMaxBytes = 64 * 1024; + + private const int LabelStagedReadTableSize = 64; + + internal enum LabelStagedRefusal + { + Graphics, + NoFence, + Large, + GpuSource, + Unaligned, + StagedStorage, + NotInPlace, + DispatchWrites, + Alias, + Count, + } + + private static readonly string[] LabelStagedRefusalNames = + ["graphics", "no_fence", "large", "gpu_source", "unaligned", "staged_storage", "not_in_place", "dispatch_writes", "alias"]; + + private static readonly string[] LabelStagedNames = ["binds", "fills", "reuse", "kb", "verify_checks", "verify_failed"]; + + private sealed class LabelStagedRead + { + public ulong Address; + public ulong Size; + // The window bytes the view copies, from the word holding Address: Window.Offset is that word's. + public MetalGuestRange Window; + public MetalGuestRange Staging; + public uint Lead; + public ulong Span; + public ulong Serial; + public ulong Epoch; + // Filled at a dispatch with nothing noted over it since. + public bool Fresh; + // Still in the table, so a later binding may find it. + public bool Listed; + // Bound by the dispatch being prepared, to be filled (or found fresh) right before it. + public bool Pending; + } + + private readonly List _labelStagedTable = []; + private readonly List _labelStagedPending = []; + private ulong _labelStagedLow = ulong.MaxValue; + private ulong _labelStagedHigh; + private ulong _labelStagedEpoch; + + // The compute stage BindResources is binding; its other bindings are checked for writes over a staged range. + private MetalStageBindings? _labelStagedStage; + + private readonly long[] _labelStagedRefused = new long[(int)LabelStagedRefusal.Count]; + private long _labelStagedBinds, _labelStagedFills, _labelStagedReuse, _labelStagedBytes; + private long _labelStagedVerifyChecks, _labelStagedVerifyFailed; + private string? _labelStagedVerifyFailure; + + // =verify: views a binding found fresh with no held copy over them any more, bound to the window as usual; the + // dispatch checks that the view still holds what the window does there (the reuse rule, without a landing). + private readonly List _labelStagedChecks = []; + + private readonly Dictionary _labelStagedWords = []; + private readonly Dictionary _labelStagedAddresses = []; + private LabelScatterWord[] _labelStagedList = new LabelScatterWord[64]; + private nint[] _labelStagedResources = new nint[8]; + private static readonly nint SelLabelStagedLength = MetalNative.Selector("length"); + private static readonly nint SelLabelStagedNewBuffer = MetalNative.Selector("newBufferWithLength:options:"); + + /// label_staged: binds, fills, reuse, kb, verify_checks, verify_failed since the last take (tests). + internal long[] TakeLabelStagedCounts() => + [ + Interlocked.Exchange(ref _labelStagedBinds, 0), Interlocked.Exchange(ref _labelStagedFills, 0), + Interlocked.Exchange(ref _labelStagedReuse, 0), Interlocked.Exchange(ref _labelStagedBytes, 0) / 1024, + Interlocked.Exchange(ref _labelStagedVerifyChecks, 0), Interlocked.Exchange(ref _labelStagedVerifyFailed, 0), + ]; + + /// label_staged_refused since the last take, in order (tests). + internal long[] TakeLabelStagedRefusals() + { + var counts = new long[_labelStagedRefused.Length]; + for (var index = 0; index < counts.Length; index++) counts[index] = Interlocked.Exchange(ref _labelStagedRefused[index], 0); + return counts; + } + + /// Views bound and not yet filled for a dispatch (tests). + internal int PendingLabelStagedReads => _labelStagedPending.Count; + + private void AppendLabelStagedCounters(System.Text.StringBuilder text) + { + var counts = TakeLabelStagedCounts(); + text.Append(" label_staged=["); + for (var index = 0; index < LabelStagedNames.Length; index++) + { + if (index != 0) text.Append(','); + text.Append(LabelStagedNames[index]).Append(':').Append(counts[index]); + } + + text.Append("] label_staged_refused=["); + for (var index = 0; index < LabelStagedRefusalNames.Length; index++) + { + if (index != 0) text.Append(','); + text.Append(LabelStagedRefusalNames[index]).Append(':').Append(Interlocked.Exchange(ref _labelStagedRefused[index], 0)); + } + + text.Append(']'); + } + + // A read-only binding of these bytes, which held copies touch: a view to bind instead of landing them, or false + // (counted when a reason refused it) to land them as before. untouched: no held copy touches the bytes and a fill + // over them has landed, which is all OrderAfterDeferredCopies would do. + private bool TryStageLabelRead(ulong address, ulong size, bool computeStage, out MetalGuestRange view, out bool untouched) + { + view = default; + untouched = false; + if (!LabelStagedReads || !LabelsAtCommit || size == 0 || size > ulong.MaxValue - address) + { + return false; + } + + if (_deferredLabelCopies.Count == 0) + { + NoteLabelStagedReuseCheck(address, size, computeStage); + return false; + } + + ThrowIfLabelStagedVerifyFailed(); + // As OrderAfterDeferredCopies: a fill the open pass holds over the bytes lands first, so the view sees it. + LandDeferredFillsOver(address, size); + if (!DeferredLabelCopiesTouch(address, size)) + { + untouched = true; + NoteLabelStagedReuseCheck(address, size, computeStage); + return false; + } + + if (!computeStage) + { + return RefuseLabelStagedRead(LabelStagedRefusal.Graphics); + } + + if (EncoderOrdering != EncoderOrderingMode.Fence) + { + // The view's fill reads the window in its dispatch's encoder, which must start after the encoders before it. + return RefuseLabelStagedRead(LabelStagedRefusal.NoFence); + } + + if (size > LabelStagedReadMaxBytes) + { + return RefuseLabelStagedRead(LabelStagedRefusal.Large); + } + + if (_stagedStorageCopies is { Count: > 0 } staged && staged.MayConcern(address, size)) + { + // A staged copy would answer the binding, or its stores are still to be written back over the bytes. + return RefuseLabelStagedRead(LabelStagedRefusal.StagedStorage); + } + + if ((_labelStagedStage is { } stage && DispatchWritesOver(stage, address, size)) || + (LabelStagedDispatchWriteForTest is var (writeAddress, writeSize) && writeAddress < address + size && address < writeAddress + writeSize)) + { + return RefuseLabelStagedRead(LabelStagedRefusal.DispatchWrites); + } + + if (!_guestMemory.TryResolveInPlace(address, size, out var window, out _, out _)) + { + return RefuseLabelStagedRead(LabelStagedRefusal.NotInPlace); + } + + var lead = (uint)(address & 3); + var span = (lead + size + 3) & ~3UL; + if ((window.Offset & 3) != lead || + window.Offset - lead + span > (ulong)MetalNative.Send(window.Buffer, SelLabelStagedLength)) + { + return RefuseLabelStagedRead(LabelStagedRefusal.Unaligned); + } + + var source = new MetalGuestRange(window.Buffer, window.Offset - lead, span, 0); + var refusal = HeldCopiesOver(address - lead, in source, build: false, staging: 0); + if (refusal != LabelStagedRefusal.Count) + { + return RefuseLabelStagedRead(refusal); + } + + var entry = FindLabelStagedRead(address, size, in source); + if (entry is null) + { + var staging = _guestMemory.Allocate(span, 16, out _); + if (!staging.IsValid || staging.GpuAddress == 0) + { + throw Fatal($"A staged label read has no ring room: address=0x{address:X16} size=0x{size:X}."); + } + + entry = new LabelStagedRead + { + Address = address, Size = size, Window = source, Staging = staging, Lead = lead, Span = span, + Serial = _submissionSerial, Epoch = _labelStagedEpoch, Listed = true, + }; + if (_labelStagedTable.Count == LabelStagedReadTableSize) + { + _labelStagedTable[0].Listed = false; + _labelStagedTable.RemoveAt(0); + } + + _labelStagedTable.Add(entry); + _labelStagedLow = Math.Min(_labelStagedLow, address - lead); + _labelStagedHigh = Math.Max(_labelStagedHigh, address - lead + span); + } + + if (!entry.Pending) + { + entry.Pending = true; + _labelStagedPending.Add(entry); + } + + _labelStagedBinds++; + _labelTouchClass = -1; + view = new MetalGuestRange(entry.Staging.Buffer, entry.Staging.Offset + lead, size, entry.Staging.GpuAddress + lead); + return true; + } + + // =verify: a view of exactly this range still listed as fresh is checked against the window at the dispatch. + private void NoteLabelStagedReuseCheck(ulong address, ulong size, bool computeStage) + { + if (!LabelStagedReadsVerify || !computeStage || _labelStagedTable.Count == 0 || + !_guestMemory.TryResolveInPlace(address, size, out var window, out _, out _)) + { + return; + } + + var lead = address & 3; + var source = new MetalGuestRange(window.Buffer, window.Offset - lead, (lead + size + 3) & ~3UL, 0); + if (FindLabelStagedRead(address, size, in source) is { Fresh: true } entry && !_labelStagedChecks.Contains(entry)) + { + _labelStagedChecks.Add(entry); + } + } + + private bool RefuseLabelStagedRead(LabelStagedRefusal reason) + { + _labelStagedRefused[(int)reason]++; + return false; + } + + private LabelStagedRead? FindLabelStagedRead(ulong address, ulong size, in MetalGuestRange source) + { + foreach (var entry in _labelStagedTable) + { + if (entry.Address == address && entry.Size == size) + { + if (entry.Serial == _submissionSerial && entry.Epoch == _labelStagedEpoch && + entry.Window.Buffer == source.Buffer && entry.Window.Offset == source.Offset) + { + return entry; + } + + // A view of another command buffer or guest submission, or another window: replaced. + entry.Listed = false; + _labelStagedTable.Remove(entry); + return null; + } + } + + return null; + } + + // Whether another binding or device-address range of the dispatch being bound writes these bytes: the dispatch would + // read them from the view while storing them through the window. Unplanned ranges and unbounded stores count. + private static bool DispatchWritesOver(MetalStageBindings stage, ulong address, ulong size) + { + var info = stage.Program.Resources!.Info; + var snapshot = stage.StageResources.Resources; + for (var index = 0; index < stage.BufferCount && index < info.Buffers.Count; index++) + { + if (!info.Buffers[index].Written) + { + continue; + } + + var words = snapshot.Buffers[index]; + if (words.Length < 4) + { + return true; + } + + var descriptor = BufferDescriptorWords.From(words); + if (descriptor.Footprint() is not { } footprint) + { + return true; + } + + if (descriptor.Address != 0 && footprint != 0 && + descriptor.Address < address + size && address < descriptor.Address + footprint) + { + return true; + } + } + + var declared = false; + foreach (var range in snapshot.DeviceAddressRanges) + { + if (!range.Planned) + { + return true; + } + + if (range.Written) + { + declared = true; + if (range.Base < address + size && address < range.Base + range.Size) + { + return true; + } + } + } + + return info.WritesDeviceAddresses && !declared; + } + + // The held copies over a view's window bytes (by guest address, or by the window buffer's bytes for an alias of + // them), in held order. Count when every one can be applied; otherwise why not. build: also make the scatter list + // into the staging at that GPU address (_labelStagedList, _labelStagedResources), returning the word count in + // _labelStagedWords.Count. + private LabelStagedRefusal HeldCopiesOver(ulong low, in MetalGuestRange source, bool build, ulong staging) + { + if (build) + { + _labelStagedWords.Clear(); + _labelStagedAddresses.Clear(); + } + + var span = source.Size; + var copies = System.Runtime.InteropServices.CollectionsMarshal.AsSpan(_deferredLabelCopies); + foreach (ref readonly var copy in copies) + { + var bytes = (ulong)copy.Bytes; + var byGuest = copy.GuestAddress < low + span && low < copy.GuestAddress + bytes; + var byBuffer = copy.DestinationBuffer == source.Buffer && + copy.DestinationOffset < source.Offset + span && source.Offset < copy.DestinationOffset + bytes; + if (!byGuest && !byBuffer) + { + continue; + } + + if (copy.Kind == LabelCopyKind.Other || copy.StagingBuffer == 0) + { + return LabelStagedRefusal.GpuSource; + } + + if (((bytes | copy.StagingOffset) & 3) != 0 || (byGuest && (copy.GuestAddress & 3) != 0) || + (byBuffer && (copy.DestinationOffset & 3) != 0)) + { + return LabelStagedRefusal.Unaligned; + } + + var at = byGuest + ? (long)(copy.GuestAddress - low) + : (long)copy.DestinationOffset - (long)source.Offset; + if (byGuest && byBuffer && at != (long)copy.DestinationOffset - (long)source.Offset) + { + return LabelStagedRefusal.Alias; + } + + if (!build) + { + continue; + } + + if (!_labelStagedAddresses.TryGetValue(copy.StagingBuffer, out var from)) + { + from = MetalNative.SendGpuAddress(copy.StagingBuffer, SelLabelScatterGpuAddress); + if (from == 0) + { + throw Fatal("A held label copy's staging has no GPU address for a staged read."); + } + + _labelStagedAddresses.Add(copy.StagingBuffer, from); + } + + for (var offset = 0L; offset < (long)bytes; offset += sizeof(uint)) + { + var position = at + offset; + if (position < 0 || position >= (long)span) + { + continue; + } + + var word = new LabelScatterWord { Source = from + copy.StagingOffset + (ulong)offset, Destination = staging + (ulong)position }; + if (_labelStagedWords.TryGetValue((ulong)position, out var existing)) + { + _labelStagedList[existing] = word; + continue; + } + + var count = _labelStagedWords.Count; + if (count == _labelStagedList.Length) + { + Array.Resize(ref _labelStagedList, count * 2); + } + + _labelStagedWords.Add((ulong)position, count); + _labelStagedList[count] = word; + } + } + + return LabelStagedRefusal.Count; + } + + /// + /// Right before a dispatch, in its compute encoder: fills the views its bindings got (or finds them still fresh). + /// Returns the encoder the dispatch encodes into, which =verify replaces after landing the copies. + /// + internal nint EncodeStagedLabelReads(nint encoder) + { + if (_labelStagedPending.Count == 0 && _labelStagedChecks.Count == 0) + { + return encoder; + } + + ThrowIfLabelStagedVerifyFailed(); + foreach (var entry in _labelStagedPending) + { + if (entry.Serial != _submissionSerial) + { + // The ring range belongs to the command buffer the binding was made in. + throw Fatal( + $"A staged label read is dispatched in another command buffer than it was bound in: address=0x{entry.Address:X16} " + + $"size=0x{entry.Size:X} bound={entry.Serial} now={_submissionSerial}."); + } + + if (entry.Fresh && entry.Listed) + { + _labelStagedReuse++; + continue; + } + + FillLabelStagedRead(encoder, entry); + entry.Fresh = entry.Listed; + } + + if (LabelStagedReadsVerify) + { + encoder = VerifyLabelStagedReads(encoder); + } + + foreach (var entry in _labelStagedPending) + { + entry.Pending = false; + } + + _labelStagedPending.Clear(); + return encoder; + } + + private unsafe void FillLabelStagedRead(nint encoder, LabelStagedRead entry) + { + var refusal = HeldCopiesOver(entry.Address - entry.Lead, in entry.Window, build: true, entry.Staging.GpuAddress); + if (refusal != LabelStagedRefusal.Count) + { + // Checked when the binding was made; nothing records a copy between a binding and its dispatch. + throw Fatal( + $"A held copy over a staged label read changed before its dispatch: address=0x{entry.Address:X16} " + + $"size=0x{entry.Size:X} reason={LabelStagedRefusalNames[(int)refusal]}."); + } + + NoteRecordedWork(); + MetalV2Native.SendMemoryBarrierScope(encoder, SelComputeMemoryBarrier, Mtl.BarrierScopeBuffers | Mtl.BarrierScopeTextures); + EncodeLabelStagedCopy(encoder, entry.Window.Buffer, entry.Window.Offset, entry.Staging.Buffer, entry.Staging.Offset, entry.Span); + var count = _labelStagedWords.Count; + if (count != 0) + { + var list = _guestMemory.Allocate((ulong)count * 16, 16, out var payload); + if (!list.IsValid) + { + throw Fatal($"A staged label read has no ring room for its copies: address=0x{entry.Address:X16} words={count}."); + } + + System.Runtime.InteropServices.MemoryMarshal.AsBytes(_labelStagedList.AsSpan(0, count)).CopyTo(payload); + var resources = _labelStagedAddresses.Count + 1; + if (_labelStagedResources.Length < resources) + { + _labelStagedResources = new nint[resources * 2]; + } + + var used = 0; + foreach (var buffer in _labelStagedAddresses.Keys) + { + _labelStagedResources[used++] = buffer; + } + + if (!_labelStagedAddresses.ContainsKey(entry.Staging.Buffer)) + { + _labelStagedResources[used++] = entry.Staging.Buffer; + } + + MetalV2Native.SendMemoryBarrierScope(encoder, SelComputeMemoryBarrier, Mtl.BarrierScopeBuffers | Mtl.BarrierScopeTextures); + MetalNative.SendVoid(encoder, SelOcclusionPipeline, LabelScatterPipeline()); + MetalNative.SendSetBuffer(encoder, SelOcclusionBuffer, list.Buffer, (nuint)list.Offset, 0); + var words = (uint)count; + MetalNative.SendSetBytes(encoder, SelOcclusionBytes, (nint)(&words), sizeof(uint), 1); + fixed (nint* pointers = _labelStagedResources) + { + MetalNative.SendUseResources(encoder, SelUseResourcesUsage, pointers, (nuint)used, + Mtl.ResourceUsageRead | Mtl.ResourceUsageWrite); + } + + MetalNative.SendDispatch(encoder, SelOcclusionDispatch, + new MtlSize { Width = (nuint)((count + LabelScatterThreads - 1) / LabelScatterThreads), Height = 1, Depth = 1 }, + new MtlSize { Width = LabelScatterThreads, Height = 1, Depth = 1 }); + } + + MetalV2Native.SendMemoryBarrierScope(encoder, SelComputeMemoryBarrier, Mtl.BarrierScopeBuffers | Mtl.BarrierScopeTextures); + // The guest dispatch binds its own pipeline again; its buffers are bound per dispatch. + _boundComputePipeline = 0; + _labelStagedFills++; + _labelStagedBytes += (long)entry.Span; + if (PassProfileEnabled) + { + PassProfileNoteWork($"label-staged-read words={count}", "transfer"); + } + } + + // Words from source to destination by the word-copy kernel, between barriers the caller places. + private unsafe void EncodeLabelStagedCopy(nint encoder, nint source, ulong sourceOffset, nint destination, ulong destinationOffset, ulong size) + { + var count = (uint)(size / sizeof(uint)); + MetalNative.SendVoid(encoder, SelOcclusionPipeline, CopyWordsPipeline()); + MetalNative.SendSetBuffer(encoder, SelOcclusionBuffer, source, (nuint)sourceOffset, 0); + MetalNative.SendSetBuffer(encoder, SelOcclusionBuffer, destination, (nuint)destinationOffset, 1); + MetalNative.SendSetBytes(encoder, SelOcclusionBytes, (nint)(&count), sizeof(uint), 2); + MetalNative.SendDispatch(encoder, SelOcclusionDispatch, + new MtlSize { Width = (nuint)((count + FillThreads - 1) / FillThreads), Height = 1, Depth = 1 }, + new MtlSize { Width = FillThreads, Height = 1, Depth = 1 }); + } + + // =verify: each view filled for this dispatch, copied out; then the landing the view stood in for; then the window + // bytes after it, copied out too. Each view found fresh with nothing held over it any more (_labelStagedChecks) is + // copied out next to its window bytes at this dispatch, with no landing: the reuse rule says they are equal. At + // completion each pair must be equal. + private unsafe nint VerifyLabelStagedReads(nint encoder) + { + // A view something wrote over since its binding is filled again before its next reuse; only a fresh one is checked. + _labelStagedChecks.RemoveAll(entry => !entry.Fresh || !entry.Listed || entry.Serial != _submissionSerial); + var filled = _labelStagedPending.Count; + var checks = new (LabelStagedRead Entry, nint Buffer)[filled + _labelStagedChecks.Count]; + MetalV2Native.SendMemoryBarrierScope(encoder, SelComputeMemoryBarrier, Mtl.BarrierScopeBuffers | Mtl.BarrierScopeTextures); + for (var index = 0; index < checks.Length; index++) + { + var entry = index < filled ? _labelStagedPending[index] : _labelStagedChecks[index - filled]; + var buffer = MetalNative.SendNewBuffer(_device, SelLabelStagedNewBuffer, (nuint)(entry.Span * 2), 0); + if (buffer == 0) + { + throw Fatal("A staged label read verify buffer could not be created."); + } + + checks[index] = (entry, buffer); + EncodeLabelStagedCopy(encoder, entry.Staging.Buffer, entry.Staging.Offset, buffer, 0, entry.Span); + } + + MetalV2Native.SendMemoryBarrierScope(encoder, SelComputeMemoryBarrier, Mtl.BarrierScopeBuffers | Mtl.BarrierScopeTextures); + _boundComputePipeline = 0; + for (var index = 0; index < filled; index++) + { + OrderAfterDeferredCopies(checks[index].Entry.Address, checks[index].Entry.Size, LabelLandCause.BindRead); + } + + encoder = EnsureComputeEncoder(); + MetalV2Native.SendMemoryBarrierScope(encoder, SelComputeMemoryBarrier, Mtl.BarrierScopeBuffers | Mtl.BarrierScopeTextures); + foreach (var (entry, buffer) in checks) + { + EncodeLabelStagedCopy(encoder, entry.Window.Buffer, entry.Window.Offset, buffer, entry.Span, entry.Span); + } + + MetalV2Native.SendMemoryBarrierScope(encoder, SelComputeMemoryBarrier, Mtl.BarrierScopeBuffers | Mtl.BarrierScopeTextures); + _boundComputePipeline = 0; + NoteRecordedWork(); + _labelStagedChecks.Clear(); + _completions.Enqueue(SubmissionSerial, () => + { + for (var index = 0; index < checks.Length; index++) + { + var (entry, buffer) = checks[index]; + var contents = new ReadOnlySpan((void*)MetalNative.Send(buffer, SelLabelFoldContents), checked((int)(entry.Span * 2))); + var staged = contents[..(int)entry.Span]; + var landed = contents[(int)entry.Span..]; + Interlocked.Increment(ref _labelStagedVerifyChecks); + if (!staged.SequenceEqual(landed)) + { + var at = staged.CommonPrefixLength(landed) & ~3; + Interlocked.Increment(ref _labelStagedVerifyFailed); + var failure = + $"A staged label read differs from the bytes {(index < filled ? "a landing left" : "its reuse reads")}: " + + $"address=0x{entry.Address:X16} size=0x{entry.Size:X} word=0x{entry.Address - entry.Lead + (ulong)at:X16} " + + $"staged=0x{BitConverter.ToUInt32(staged[at..]):X8} window=0x{BitConverter.ToUInt32(landed[at..]):X8}."; + Interlocked.CompareExchange(ref _labelStagedVerifyFailure, failure, null); + Console.Error.WriteLine($"[METAL-V2][ERROR] {failure}"); + } + + MetalNative.SendVoid(buffer, SelRelease); + } + }); + + return encoder; + } + + private void ThrowIfLabelStagedVerifyFailed() + { + if (Volatile.Read(ref _labelStagedVerifyFailure) is { } failure) + { + throw Fatal(failure); + } + } + + /// Tests: whether a staged label read failed verification (clears it). + internal string? TakeLabelStagedVerifyFailure() => Interlocked.Exchange(ref _labelStagedVerifyFailure, null); + + // A GPU write into guest memory was recorded: views over it are filled again at their next dispatch. + private void NoteLabelStagedReadsWrite(ulong address, ulong size) + { + if (_labelStagedTable.Count == 0 || address >= _labelStagedHigh || address + size <= _labelStagedLow) + { + return; + } + + foreach (var entry in _labelStagedTable) + { + if (address < entry.Address - entry.Lead + entry.Span && entry.Address - entry.Lead < address + size) + { + entry.Fresh = false; + } + } + } + + // A held copy into these window bytes: a view over them by another guest address is filled again too. + private void NoteLabelStagedReadsCopy(in DeferredLabelCopy copy) + { + if (_labelStagedTable.Count == 0) + { + return; + } + + foreach (var entry in _labelStagedTable) + { + if (entry.Window.Buffer == copy.DestinationBuffer && + copy.DestinationOffset < entry.Window.Offset + entry.Span && entry.Window.Offset < copy.DestinationOffset + (ulong)copy.Bytes) + { + entry.Fresh = false; + } + } + } + + // Held copies landed, a store with no known range, or a new guest submission: no view found so far is reused. + // A view the dispatch being bound holds is still filled before it. + private void ForgetLabelStagedReads() + { + if (_labelStagedTable.Count == 0) + { + return; + } + + foreach (var entry in _labelStagedTable) + { + entry.Listed = false; + entry.Fresh = false; + } + + _labelStagedTable.Clear(); + _labelStagedLow = ulong.MaxValue; + _labelStagedHigh = 0; + } + + /// A guest submission (slice) begins: its CPU stores before the submit are not in the views made so far. + internal void NoteLabelStagedReadsSubmission() + { + _labelStagedEpoch++; + ForgetLabelStagedReads(); + } + + // BindResources begins a stage: views bound for a dispatch that was never encoded are dropped (their bindings with it). + private void BeginLabelStagedStage(MetalStageBindings? computeStage) + { + foreach (var entry in _labelStagedPending) + { + entry.Pending = false; + entry.Fresh = false; + } + + _labelStagedPending.Clear(); + _labelStagedChecks.Clear(); + _labelStagedStage = computeStage; + } +} diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Rendering.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Rendering.cs index ea9a17583..55e017982 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Rendering.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Rendering.cs @@ -2140,7 +2140,7 @@ public void Dispatch(uint groupsX, uint groupsY, uint groupsZ) OrderAfterDeferredCopies(0, ulong.MaxValue, LabelLandCause.Persistent); } - var encoder = EnsureComputeEncoder(); + var encoder = EncodeStagedLabelReads(EnsureComputeEncoder()); var entry = _pendingComputePipeline ?? throw Fatal("A dispatch has no bound Metal compute pipeline state."); if (entry.PersistentThreads && PersistentThreadGroups != 0 && groupsY <= 1 && groupsZ <= 1 && groupsX > PersistentThreadGroups) @@ -2244,7 +2244,7 @@ public bool TryDispatchIndirect(ulong argumentsAddress, ReadOnlySpan physic OrderAfterDeferredCopies(argumentsAddress, 3 * sizeof(uint), LabelLandCause.Indirect); TraceIndirectDispatch(argumentsAddress); var started = DrawTimingStart(); - var encoder = EnsureComputeEncoder(); + var encoder = EncodeStagedLabelReads(EnsureComputeEncoder()); var entry = _pendingComputePipeline ?? throw Fatal("An indirect dispatch has no bound Metal compute pipeline state."); EnsureComputePipelineState(encoder, entry); diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.StagedStorage.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.StagedStorage.cs index f854ac605..7a4280fe8 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.StagedStorage.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.StagedStorage.cs @@ -48,7 +48,18 @@ private MetalGuestRange ResolveStorageBuffer( inPlaceAlias = 0; inPlaceWindow = null; using var phaseScope = SharpEmu.Libs.VideoOut.RenderPhaseProfile.MeasureDetail(SharpEmu.Libs.VideoOut.RenderPhaseProfile.Phase.StorageDeferredLabels); - OrderAfterDeferredCopies(address, size, written ? LabelLandCause.BindWritten : LabelLandCause.BindRead); + // A read of held label copies gets a view the dispatch fills with them, the copies left held + // (MetalRenderHost.LabelStagedReads.cs); not in place, so no read-binding memo keeps it. + var untouched = false; + if (!written && TryStageLabelRead(address, size, computeStage, out var labelView, out untouched)) + { + return labelView; + } + + if (!untouched) + { + OrderAfterDeferredCopies(address, size, written ? LabelLandCause.BindWritten : LabelLandCause.BindRead); + } phaseScope.SwitchPhase(SharpEmu.Libs.VideoOut.RenderPhaseProfile.Phase.StorageSharedLookup); var staged = StagedStorage; if (staged.TryShare(address, size, written, out var shared)) diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.ThreadDispatch.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.ThreadDispatch.cs index f80527669..551092bd9 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.ThreadDispatch.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.ThreadDispatch.cs @@ -107,7 +107,7 @@ public unsafe bool TryDispatchThreadsIndirect( // The GPU reads the thread counts where the dispatch sits in the stream. OrderAfterDeferredCopies(argumentsAddress, 3 * sizeof(uint), LabelLandCause.Indirect); var started = DrawTimingStart(); - var encoder = EnsureComputeEncoder(); + var encoder = EncodeStagedLabelReads(EnsureComputeEncoder()); var entry = _pendingComputePipeline ?? throw Fatal("A thread-unit indirect dispatch has no bound Metal compute pipeline state."); var limits = _threadLimitsTarget; diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.cs index 11a7ea866..fc28626ab 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.cs @@ -1378,6 +1378,7 @@ public void NoteGuestMemoryWriteBeyondOverlays(ulong address, ulong size, MetalG { _stagedStorageCopies?.Forget(address, size); _stagedRanges?.OnGpuWrite(address, size, origin); + NoteLabelStagedReadsWrite(address, size); } if (_guard is not null && size != 0) @@ -1446,6 +1447,7 @@ public void NoteUnboundedGuestMemoryWrite() _gpuWrites.NoteUnbounded(SubmissionSerial); _cpOverlay.Clear(); _labelOverlay.Clear(); + ForgetLabelStagedReads(); } void IMetalImageCacheOwner.WaitForGpu() => FlushAndWaitForGpu(MetalWaitReason.ImageCache); From 91b6b364f5afe1c8bd6d013456518a4ef5260799 Mon Sep 17 00:00:00 2001 From: kuba Date: Sun, 15 Nov 2026 15:06:01 +0000 Subject: [PATCH 074/178] [Tests] Staged label reads: no barrier, earlier stores, later labels, written bindings, refusals, reuse, verify --- ...talEndOfPipeOrderTests.LabelStagedReads.cs | 423 ++++++++++++++++++ 1 file changed, 423 insertions(+) create mode 100644 tests/SharpEmu.Gpu.Metal.Tests/MetalEndOfPipeOrderTests.LabelStagedReads.cs diff --git a/tests/SharpEmu.Gpu.Metal.Tests/MetalEndOfPipeOrderTests.LabelStagedReads.cs b/tests/SharpEmu.Gpu.Metal.Tests/MetalEndOfPipeOrderTests.LabelStagedReads.cs new file mode 100644 index 000000000..2fc2e32b9 --- /dev/null +++ b/tests/SharpEmu.Gpu.Metal.Tests/MetalEndOfPipeOrderTests.LabelStagedReads.cs @@ -0,0 +1,423 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using SharpEmu.Gpu.Metal.V2; +using SharpEmu.Libs.Gpu.GpuCommands; +using Xunit; + +namespace SharpEmu.Gpu.Metal.Tests; + +// A read-only compute binding over held label copies reads a view the dispatch fills with them, and the copies stay held +// to the commit (MetalRenderHost.LabelStagedReads.cs). +public sealed unsafe partial class MetalEndOfPipeOrderTests +{ + private const ulong StagedRange = GuestBase + 0x10000; + private const ulong StagedLabel = StagedRange + 0x10; + private const uint StagedWords = 16; + + // A CPU-visible label held over the bytes a dispatch reads: no barrier, the encoder stays open, the dispatch reads the + // label's value over the rest of guest memory, the label is still held and lands at the commit behind the shared event. + [Fact] + public void AHeldCpuVisibleLabelIsReadThroughAStagedViewWithoutLandingIt() + { + if (!RequireDevice()) return; + using var rig = new Rig(Device.Value); + using var probe = new StagedProbe(Device.Value); + var host = rig.Host; + Assert.True(host.LabelStagedReads); + FillStagedPattern(rig); + TakeStagedCounters(host); + + _ = host.EnsureComputeEncoder(); + host.RecordEndOfPipe(new EndOfPipeWrite(EndOfPipeWriteKind.WriteBack64, 1, StagedLabel, 0x1122334455667788)); + var view = host.ResolveStorageBuffer(StagedRange, StagedWords * 4, written: false, computeStage: true); + Assert.True(host.ComputeEncoderOpen); + Assert.Equal(1, host.DeferredLabelCopyCount); + Assert.Equal(1, host.PendingLabelStagedReads); + Assert.False(host.GuestMemory.IsInPlace(view)); + + probe.Read(host, view, slot: 0); + Assert.True(host.ComputeEncoderOpen); + Assert.Equal(1, host.DeferredLabelCopyCount); + Assert.Equal(0, host.PendingLabelStagedReads); + Assert.Equal(0L, host.TakeLabelBarriers()); + Assert.All(host.TakeLabelLandCounts(), count => Assert.Equal(0L, count)); + var counts = host.TakeLabelStagedCounts(); + Assert.Equal(1L, counts[0]); + Assert.Equal(1L, counts[1]); + Assert.Equal(0L, counts[2]); + + host.FlushCommandBuffer(); + WaitForGpu(host, host.LastWorkSerial); + WaitForCompletions(host); + for (var word = 0; word < StagedWords; word++) + { + var expected = word switch { 4 => 0x55667788u, 5 => 0x11223344u, _ => 0xA0000000u + (uint)word }; + Assert.Equal(expected, probe.Word(0, word)); + } + + Assert.Equal(0x1122334455667788UL, rig.Backing.Read64(StagedLabel)); + var lands = host.TakeLabelLandCounts(); + Assert.Equal(1L, lands[(int)MetalRenderHost.LabelLandCause.Commit - 1]); + Assert.Equal(0L, lands[(int)MetalRenderHost.LabelLandCause.BindRead - 1]); + Assert.Equal(1L, host.TakeLabelBarrierKinds()[0]); + } + + // A dispatch earlier in the same encoder that stores into the range (a fill beside the label) is seen through the view. + [Fact] + public void AStoreEarlierInTheEncoderIsSeenThroughTheStagedView() + { + if (!RequireDevice()) return; + using var rig = new Rig(Device.Value); + using var probe = new StagedProbe(Device.Value); + var host = rig.Host; + FillStagedPattern(rig); + TakeStagedCounters(host); + + _ = host.EnsureComputeEncoder(); + host.RecordEndOfPipe(new EndOfPipeWrite(EndOfPipeWriteKind.WriteBack32, 1, StagedLabel, 0x5A5A)); + // A dispatch ahead of the reader in the same encoder stores into the range beside the label. + Assert.True(host.GuestMemory.TryResolveInPlace(StagedRange, StagedWords * 4, out var window)); + for (var word = 0u; word < 4; word++) + { + probe.StoreBehindTheHost(host, window with { Offset = window.Offset + word * 4 }, 0x77); + } + + Assert.True(host.ComputeEncoderOpen); + var view = host.ResolveStorageBuffer(StagedRange, StagedWords * 4, written: false, computeStage: true); + probe.Read(host, view, slot: 0); + Assert.True(host.ComputeEncoderOpen); + Assert.Equal(1, host.DeferredLabelCopyCount); + Assert.Equal(0L, host.TakeLabelBarriers()); + + host.FlushCommandBuffer(); + WaitForGpu(host, host.LastWorkSerial); + WaitForCompletions(host); + for (var word = 0; word < StagedWords; word++) + { + var expected = word switch { < 4 => 0x77u, 4 => 0x5A5Au, _ => 0xA0000000u + (uint)word }; + Assert.Equal(expected, probe.Word(0, word)); + } + } + + // A second label to the same bytes recorded after the view was filled makes the next reader fill it again: the first + // reader saw the first value, the next one the second; the second lands last. + [Fact] + public void ALabelRecordedAfterTheViewWasFilledIsSeenByTheNextReader() + { + if (!RequireDevice()) return; + using var rig = new Rig(Device.Value); + using var probe = new StagedProbe(Device.Value); + var host = rig.Host; + FillStagedPattern(rig); + TakeStagedCounters(host); + + _ = host.EnsureComputeEncoder(); + host.RecordEndOfPipe(new EndOfPipeWrite(EndOfPipeWriteKind.WriteBack32, 1, StagedLabel, 1)); + var first = host.ResolveStorageBuffer(StagedRange, StagedWords * 4, written: false, computeStage: true); + probe.Read(host, first, slot: 0); + host.RecordEndOfPipe(new EndOfPipeWrite(EndOfPipeWriteKind.WriteBack32, 1, StagedLabel, 2)); + var second = host.ResolveStorageBuffer(StagedRange, StagedWords * 4, written: false, computeStage: true); + Assert.Equal(first, second); + probe.Read(host, second, slot: 1); + Assert.True(host.ComputeEncoderOpen); + Assert.Equal(2, host.DeferredLabelCopyCount); + Assert.Equal(0L, host.TakeLabelBarriers()); + var counts = host.TakeLabelStagedCounts(); + Assert.Equal(2L, counts[1]); + Assert.Equal(0L, counts[2]); + + host.FlushCommandBuffer(); + WaitForGpu(host, host.LastWorkSerial); + WaitForCompletions(host); + Assert.Equal(1u, probe.Word(0, 4)); + Assert.Equal(2u, probe.Word(1, 4)); + Assert.Equal(0xA0000005u, probe.Word(1, 5)); + Assert.Equal(2u, rig.Backing.Read32(StagedLabel)); + } + + // A written binding over the held label still lands it, ending the encoder for the shared event. + [Fact] + public void AWrittenBindingOverAHeldLabelStillLandsIt() + { + if (!RequireDevice()) return; + using var rig = new Rig(Device.Value); + var host = rig.Host; + TakeStagedCounters(host); + + _ = host.EnsureComputeEncoder(); + host.RecordEndOfPipe(new EndOfPipeWrite(EndOfPipeWriteKind.WriteBack64, 1, StagedLabel, 9)); + _ = host.ResolveStorageBuffer(StagedRange, StagedWords * 4, written: true, computeStage: true); + Assert.False(host.ComputeEncoderOpen); + Assert.Equal(0, host.DeferredLabelCopyCount); + Assert.Equal(0, host.PendingLabelStagedReads); + Assert.Equal(1L, host.TakeLabelBarriers()); + Assert.Equal(1L, host.TakeLabelLandCounts()[(int)MetalRenderHost.LabelLandCause.BindWritten - 1]); + Assert.Equal(0L, host.TakeLabelStagedCounts()[0]); + + host.FlushCommandBuffer(); + WaitForGpu(host, host.LastWorkSerial); + WaitForCompletions(host); + Assert.Equal(9UL, rig.Backing.Read64(StagedLabel)); + } + + // Each reason a binding over held copies is not staged is counted, and the copies land as before. Not here: gpu_source + // (an occlusion dump is held only inside an open occlusion pass) and alias (two guest addresses of one window). + [Theory] + [InlineData((int)MetalRenderHost.LabelStagedRefusal.Graphics)] + [InlineData((int)MetalRenderHost.LabelStagedRefusal.NoFence)] + [InlineData((int)MetalRenderHost.LabelStagedRefusal.Large)] + [InlineData((int)MetalRenderHost.LabelStagedRefusal.Unaligned)] + [InlineData((int)MetalRenderHost.LabelStagedRefusal.StagedStorage)] + [InlineData((int)MetalRenderHost.LabelStagedRefusal.NotInPlace)] + [InlineData((int)MetalRenderHost.LabelStagedRefusal.DispatchWrites)] + public void EachRefusalIsCountedAndTheCopiesLand(int refusal) + { + var reason = (MetalRenderHost.LabelStagedRefusal)refusal; + if (!RequireDevice()) return; + using var rig = new Rig(Device.Value); + var host = rig.Host; + TakeStagedCounters(host); + var address = StagedRange; + var size = (ulong)StagedWords * 4; + var computeStage = true; + _ = host.EnsureComputeEncoder(); + switch (reason) + { + case MetalRenderHost.LabelStagedRefusal.Graphics: + computeStage = false; + break; + case MetalRenderHost.LabelStagedRefusal.NoFence: + host.EncoderOrdering = MetalRenderHost.EncoderOrderingMode.None; + break; + case MetalRenderHost.LabelStagedRefusal.Large: + size = MetalRenderHost.LabelStagedReadMaxBytes + 0x1000; + break; + case MetalRenderHost.LabelStagedRefusal.StagedStorage: + _ = host.StageRecordedStoresForTest(address, size); + break; + case MetalRenderHost.LabelStagedRefusal.NotInPlace: + // The range runs into the page no window covers. + address = GuestBase + HoleOffset - 0x40; + size = 0x80; + break; + case MetalRenderHost.LabelStagedRefusal.DispatchWrites: + host.LabelStagedDispatchWriteForTest = (address + 0x20, 4); + break; + } + + if (reason == MetalRenderHost.LabelStagedRefusal.Unaligned) + { + host.RecordCommandProcessorWrite(address + 0x10, [1, 2, 3, 4, 5, 6], "WRITE_DATA", causal: true); + } + else + { + host.RecordEndOfPipe(new EndOfPipeWrite(EndOfPipeWriteKind.WriteBack32, 1, address + 0x10, 0x42)); + } + + Assert.NotEqual(0, host.DeferredLabelCopyCount); + _ = host.ResolveStorageBuffer(address, size, written: false, computeStage); + var refused = host.TakeLabelStagedRefusals(); + for (var index = 0; index < refused.Length; index++) + { + Assert.Equal(index == (int)reason ? 1L : 0L, refused[index]); + } + + Assert.Equal(0L, host.TakeLabelStagedCounts()[0]); + Assert.Equal(0, host.PendingLabelStagedReads); + Assert.Equal(0, host.DeferredLabelCopyCount); + Assert.Equal(1L, host.TakeLabelLandCounts()[(int)MetalRenderHost.LabelLandCause.BindRead - 1]); + host.FlushCommandBuffer(); + WaitForGpu(host, host.LastWorkSerial); + WaitForCompletions(host); + } + + // A view is reused (no fill) by a later dispatch only while nothing could have changed its bytes: a GPU write over it, + // a new guest submission or another command buffer makes the next reader fill it again. + [Fact] + public void AViewIsReusedOnlyWhileItsBytesCannotHaveChanged() + { + if (!RequireDevice()) return; + using var rig = new Rig(Device.Value); + using var probe = new StagedProbe(Device.Value); + var host = rig.Host; + FillStagedPattern(rig); + TakeStagedCounters(host); + const ulong size = StagedWords * 4; + + _ = host.EnsureComputeEncoder(); + host.RecordEndOfPipe(new EndOfPipeWrite(EndOfPipeWriteKind.WriteBack32, 1, StagedLabel, 3)); + probe.Read(host, host.ResolveStorageBuffer(StagedRange, size, written: false, computeStage: true), slot: 0); + // Nothing since: reused. + probe.Read(host, host.ResolveStorageBuffer(StagedRange, size, written: false, computeStage: true), slot: 1); + Assert.Equal(new long[] { 2, 1, 1 }, host.TakeLabelStagedCounts()[..3]); + + // A label elsewhere, outside the view: still reused. + host.RecordEndOfPipe(new EndOfPipeWrite(EndOfPipeWriteKind.WriteBack32, 1, StagedRange + 0x800, 4)); + probe.Read(host, host.ResolveStorageBuffer(StagedRange, size, written: false, computeStage: true), slot: 2); + Assert.Equal(new long[] { 1, 0, 1 }, host.TakeLabelStagedCounts()[..3]); + + // A GPU store over the view: filled again, and it sees the store. + host.FillBufferInOrder(StagedRange, 4, 0x99); + probe.Read(host, host.ResolveStorageBuffer(StagedRange, size, written: false, computeStage: true), slot: 3); + Assert.Equal(new long[] { 1, 1, 0 }, host.TakeLabelStagedCounts()[..3]); + + // A new guest submission: filled again (in a new view). + host.NoteLabelStagedReadsSubmission(); + probe.Read(host, host.ResolveStorageBuffer(StagedRange, size, written: false, computeStage: true), slot: 4); + Assert.Equal(new long[] { 1, 1, 0 }, host.TakeLabelStagedCounts()[..3]); + Assert.True(host.ComputeEncoderOpen); + Assert.Equal(0L, host.TakeLabelBarriers()); + + // Another command buffer: the commit lands the copies; a label held in the next one is staged anew. + host.FlushCommandBuffer(); + _ = host.EnsureComputeEncoder(); + host.RecordEndOfPipe(new EndOfPipeWrite(EndOfPipeWriteKind.WriteBack32, 1, StagedLabel, 5)); + probe.Read(host, host.ResolveStorageBuffer(StagedRange, size, written: false, computeStage: true), slot: 5); + Assert.Equal(new long[] { 1, 1, 0 }, host.TakeLabelStagedCounts()[..3]); + + host.FlushCommandBuffer(); + WaitForGpu(host, host.LastWorkSerial); + WaitForCompletions(host); + Assert.Equal(3u, probe.Word(0, 4)); + Assert.Equal(3u, probe.Word(1, 4)); + Assert.Equal(3u, probe.Word(2, 4)); + Assert.Equal(0xA0000000u, probe.Word(2, 0)); + Assert.Equal(0x99u, probe.Word(3, 0)); + Assert.Equal(3u, probe.Word(4, 4)); + Assert.Equal(5u, probe.Word(5, 4)); + Assert.Equal(0x99u, probe.Word(5, 0)); + Assert.Equal(5u, rig.Backing.Read32(StagedLabel)); + } + + // =verify: the view is compared with the bytes a landing leaves (and the landing is made), and a view found fresh + // later is compared with the window it stands for. A store the host was never told of makes that check fail. + [Fact] + public void VerifyComparesTheViewWithTheLandingAndCatchesAStaleReuse() + { + if (!RequireDevice()) return; + using var rig = new Rig(Device.Value); + using var probe = new StagedProbe(Device.Value); + var host = rig.Host; + host.LabelStagedReadsVerify = true; + FillStagedPattern(rig); + TakeStagedCounters(host); + const ulong size = StagedWords * 4; + + _ = host.EnsureComputeEncoder(); + host.RecordEndOfPipe(new EndOfPipeWrite(EndOfPipeWriteKind.WriteBack64, 1, StagedLabel, 0xABCDEF)); + probe.Read(host, host.ResolveStorageBuffer(StagedRange, size, written: false, computeStage: true), slot: 0); + // The check landed the label. + Assert.Equal(0, host.DeferredLabelCopyCount); + + // Fresh with nothing held: the binding reads the window, and the dispatch checks the view against it. + probe.Read(host, host.ResolveStorageBuffer(StagedRange, size, written: false, computeStage: true), slot: 1); + host.FlushCommandBuffer(); + WaitForGpu(host, host.LastWorkSerial); + WaitForCompletions(host); + var counts = host.TakeLabelStagedCounts(); + Assert.Equal(2L, counts[4]); + Assert.Equal(0L, counts[5]); + Assert.Null(host.TakeLabelStagedVerifyFailure()); + Assert.Equal(0xABCDEFu, probe.Word(0, 4)); + Assert.Equal(0xABCDEFu, probe.Word(1, 4)); + + // The same again, with a store into the window the host does not know about between the two dispatches. + _ = host.EnsureComputeEncoder(); + host.RecordEndOfPipe(new EndOfPipeWrite(EndOfPipeWriteKind.WriteBack64, 1, StagedLabel, 0x123)); + probe.Read(host, host.ResolveStorageBuffer(StagedRange, size, written: false, computeStage: true), slot: 2); + Assert.True(host.GuestMemory.TryResolveInPlace(StagedRange, size, out var window)); + probe.StoreBehindTheHost(host, window, 0xDEAD); + probe.Read(host, host.ResolveStorageBuffer(StagedRange, size, written: false, computeStage: true), slot: 3); + host.FlushCommandBuffer(); + WaitForGpu(host, host.LastWorkSerial); + WaitForCompletions(host); + counts = host.TakeLabelStagedCounts(); + Assert.Equal(2L, counts[4]); + Assert.Equal(1L, counts[5]); + Assert.Contains("its reuse reads", host.TakeLabelStagedVerifyFailure()); + } + + private static void FillStagedPattern(Rig rig) + { + Span words = stackalloc byte[(int)StagedWords * 4]; + for (var word = 0; word < StagedWords; word++) + { + BitConverter.TryWriteBytes(words[(word * 4)..], 0xA0000000u + (uint)word); + } + + Assert.True(rig.Backing.TryWrite(StagedRange, words)); + } + + private static void TakeStagedCounters(MetalRenderHost host) + { + _ = host.TakeLabelBarriers(); + _ = host.TakeLabelBarrierKinds(); + _ = host.TakeLabelLandCounts(); + _ = host.TakeLabelStagedCounts(); + _ = host.TakeLabelStagedRefusals(); + } + + // A dispatch of its own in the host's compute encoder, encoded where a guest dispatch would be: after the host + // filled the views its bindings got (EncodeStagedLabelReads), it copies the view's words out. + private sealed class StagedProbe : IDisposable + { + private const int SlotWords = 256; + private static readonly nint SelPipeline = MetalNative.Selector("setComputePipelineState:"); + private static readonly nint SelSetBuffer = MetalNative.Selector("setBuffer:offset:atIndex:"); + private static readonly nint SelSetBytes = MetalNative.Selector("setBytes:length:atIndex:"); + private static readonly nint SelDispatch = MetalNative.Selector("dispatchThreadgroups:threadsPerThreadgroup:"); + private static readonly nint SelBarrier = MetalNative.Selector("memoryBarrierWithScope:"); + private readonly nint _read; + private readonly nint _store; + private readonly nint _output; + + public StagedProbe(nint device) + { + _read = SeparatorBenchPipeline(device, + "kernel void bench(device const uint* source [[buffer(0)]], device uint* destination [[buffer(1)]], " + + "constant uint& count [[buffer(2)]], uint index [[thread_position_in_grid]]) { if (index < count) destination[index] = source[index]; }"); + _store = SeparatorBenchPipeline(device, + "kernel void bench(device uint* words [[buffer(0)]], constant uint& value [[buffer(1)]], " + + "uint index [[thread_position_in_grid]]) { if (index == 0u) words[0] = value; }"); + _output = MetalNative.SendNewBuffer(device, MetalNative.Selector("newBufferWithLength:options:"), 16 * SlotWords * 4, 0); + } + + public void Read(MetalRenderHost host, MetalGuestRange view, int slot) + { + var encoder = host.EncodeStagedLabelReads(host.EnsureComputeEncoder()); + var count = StagedWords; + MetalV2Native.SendMemoryBarrierScope(encoder, SelBarrier, 1); + MetalNative.SendVoid(encoder, SelPipeline, _read); + MetalNative.SendSetBuffer(encoder, SelSetBuffer, view.Buffer, (nuint)view.Offset, 0); + MetalNative.SendSetBuffer(encoder, SelSetBuffer, _output, (nuint)(slot * SlotWords * 4), 1); + MetalNative.SendSetBytes(encoder, SelSetBytes, (nint)(&count), sizeof(uint), 2); + MetalNative.SendDispatch(encoder, SelDispatch, + new MtlSize { Width = 1, Height = 1, Depth = 1 }, new MtlSize { Width = 64, Height = 1, Depth = 1 }); + MetalV2Native.SendMemoryBarrierScope(encoder, SelBarrier, 1); + } + + public void StoreBehindTheHost(MetalRenderHost host, MetalGuestRange window, uint value) + { + var encoder = host.EnsureComputeEncoder(); + MetalV2Native.SendMemoryBarrierScope(encoder, SelBarrier, 1); + MetalNative.SendVoid(encoder, SelPipeline, _store); + MetalNative.SendSetBuffer(encoder, SelSetBuffer, window.Buffer, (nuint)window.Offset, 0); + MetalNative.SendSetBytes(encoder, SelSetBytes, (nint)(&value), sizeof(uint), 1); + MetalNative.SendDispatch(encoder, SelDispatch, + new MtlSize { Width = 1, Height = 1, Depth = 1 }, new MtlSize { Width = 1, Height = 1, Depth = 1 }); + MetalV2Native.SendMemoryBarrierScope(encoder, SelBarrier, 1); + } + + public uint Word(int slot, int index) => + ((uint*)MetalNative.Send(_output, MetalNative.Selector("contents")))[slot * SlotWords + index]; + + public void Dispose() + { + var release = MetalNative.Selector("release"); + MetalNative.SendVoid(_read, release); + MetalNative.SendVoid(_store, release); + MetalNative.SendVoid(_output, release); + } + } +} From 7ad48fe21706650e82f56ae29f8565437c8a108f Mon Sep 17 00:00:00 2001 From: kuba Date: Sun, 15 Nov 2026 15:31:25 +0000 Subject: [PATCH 075/178] [Shader] Prove a fast snapshot current from its program's recorded reads A revalidation that evaluated its materialization program records every word it read (address and value, folded into runs of whole words inside 256-byte lines), the addresses it could not read, and the sources the branches left active. The next revalidation of that origin hands the runs to a host comparer (ResourceRuntimeInputs.CompareGuestWords) and, when every word compares equal, every unreadable word still reads nothing and the active sources match, answers current without evaluating the program or comparing its output. SHARPEMU_RESOURCE_READ_PROOF=0 turns it off; =verify also evaluates in full and stops on a proof that disagrees. Counted on the read_proof=(...) report. --- .../Resources/MaterializationProgram.cs | 244 +++++++++++++- .../Resources/ResourceMaterializer.cs | 315 +++++++++++++++++- .../Resources/ResourceRuntimeInputs.cs | 13 + .../Resources/ReadProofTests.cs | 306 +++++++++++++++++ 4 files changed, 862 insertions(+), 16 deletions(-) create mode 100644 tests/SharpEmu.ShaderCompiler.Tests/Resources/ReadProofTests.cs diff --git a/src/SharpEmu.ShaderCompiler/Resources/MaterializationProgram.cs b/src/SharpEmu.ShaderCompiler/Resources/MaterializationProgram.cs index 664183ed1..42afa9c60 100644 --- a/src/SharpEmu.ShaderCompiler/Resources/MaterializationProgram.cs +++ b/src/SharpEmu.ShaderCompiler/Resources/MaterializationProgram.cs @@ -107,7 +107,7 @@ private sealed class FixedReads [ThreadStatic] private static Scratch? _scratch; - private sealed class Scratch + internal sealed class Scratch { public ulong[] Values = new ulong[256]; public bool[] Valid = new bool[256]; @@ -119,6 +119,27 @@ private sealed class Scratch public readonly ReadOrder Order = new(); public int Count; + // While an evaluation records what it reads (ReadProof): each word read from memory, and each address whose + // read found none. + public bool Recording; + public ulong[] ReadAddresses = new ulong[64]; + public uint[] ReadWords = new uint[64]; + public int ReadCount; + public readonly List Unreadable = []; + + public void NoteRead(ulong address, uint word) + { + if (ReadCount == ReadAddresses.Length) + { + Array.Resize(ref ReadAddresses, ReadCount * 2); + Array.Resize(ref ReadWords, ReadCount * 2); + } + + ReadAddresses[ReadCount] = address; + ReadWords[ReadCount] = word; + ReadCount++; + } + public void Ensure(int registers) { if (Values.Length < registers) @@ -500,22 +521,208 @@ internal sealed class Output public ReadOnlySpan RangeValues => Ranges.AsSpan(0, RangeCount); } - internal bool TryRunInto(ShaderResourcePlan plan, ResourceRuntimeInputs inputs, int additionalTableWords, Output output) + internal bool TryRunInto(ShaderResourcePlan plan, ResourceRuntimeInputs inputs, int additionalTableWords, Output output) => + TryRunInto(plan, inputs, additionalTableWords, output, record: false, previous: null, out _); + + // With record, also what the evaluation read (null when one address read as two values): previous itself when it + // holds exactly that, or a proof sharing its ranges when only their bytes differ. + internal bool TryRunInto(ShaderResourcePlan plan, ResourceRuntimeInputs inputs, int additionalTableWords, Output output, bool record, + ReadProof? previous, out ReadProof? proof) { + proof = null; var activeSources = plan.ResourceBranches.Count != 0 ? RuntimeValueEvaluator.EvaluateActiveSources(plan, inputs) : []; var scratch = _scratch ?? new Scratch(); _scratch = null; try { + scratch.Recording = record; + scratch.ReadCount = 0; + scratch.Unreadable.Clear(); Evaluate(inputs, scratch); - return Emit(plan, additionalTableWords, scratch, activeSources, output); + scratch.Recording = false; + if (!Emit(plan, additionalTableWords, scratch, activeSources, output)) + { + return false; + } + + if (record) + { + proof = ReadProof.Build(this, scratch, activeSources, previous); + } + + return true; } finally { + scratch.Recording = false; _scratch = scratch; } } + /// + /// What one evaluation of a program read, as the proof that another evaluation with the same user data, shader base, + /// compute state and readers emits the same words. Every read's address is a function of the registers of the levels + /// before it, and those of the first read level of the user data, shader base and constants alone; so while those + /// are the same, every word read from memory still holds the value it was read as, and every read that found no + /// memory finds none again, every read is at the same address with the same outcome, level by level, and every + /// register comes out the same. The words emitted are a function of the registers and the active sources + /// (, which the caller evaluates again). A caller compares the words + /// (, , ) through the ownership tests a word read + /// makes, recorded as that read records them, and reads again. Immutable once built. + /// + internal sealed class ReadProof + { + // Words of one range lie in one 256-byte line, the unit the concurrent ownership tests answer for. + internal const int LineBytes = 256; + + public required MaterializationProgram Program; + // The words read from memory, in address order, as runs of consecutive words within a line, and their bytes, run + // after run. + public required ulong[] Addresses; + public required int[] Lengths; + public required byte[] Bytes; + // Addresses whose read found no memory. + public required ulong[] Unreadable; + // The sources the plan's branches left active (empty without branches). + public required bool[] ActiveSources; + + internal static ReadProof? Build(MaterializationProgram program, Scratch scratch, bool[] activeSources, ReadProof? previous = null) + { + var count = scratch.ReadCount; + var addresses = scratch.ReadAddresses; + var words = scratch.ReadWords; + Array.Sort(addresses, words, 0, count); + var unique = 0; + var ranges = 0; + for (var index = 0; index < count; index++) + { + if (unique != 0 && addresses[unique - 1] == addresses[index]) + { + // One address read as two values in the same evaluation (the guest wrote it meanwhile): no proof. + if (words[unique - 1] != words[index]) + { + return null; + } + + continue; + } + + if (unique == 0 || !Continues(addresses[unique - 1], addresses[index])) + { + ranges++; + } + + addresses[unique] = addresses[index]; + words[unique] = words[index]; + unique++; + } + + // A revalidation that read in full mostly reads what the proof before it did (its compare was refused) or the + // same words with other values (a words miss): kept, or its ranges shared, rather than allocated again. + var sameRanges = previous is not null && ReferenceEquals(previous.Program, program) && previous.Addresses.Length == ranges && + previous.Bytes.Length == unique * sizeof(uint) && SameRanges(previous, addresses, unique); + var sameBytes = sameRanges && SameWords(previous!.Bytes, words, unique); + var sameRest = previous is not null && previous.ActiveSources.AsSpan().SequenceEqual(activeSources) && + previous.Unreadable.AsSpan().SequenceEqual(System.Runtime.InteropServices.CollectionsMarshal.AsSpan(scratch.Unreadable)); + if (sameBytes && sameRest) + { + return previous; + } + + ulong[] starts; + int[] lengths; + if (sameRanges) + { + starts = previous!.Addresses; + lengths = previous.Lengths; + } + else + { + starts = new ulong[ranges]; + lengths = new int[ranges]; + var range = -1; + for (var index = 0; index < unique; index++) + { + if (index == 0 || !Continues(addresses[index - 1], addresses[index])) + { + starts[++range] = addresses[index]; + } + + lengths[range] += sizeof(uint); + } + } + + byte[] bytes; + if (sameBytes) + { + bytes = previous!.Bytes; + } + else + { + bytes = new byte[unique * sizeof(uint)]; + System.Runtime.InteropServices.MemoryMarshal.AsBytes(words.AsSpan(0, unique)).CopyTo(bytes); + if (!BitConverter.IsLittleEndian) + { + for (var index = 0; index < unique; index++) + { + System.Buffers.Binary.BinaryPrimitives.WriteUInt32LittleEndian(bytes.AsSpan(index * sizeof(uint)), words[index]); + } + } + } + + return new ReadProof + { + Program = program, Addresses = starts, Lengths = lengths, Bytes = bytes, + Unreadable = scratch.Unreadable.Count == 0 ? [] : sameRest ? previous!.Unreadable : [.. scratch.Unreadable], + ActiveSources = activeSources, + }; + } + + // Whether the unique sorted addresses form exactly the proof's ranges. + private static bool SameRanges(ReadProof proof, ulong[] addresses, int unique) + { + var index = 0; + for (var range = 0; range < proof.Addresses.Length; range++) + { + var start = proof.Addresses[range]; + var words = proof.Lengths[range] / sizeof(uint); + if (index + words > unique || addresses[index] != start || (index != 0 && Continues(addresses[index - 1], start))) + { + return false; + } + + for (var word = 1; word < words; word++) + { + if (addresses[index + word] != start + (ulong)(word * sizeof(uint))) + { + return false; + } + } + + index += words; + } + + return index == unique; + } + + private static bool SameWords(byte[] bytes, uint[] words, int unique) + { + for (var index = 0; index < unique; index++) + { + if (System.Buffers.Binary.BinaryPrimitives.ReadUInt32LittleEndian(bytes.AsSpan(index * sizeof(uint))) != words[index]) + { + return false; + } + } + + return true; + } + + // Whether a word at next extends the run whose last word is at previous: the next word, in the same line. + private static bool Continues(ulong previous, ulong next) => + next - previous == sizeof(uint) && (next & ~(ulong)(LineBytes - 1)) == (previous & ~(ulong)(LineBytes - 1)); + } + private void Evaluate(ResourceRuntimeInputs inputs, Scratch scratch) { scratch.Ensure(_registerCount); @@ -784,8 +991,13 @@ private static bool TryReadFixed(ReadStep[] reads, FixedReads plan, ResourceRunt for (var index = start; index < end; index++) { var target = reads[order[index]].Target; - values[target] = System.Buffers.Binary.BinaryPrimitives.ReadUInt32LittleEndian(bytes[(int)(offsets[index] - offsets[start])..]); + var word = System.Buffers.Binary.BinaryPrimitives.ReadUInt32LittleEndian(bytes[(int)(offsets[index] - offsets[start])..]); + values[target] = word; valid[target] = true; + if (scratch.Recording) + { + scratch.NoteRead(runFirst + (ulong)(offsets[index] - offsets[start]), word); + } } start = end; @@ -796,7 +1008,7 @@ private static bool TryReadFixed(ReadStep[] reads, FixedReads plan, ResourceRunt for (var index = start; index < end; index++) { ref readonly var read = ref reads[order[index]]; - ReadWord(inputs, lowest + (ulong)(offsets[index] - origin), baseAddress, read.Absolute, read.Target, values, valid); + ReadWord(inputs, lowest + (ulong)(offsets[index] - origin), baseAddress, read.Absolute, read.Target, scratch); } start = end; @@ -874,7 +1086,7 @@ private static void ReadLevel(Level level, ResourceRuntimeInputs inputs, Scratch for (var index = start; index < end; index++) { - ReadWord(inputs, addresses[index], bases[index], absolute[index], targets[index], values, valid); + ReadWord(inputs, addresses[index], bases[index], absolute[index], targets[index], scratch); } start = end; @@ -1048,23 +1260,39 @@ private static bool ReadRun(ResidentGuestBytesReader reader, bool clean, Scratch for (var index = start; index < end; index++) { var target = scratch.Targets[index]; - scratch.Values[target] = System.Buffers.Binary.BinaryPrimitives.ReadUInt32LittleEndian(bytes[(int)(addresses[index] - first)..]); + var word = System.Buffers.Binary.BinaryPrimitives.ReadUInt32LittleEndian(bytes[(int)(addresses[index] - first)..]); + scratch.Values[target] = word; scratch.Valid[target] = true; + if (scratch.Recording) + { + scratch.NoteRead(addresses[index], word); + } } return true; } - private static void ReadWord(ResourceRuntimeInputs inputs, ulong address, ulong baseAddress, bool absolute, int target, ulong[] values, bool[] valid) + private static void ReadWord(ResourceRuntimeInputs inputs, ulong address, ulong baseAddress, bool absolute, int target, Scratch scratch) { + var values = scratch.Values; + var valid = scratch.Valid; if (inputs.ReadMemory is not null && inputs.ReadMemory(address, out var word)) { values[target] = word; valid[target] = true; + if (scratch.Recording) + { + scratch.NoteRead(address, word); + } + return; } values[target] = 0; valid[target] = (baseAddress & ~3ul) == 0 || (absolute && inputs.ReadMemory is not null && !inputs.ReadsClean); + if (scratch.Recording) + { + scratch.Unreadable.Add(address); + } } } diff --git a/src/SharpEmu.ShaderCompiler/Resources/ResourceMaterializer.cs b/src/SharpEmu.ShaderCompiler/Resources/ResourceMaterializer.cs index 2a2fdea11..6d33e307d 100644 --- a/src/SharpEmu.ShaderCompiler/Resources/ResourceMaterializer.cs +++ b/src/SharpEmu.ShaderCompiler/Resources/ResourceMaterializer.cs @@ -377,7 +377,80 @@ public FastOrigin(ShaderResourcePlan plan, ResourceRuntimeInputs inputs, Resourc : this(plan, inputs, inputs.UserData, inputs.ShaderBase, inputs.ComputeState, specialization) { } - } + + private MaterializationProgram.ReadProof? _proof; + + // What an evaluation of this origin's own draw values that emitted the snapshot's words read (ReadProof, set by + // AttachProof and NoteRevalidation only): the origin's user data, shader base and readers are the ones it was + // recorded with. Read and replaced from any thread. + public MaterializationProgram.ReadProof? Proof + { + get => Volatile.Read(ref _proof); + set => Volatile.Write(ref _proof, value); + } + } + + // SHARPEMU_RESOURCE_READ_PROOF: on (default), 0 (every revalidation evaluates the program word by word, as before), + // verify (a proved revalidation also evaluates in full and stops when the snapshot is not current). + // + // A fast snapshot's revalidation evaluates its program again with the snapshot's own user data, shader base and + // readers and compares the words it emits with the snapshot. The evaluation that made the snapshot (or last found it + // current) records what it read (MaterializationProgram.ReadProof); with it on, the revalidation compares those words + // where they lie (ResourceRuntimeInputs.CompareGuestWords: the ownership tests a word read makes, recorded as it + // records them, then the bytes), reads its unreadable words again and evaluates the branches' active sources, and + // when all are as recorded the snapshot is current without evaluating the program, emitting its words or comparing + // them (TryProve). Any refusal or difference evaluates in full, which records a new proof. Demon's Souls revalidates + // ~5000 kept stages a frame through the resolve memo, each reading ~45-100 descriptor words one by one. + internal enum ReadProofMode + { + Off, + On, + Verify, + } + + internal static ReadProofMode ParseReadProofMode(string? value) => value?.Trim().ToLowerInvariant() switch + { + "0" or "off" => ReadProofMode.Off, + "verify" => ReadProofMode.Verify, + _ => ReadProofMode.On, + }; + + internal static ReadProofMode ReadProofs { get; set; } = ParseReadProofMode(Environment.GetEnvironmentVariable("SHARPEMU_RESOURCE_READ_PROOF")); + + // A verify-mode proof whose replay differs from the full evaluation (the full one compared its words again first). + public sealed class ReadProofMismatchException(string message) : InvalidOperationException(message); + + private static readonly ThreadCounter _proofHits = new(); + private static readonly ThreadCounter _proofNone = new(); + private static readonly ThreadCounter _proofNoComparer = new(); + private static readonly ThreadCounter _proofNormalized = new(); + private static readonly ThreadCounter _proofRefusedCurrent = new(); + private static readonly ThreadCounter _proofChanged = new(); + private static readonly ThreadCounter _proofRecorded = new(); + private static readonly ThreadCounter _proofTorn = new(); + private static readonly ThreadCounter _proofUnmatched = new(); + private static readonly ThreadCounter _proofVerified = new(); + private static readonly ThreadCounter _proofVerifyRaced = new(); + private static long _proofVerifyFailed; + + // The read_proof=(...) part of the prefetch counters: revalidations proved current (hits); revalidations evaluated in + // full because the origin had no proof (none), there was no comparer (no_comparer) or the plan normalizes images + // through the host (normalized), or because the proof did not hold and the words then evaluated to the snapshot + // (refused: owned or unreadable words, or changes the output does not show) or not (changed); proofs recorded, + // refused (torn: one address read as two values) and not kept (unmatched: a snapshot that differs from the words + // its evaluation emitted); verify counts. + public static string TakeReadProofReport() => FormattableString.Invariant( + $"read_proof=(mode={ReadProofs.ToString().ToLowerInvariant()},hits={_proofHits.Take()},none={_proofNone.Take()},") + + FormattableString.Invariant($"no_comparer={_proofNoComparer.Take()},normalized={_proofNormalized.Take()},refused={_proofRefusedCurrent.Take()},changed={_proofChanged.Take()},") + + FormattableString.Invariant($"recorded={_proofRecorded.Take()},torn={_proofTorn.Take()},unmatched={_proofUnmatched.Take()},verified={_proofVerified.Take()},") + + FormattableString.Invariant($"verify_raced={_proofVerifyRaced.Take()},verify_failed={Interlocked.Read(ref _proofVerifyFailed)})"); + + // The proof a fast snapshot's origin holds (tests). + internal static MaterializationProgram.ReadProof? ReadProofOf(ResourceSnapshot snapshot) => (snapshot.Origin as FastOrigin)?.Proof; + + // The test seam for verify: puts a proof on a fast snapshot's origin as if its evaluation had recorded it. + internal static void SetReadProofForTest(ResourceSnapshot snapshot, MaterializationProgram.ReadProof? proof) => + ((FastOrigin)snapshot.Origin!).Proof = proof; // RevalidateOrRebuildFast's answer. public enum FastRevalidation @@ -439,13 +512,21 @@ public static FastRevalidation RevalidateOrRebuildFast(ResourceSnapshot snapshot var output = TakeOutput(); try { - if (!EvaluateInto(plan, inputs, output)) + var path = TryProve(plan, snapshot, origin, inputs, output); + if (path == ProofPath.Proved) + { + return FastRevalidation.Current; + } + + if (!EvaluateInto(plan, inputs, output, Records(path), out var proof, origin.Proof)) { _lastRebuildRefusal = RebuildRefusal.Evaluate; return FastRevalidation.Stale; } - if (SameAsOutput(plan, snapshot, output)) + var same = SameAsOutput(plan, snapshot, output); + NoteRevalidation(origin, proof, path, same); + if (same) { return FastRevalidation.Current; } @@ -474,6 +555,9 @@ public static FastRevalidation RevalidateOrRebuildFast(ResourceSnapshot snapshot return FastRevalidation.Stale; } + // The rebuilt snapshot's origin has this origin's draw values and readers: the reads just made are its own. + AttachProof(plan, next, output, proof); + rebuilt = next; return FastRevalidation.Rebuilt; } @@ -516,7 +600,35 @@ public static FastRevalidation RevalidateOrRebuildFast(ResourceSnapshot snapshot inputs.ComputeState = origin.ComputeState; try { - return Revalidate(origin.Plan, snapshot, inputs); + var plan = origin.Plan; + _lastRevalidateRefused = plan.MaterializationProgram is null; + if (_lastRevalidateRefused) + { + return false; + } + + var output = TakeOutput(); + try + { + var path = TryProve(plan, snapshot, origin, inputs, output); + if (path == ProofPath.Proved) + { + return true; + } + + if (!EvaluateInto(plan, inputs, output, Records(path), out var proof, origin.Proof)) + { + return false; + } + + var same = SameAsOutput(plan, snapshot, output); + NoteRevalidation(origin, proof, path, same); + return same; + } + finally + { + _programOutput = output; + } } finally { @@ -525,6 +637,165 @@ public static FastRevalidation RevalidateOrRebuildFast(ResourceSnapshot snapshot } } + // How a revalidation went (TryProve). + private enum ProofPath + { + // SHARPEMU_RESOURCE_READ_PROOF=0: evaluated in full, nothing recorded. + Off, + // The origin holds no proof: evaluated in full, recorded. + None, + // No comparer, or the plan normalizes image descriptors through a host: evaluated in full, nothing recorded. + NoComparer, + Normalized, + // The proof stands: the snapshot is current, nothing evaluated. + Proved, + // A word compared unequal or owned, an unreadable word read, or the active sources differ: evaluated in full. + Refused, + } + + // Whether the origin's proof shows its snapshot current without evaluating its program (ReadProofMode). The proof is + // only ever held by an origin whose snapshot matched the words that proof's evaluation emitted (AttachProof), and it + // was recorded with the origin's own user data, shader base, compute state and readers (the inputs here), so while + // its words compare equal (through the ownership tests a word read makes, recorded as that read records them), its + // unreadable words still read nothing, and the branches leave the same sources active, a full evaluation would emit + // the same words and SameAsOutput would answer true again (MaterializationProgram.ReadProof). Verify also evaluates + // in full and stops on a snapshot that is not current while the proof still compares equal. + private static ProofPath TryProve(ShaderResourcePlan plan, ResourceSnapshot snapshot, FastOrigin origin, ResourceRuntimeInputs inputs, + MaterializationProgram.Output output) + { + var mode = ReadProofs; + if (mode == ReadProofMode.Off) + { + return ProofPath.Off; + } + + // A host image normalizer may answer from more than the words (ShaderProgramCache.ImageNormalizer). + if (plan.NormalizeImageDescriptor is not null) + { + return ProofPath.Normalized; + } + + if (inputs.CompareGuestWords is not { } compare) + { + return ProofPath.NoComparer; + } + + if (origin.Proof is not { } proof) + { + return ProofPath.None; + } + + if (!Holds(plan, proof, inputs, compare)) + { + return ProofPath.Refused; + } + + _proofHits.Increment(); + if (mode == ReadProofMode.Verify) + { + VerifyProof(plan, snapshot, proof, inputs, output); + } + + return ProofPath.Proved; + } + + // Whether the evaluation a path leads to records a proof: only where one could be taken next time. + private static bool Records(ProofPath path) => path is ProofPath.None or ProofPath.Refused; + + private static bool Holds(ShaderResourcePlan plan, MaterializationProgram.ReadProof proof, ResourceRuntimeInputs inputs, GuestWordsComparer compare) + { + if (!ReferenceEquals(proof.Program, plan.MaterializationProgram) || !compare(proof.Addresses, proof.Lengths, proof.Bytes)) + { + return false; + } + + foreach (var address in proof.Unreadable) + { + if (inputs.ReadMemory is { } read && read(address, out _)) + { + return false; + } + } + + return plan.ResourceBranches.Count == 0 || + RuntimeValueEvaluator.EvaluateActiveSources(plan, inputs).AsSpan().SequenceEqual(proof.ActiveSources); + } + + // After a full revalidation: counted by why it was not proved, and its proof kept on the origin when its words were + // the snapshot's (a rebuild hands it to the rebuilt snapshot's origin instead, AttachProof). + private static void NoteRevalidation(FastOrigin origin, MaterializationProgram.ReadProof? proof, ProofPath path, bool same) + { + switch (path) + { + case ProofPath.Off: + return; + case ProofPath.None: + _proofNone.Increment(); + break; + case ProofPath.NoComparer: + _proofNoComparer.Increment(); + break; + case ProofPath.Normalized: + _proofNormalized.Increment(); + break; + default: + (same ? _proofRefusedCurrent : _proofChanged).Increment(); + break; + } + + if (same) + { + origin.Proof = proof; + } + } + + // A proof recorded by the evaluation that emitted output, kept on the origin of the snapshot materialized from it with + // the same draw values and readers only when the snapshot matches those words (unmatched otherwise, never expected). + private static void AttachProof(ShaderResourcePlan plan, ResourceSnapshot snapshot, MaterializationProgram.Output output, + MaterializationProgram.ReadProof? proof) + { + if (proof is null || snapshot.Origin is not FastOrigin origin) + { + return; + } + + if (!SameAsOutput(plan, snapshot, output)) + { + _proofUnmatched.Increment(); + return; + } + + origin.Proof = proof; + } + + [ThreadStatic] + private static MaterializationProgram.Output? _verifyOutput; + + // Verify: a proved snapshot against a full evaluation of the same inputs. Not current while the proof's words still + // compare equal is a wrong proof (counted, then thrown for the host's fatal); after they changed, a race with a guest + // write (verify_raced). + private static void VerifyProof(ShaderResourcePlan plan, ResourceSnapshot snapshot, MaterializationProgram.ReadProof proof, + ResourceRuntimeInputs inputs, MaterializationProgram.Output output) + { + if (EvaluateInto(plan, inputs, output) && SameAsOutput(plan, snapshot, output)) + { + _proofVerified.Increment(); + return; + } + + if (!Holds(plan, proof, inputs, inputs.CompareGuestWords!)) + { + _proofVerifyRaced.Increment(); + return; + } + + Interlocked.Increment(ref _proofVerifyFailed); + var message = $"[SHADER][READ_PROOF] verify mismatch: proved current but evaluates otherwise plan=0x{plan.Hash:X16} stage={plan.Stage} " + + $"ranges={proof.Addresses.Length} bytes={proof.Bytes.Length} unreadable={proof.Unreadable.Length}."; + Console.Error.WriteLine(message); + throw new ReadProofMismatchException(message); + } + // Whether the plan evaluates to the snapshot's words again for these inputs (a draw's user data, shader base and // readers), read as a materialization reads them; a reader wrapper that tells table words apart (TablePhase) is // refused (LastRevalidateRefused). @@ -572,13 +843,32 @@ private static MaterializationProgram.Output TakeOutput() // The program's words as a full materialization would read them: written ranges in the table // and unusable image descriptors as zeros. - private static bool EvaluateInto(ShaderResourcePlan plan, ResourceRuntimeInputs inputs, MaterializationProgram.Output output) + private static bool EvaluateInto(ShaderResourcePlan plan, ResourceRuntimeInputs inputs, MaterializationProgram.Output output) => + EvaluateInto(plan, inputs, output, record: false, out _); + + // With record, the proof of the evaluation's reads (null when refused, counted); previous, the proof it may keep or + // share ranges with (MaterializationProgram.ReadProof.Build). + private static bool EvaluateInto(ShaderResourcePlan plan, ResourceRuntimeInputs inputs, MaterializationProgram.Output output, bool record, + out MaterializationProgram.ReadProof? proof, MaterializationProgram.ReadProof? previous = null) { - if (!plan.MaterializationProgram!.TryRunInto(plan, inputs, checked(plan.WrittenRangeCount * ShaderResourcePlan.WrittenRangeDwordCount), output)) + if (!plan.MaterializationProgram!.TryRunInto(plan, inputs, checked(plan.WrittenRangeCount * ShaderResourcePlan.WrittenRangeDwordCount), output, + record, previous, out proof)) { + proof = null; return false; } + if (record) + { + (proof is null ? _proofTorn : _proofRecorded).Increment(); + } + + return FinishOutput(plan, output); + } + + // The written ranges in the table, normalized descriptors and unusable images cleared, as EvaluateInto leaves them. + private static bool FinishOutput(ShaderResourcePlan plan, MaterializationProgram.Output output) + { var table = output.TableWords; foreach (var range in output.RangeValues) { @@ -718,7 +1008,8 @@ public static bool MaterializeFast( var output = TakeOutput(); try { - if (!EvaluateInto(plan, inputs, output)) + var record = ReadProofs != ReadProofMode.Off && plan.NormalizeImageDescriptor is null && inputs.CompareGuestWords is not null; + if (!EvaluateInto(plan, inputs, output, record, out var proof)) { _programFallbacks.Increment(); return MaterializeFastFromSnapshot(plan, inputs, ref snapshot, ref specialization, out failure); @@ -727,7 +1018,15 @@ public static bool MaterializeFast( _programRuns.Increment(); _fastMaterializations.Increment(); _lastFastOutcome = MaterializationTally.Outcome.FastMiss; - return MaterializeFromOutput(plan, inputs, output, ref snapshot, ref specialization, out failure); + if (!MaterializeFromOutput(plan, inputs, output, ref snapshot, ref specialization, out failure)) + { + return false; + } + + // The snapshot's origin holds these inputs' draw values and readers: the reads just made are its own. + AttachProof(plan, snapshot, output, proof); + + return true; } finally { diff --git a/src/SharpEmu.ShaderCompiler/Resources/ResourceRuntimeInputs.cs b/src/SharpEmu.ShaderCompiler/Resources/ResourceRuntimeInputs.cs index 65bbd0d55..39bd13d67 100644 --- a/src/SharpEmu.ShaderCompiler/Resources/ResourceRuntimeInputs.cs +++ b/src/SharpEmu.ShaderCompiler/Resources/ResourceRuntimeInputs.cs @@ -8,6 +8,13 @@ namespace SharpEmu.ShaderCompiler.Resources; // Reads one dword of guest memory; false when the address cannot be read. public delegate bool GuestWordReader(ulong address, out uint word); +// Whether every range of guest memory still holds the recorded bytes (consecutive, range after range), each range found +// as a word read through ReadMemory would find it: true only when every range passes the ownership tests that read makes +// (recorded as that read records them) and its bytes, where that read would take them, are equal; false when one +// differs, or is owned where that read would refuse, or the host cannot tell. A proof of a program evaluation's reads +// (MaterializationProgram.ReadProof); the ranges are runs of whole words, each inside one 256-byte line. +public delegate bool GuestWordsComparer(ReadOnlySpan addresses, ReadOnlySpan lengths, ReadOnlySpan recorded); + // What one draw supplies to materialise a plan: its user data, the shader base and // the two memory readers. The clean reader refuses memory the GPU may still own. public sealed class ResourceRuntimeInputs @@ -29,6 +36,8 @@ public sealed class ResourceRuntimeInputs // Compares recorded ranges in place on a hit; null leaves a hit reading every range back. public ResidentGuestBytesComparer? CompareResidentMemory { get; init; } + // Compares a program evaluation's recorded reads (GuestWordsComparer); null proves nothing, every evaluation reads. + public GuestWordsComparer? CompareGuestWords { get; init; } public bool ReadsClean { get; init; } @@ -51,6 +60,7 @@ public sealed class ResourceRuntimeInputs TablePhase = TablePhase, ReadResidentMemory = ReadResidentMemory, CompareResidentMemory = CompareResidentMemory, + CompareGuestWords = CompareGuestWords, ReadsClean = ReadsClean, DataWritePending = DataWritePending, NullsOffClassLoopRecords = NullsOffClassLoopRecords, @@ -61,6 +71,7 @@ public bool SameReaders(ResourceRuntimeInputs other) => ReferenceEquals(ReadMemory, other.ReadMemory) && ReferenceEquals(ReadCleanMemory, other.ReadCleanMemory) && ReferenceEquals(TraceImageCandidate, other.TraceImageCandidate) && ReferenceEquals(TablePhase, other.TablePhase) && ReferenceEquals(ReadResidentMemory, other.ReadResidentMemory) && ReferenceEquals(CompareResidentMemory, other.CompareResidentMemory) && + ReferenceEquals(CompareGuestWords, other.CompareGuestWords) && ReadsClean == other.ReadsClean && ReferenceEquals(DataWritePending, other.DataWritePending) && NullsOffClassLoopRecords == other.NullsOffClassLoopRecords; @@ -75,6 +86,7 @@ public bool SameReaders(ResourceRuntimeInputs other) => TablePhase = TablePhase, ReadResidentMemory = ReadResidentMemory, CompareResidentMemory = CompareResidentMemory, + CompareGuestWords = CompareGuestWords, ReadsClean = ReadsClean || ReferenceEquals(reader, ReadCleanMemory), DataWritePending = DataWritePending, NullsOffClassLoopRecords = NullsOffClassLoopRecords, @@ -115,6 +127,7 @@ public ResourceRuntimeInputs WithCallArguments(uint userDataBase, IReadOnlyList< TablePhase = TablePhase, ReadResidentMemory = ReadResidentMemory, CompareResidentMemory = CompareResidentMemory, + CompareGuestWords = CompareGuestWords, ReadsClean = ReadsClean, DataWritePending = DataWritePending, NullsOffClassLoopRecords = NullsOffClassLoopRecords, diff --git a/tests/SharpEmu.ShaderCompiler.Tests/Resources/ReadProofTests.cs b/tests/SharpEmu.ShaderCompiler.Tests/Resources/ReadProofTests.cs new file mode 100644 index 000000000..9daea0b37 --- /dev/null +++ b/tests/SharpEmu.ShaderCompiler.Tests/Resources/ReadProofTests.cs @@ -0,0 +1,306 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using System.Text.RegularExpressions; +using SharpEmu.ShaderCompiler.Resources; +using Xunit; +using static SharpEmu.ShaderCompiler.Tests.Resources.ResourceTestProgram; + +namespace SharpEmu.ShaderCompiler.Tests.Resources; + +[CollectionDefinition(nameof(ReadProofModeCollection), DisableParallelization = true)] +public sealed class ReadProofModeCollection; + +// A fast snapshot's revalidation proved from what the evaluation that made it read (ResourceMaterializer.ReadProofs): +// current without reading a word one by one while every word compares equal; evaluated in full when one changed, is +// owned, an unreadable one turned readable, or the proof is refused; verify stops on a wrong proof. +[Collection(nameof(ReadProofModeCollection))] +public sealed class ReadProofTests +{ + // s[0:1] points at a V# the program loads into s[4:7] and reads through: the V# words are the proof's block. + private static ShaderResourcePlan PointerPlan() + { + var plan = ShaderResourcePlan.Extract(Program(ScalarLoad(0, 0, 4, 4), BufferLoad(8, 4), EndProgram(16)), ShaderStage.Compute, Hash, 0, 4); + Assert.True(ResourceMaterializer.CanMaterializeFast(plan)); + return plan; + } + + // A host comparer over a test memory: refuses every range while Owned (as a pending GPU write would), compares the + // words otherwise; counts its calls and the ranges it was asked about. + private sealed class Comparer(TestWordMemory memory) + { + public bool Owned; + public int Calls; + public readonly List<(ulong Address, int Length)> Ranges = []; + + public bool Compare(ReadOnlySpan addresses, ReadOnlySpan lengths, ReadOnlySpan recorded) + { + Calls++; + Ranges.Clear(); + var offset = 0; + for (var index = 0; index < addresses.Length; index++) + { + Ranges.Add((addresses[index], lengths[index])); + if (Owned) + { + return false; + } + + for (var word = 0; word < lengths[index] / sizeof(uint); word++) + { + var address = addresses[index] + (ulong)(word * sizeof(uint)); + if (address < memory.Base || address - memory.Base >= (ulong)memory.Words.Length * sizeof(uint) || + memory.At(address) != System.Buffers.Binary.BinaryPrimitives.ReadUInt32LittleEndian(recorded[(offset + word * sizeof(uint))..])) + { + return false; + } + } + + offset += lengths[index]; + } + + return true; + } + } + + private static (ShaderResourcePlan Plan, TestWordMemory Memory, Comparer Comparer, ResourceRuntimeInputs Inputs) Setup() + { + var plan = PointerPlan(); + var memory = new TestWordMemory { Base = 0x1000, Words = new uint[16] }; + uint[] descriptor = [0x8000, 0x10 << 16, 64, 0x24FAC]; + descriptor.CopyTo(memory.Words, 0); + descriptor.CopyTo(memory.Words, 8); + var comparer = new Comparer(memory); + var inputs = new ResourceRuntimeInputs { ReadMemory = memory.Read, CompareGuestWords = comparer.Compare }; + inputs.UserData = new uint[] { 0x1000, 0, 0, 0 }; + return (plan, memory, comparer, inputs); + } + + private static ResourceSnapshot Materialize(ShaderResourcePlan plan, ResourceRuntimeInputs inputs) + { + var snapshot = new ResourceSnapshot(); + var specialization = new ResourceSpecialization(); + Assert.True(ResourceMaterializer.MaterializeFast(plan, inputs, ref snapshot, ref specialization, out _)); + return snapshot; + } + + private static long Counter(string report, string name) => long.Parse(Regex.Match(report, $@"[(,]{name}=(\d+)").Groups[1].Value); + + private static T WithMode(ResourceMaterializer.ReadProofMode mode, Func body) + { + var previous = ResourceMaterializer.ReadProofs; + ResourceMaterializer.ReadProofs = mode; + try + { + return body(); + } + finally + { + ResourceMaterializer.ReadProofs = previous; + } + } + + [Fact] + public void AnUnchangedBlockProvesTheSnapshotCurrentWithoutReadingAWord() + { + WithMode(ResourceMaterializer.ReadProofMode.On, () => + { + var (plan, memory, comparer, inputs) = Setup(); + var snapshot = Materialize(plan, inputs); + var proof = ResourceMaterializer.ReadProofOf(snapshot); + Assert.NotNull(proof); + // The four V# words, one range in one line. + Assert.Equal([0x1000ul], proof!.Addresses); + Assert.Equal([16], proof.Lengths); + + _ = ResourceMaterializer.TakeReadProofReport(); + var reads = memory.Reads; + Assert.True(ResourceMaterializer.RevalidateFast(snapshot)); + Assert.Equal(ResourceMaterializer.FastRevalidation.Current, ResourceMaterializer.RevalidateOrRebuildFast(snapshot, out var rebuilt)); + Assert.Null(rebuilt); + Assert.Equal(reads, memory.Reads); + Assert.Equal(2, comparer.Calls); + Assert.Equal(2, Counter(ResourceMaterializer.TakeReadProofReport(), "hits")); + return 0; + }); + } + + [Fact] + public void AWordChangedInsideTheBlockIsNotProvedAndTheRebuildCarriesANewProof() + { + WithMode(ResourceMaterializer.ReadProofMode.On, () => + { + var (plan, memory, _, inputs) = Setup(); + var snapshot = Materialize(plan, inputs); + _ = ResourceMaterializer.TakeReadProofReport(); + + // The V#'s record count: inside the compared block. + memory.Words[2] = 128; + var reads = memory.Reads; + Assert.False(ResourceMaterializer.RevalidateFast(snapshot)); + Assert.True(memory.Reads > reads); + var report = ResourceMaterializer.TakeReadProofReport(); + Assert.Equal(0, Counter(report, "hits")); + Assert.Equal(1, Counter(report, "changed")); + + // The rebuilt snapshot's proof is the words read now: it proves the next revalidation. + Assert.Equal(ResourceMaterializer.FastRevalidation.Rebuilt, ResourceMaterializer.RevalidateOrRebuildFast(snapshot, out var rebuilt)); + Assert.NotNull(ResourceMaterializer.ReadProofOf(rebuilt!)); + reads = memory.Reads; + Assert.True(ResourceMaterializer.RevalidateFast(rebuilt!)); + Assert.Equal(reads, memory.Reads); + return 0; + }); + } + + [Fact] + public void AWordChangedOutsideTheBlockStillProves() + { + WithMode(ResourceMaterializer.ReadProofMode.On, () => + { + var (plan, memory, _, inputs) = Setup(); + var snapshot = Materialize(plan, inputs); + // The words right after the V# and the other V#: never read by this draw. + memory.Words[4] = 0xDEAD; + memory.Words[8] = 0x9000; + var reads = memory.Reads; + Assert.True(ResourceMaterializer.RevalidateFast(snapshot)); + Assert.Equal(reads, memory.Reads); + return 0; + }); + } + + [Fact] + public void AnOwnedBlockRefusesTheProofAndReadsEveryWord() + { + WithMode(ResourceMaterializer.ReadProofMode.On, () => + { + var (plan, memory, comparer, inputs) = Setup(); + var snapshot = Materialize(plan, inputs); + _ = ResourceMaterializer.TakeReadProofReport(); + comparer.Owned = true; + var reads = memory.Reads; + Assert.True(ResourceMaterializer.RevalidateFast(snapshot)); + Assert.True(memory.Reads > reads); + var report = ResourceMaterializer.TakeReadProofReport(); + Assert.Equal(0, Counter(report, "hits")); + Assert.Equal(1, Counter(report, "refused")); + + // Owned and changed: still read in full, and found stale. + memory.Words[0] = 0x9000; + Assert.False(ResourceMaterializer.RevalidateFast(snapshot)); + Assert.Equal(1, Counter(ResourceMaterializer.TakeReadProofReport(), "changed")); + return 0; + }); + } + + [Fact] + public void AnUnreadableWordThatTurnsReadableIsNotProved() + { + WithMode(ResourceMaterializer.ReadProofMode.On, () => + { + var (plan, memory, comparer, _) = Setup(); + // A null table pointer: its V# reads as nothing (an unbound buffer) while the low page is unmapped. + var lowMapped = false; + GuestWordReader read = (ulong address, out uint word) => + { + word = 0x40; + return address >= memory.Base ? memory.Read(address, out word) : lowMapped; + }; + var inputs = new ResourceRuntimeInputs { ReadMemory = read, CompareGuestWords = comparer.Compare, UserData = new uint[] { 0, 0, 0, 0 } }; + var snapshot = Materialize(plan, inputs); + var proof = ResourceMaterializer.ReadProofOf(snapshot); + Assert.NotNull(proof); + Assert.Equal([0ul, 4ul, 8ul, 12ul], proof!.Unreadable); + Assert.Empty(proof.Addresses); + Assert.True(ResourceMaterializer.RevalidateFast(snapshot)); + Assert.Equal(ResourceMaterializer.FastRevalidation.Current, ResourceMaterializer.RevalidateOrRebuildFast(snapshot, out _)); + + // Mapped now: the V# reads as words, not nothing. + lowMapped = true; + _ = ResourceMaterializer.TakeReadProofReport(); + Assert.False(ResourceMaterializer.RevalidateFast(snapshot)); + Assert.Equal(1, Counter(ResourceMaterializer.TakeReadProofReport(), "changed")); + return 0; + }); + } + + [Fact] + public void WithNoComparerOrSwitchedOffEveryRevalidationReads() + { + var (plan, memory, comparer, inputs) = Setup(); + WithMode(ResourceMaterializer.ReadProofMode.Off, () => + { + var snapshot = Materialize(plan, inputs); + Assert.Null(ResourceMaterializer.ReadProofOf(snapshot)); + var reads = memory.Reads; + Assert.True(ResourceMaterializer.RevalidateFast(snapshot)); + Assert.True(memory.Reads > reads); + Assert.Equal(0, comparer.Calls); + return 0; + }); + + WithMode(ResourceMaterializer.ReadProofMode.On, () => + { + var bare = new ResourceRuntimeInputs { ReadMemory = memory.Read, UserData = new uint[] { 0x1000, 0, 0, 0 } }; + var snapshot = Materialize(plan, bare); + _ = ResourceMaterializer.TakeReadProofReport(); + var reads = memory.Reads; + Assert.True(ResourceMaterializer.RevalidateFast(snapshot)); + Assert.True(memory.Reads > reads); + Assert.Equal(1, Counter(ResourceMaterializer.TakeReadProofReport(), "no_comparer")); + return 0; + }); + } + + // A proof that compares equal but does not stand for the snapshot (another draw's, attached by hand) answers current + // when it should not; verify evaluates in full beside it and stops. + [Fact] + public void VerifyStopsOnAWrongProof() + { + var (plan, memory, _, inputs) = Setup(); + var kept = WithMode(ResourceMaterializer.ReadProofMode.On, () => Materialize(plan, inputs)); + // Another draw through the other V#, whose proof covers words 8-11. + inputs.UserData = new uint[] { 0x1020, 0, 0, 0 }; + var other = WithMode(ResourceMaterializer.ReadProofMode.On, () => Materialize(plan, inputs)); + // The kept draw's own V# changes: it is stale, but the other draw's proof still compares equal. + memory.Words[0] = 0x9000; + ResourceMaterializer.SetReadProofForTest(kept, ResourceMaterializer.ReadProofOf(other)); + + Assert.True(WithMode(ResourceMaterializer.ReadProofMode.On, () => ResourceMaterializer.RevalidateFast(kept))); + Assert.Throws(() => + WithMode(ResourceMaterializer.ReadProofMode.Verify, () => ResourceMaterializer.RevalidateFast(kept))); + Assert.Throws(() => + WithMode(ResourceMaterializer.ReadProofMode.Verify, () => ResourceMaterializer.RevalidateOrRebuildFast(kept, out _))); + + // A right proof verifies. + _ = ResourceMaterializer.TakeReadProofReport(); + Assert.True(WithMode(ResourceMaterializer.ReadProofMode.Verify, () => ResourceMaterializer.RevalidateFast(other))); + Assert.Equal(1, Counter(ResourceMaterializer.TakeReadProofReport(), "verified")); + } + + // The proof's words: sorted, repeats folded, runs of consecutive words split where they leave a 256-byte line; one + // address read as two values refuses the proof. + [Fact] + public void ProofRangesStayInsideLinesAndATornReadIsRefused() + { + var plan = PointerPlan(); + var program = plan.MaterializationProgram!; + var scratch = new MaterializationProgram.Scratch(); + foreach (var (address, word) in new (ulong, uint)[] { (0x20F8, 3), (0x20F0, 1), (0x20F4, 2), (0x20FC, 4), (0x2100, 5), (0x2104, 6), (0x20F4, 2), (0x3000, 7) }) + { + scratch.NoteRead(address, word); + } + + var proof = MaterializationProgram.ReadProof.Build(program, scratch, []); + Assert.NotNull(proof); + Assert.Equal([0x20F0ul, 0x2100ul, 0x3000ul], proof!.Addresses); + Assert.Equal([16, 8, 4], proof.Lengths); + Assert.Equal(Enumerable.Range(1, 7).SelectMany(word => BitConverter.GetBytes((uint)word)).ToArray(), proof.Bytes); + + scratch.ReadCount = 0; + scratch.NoteRead(0x2000, 1); + scratch.NoteRead(0x2000, 2); + Assert.Null(MaterializationProgram.ReadProof.Build(program, scratch, [])); + } +} From c35bd47154406382202ebe87489e5760e699c939 Mon Sep 17 00:00:00 2001 From: kuba Date: Sun, 15 Nov 2026 15:31:25 +0000 Subject: [PATCH 076/178] [GPU] Compare a read proof's words through the Metal host's ownership tests MetalRenderHost.TryCompareGuestWords: off the worker each range takes the word query of IsOwnedRecorded and records its answer as a word read does, so the take's re-check sees every compared word; a range a pending copy writes is compared through the copy (TryReadThroughPendingCopyConcurrent, source answers recorded), any other owned range refuses with its owned answer dropped. On the worker, TryCompareResidentGuestBytes. Only hosts that can compare get proofs recorded (IShaderPipelineHost.ComparesGuestWords). The read_proof counters join the prefetch counter line, and a verify mismatch is a GpuFatal. DS-shaped draw bench (copied tables): resolver 2.96 -> 2.50 us/job. --- .../Gpu/Pipelines/IShaderPipelineHost.cs | 9 + .../Gpu/Pipelines/ShaderPipelineCache.cs | 2 +- .../Gpu/Pipelines/ShaderProgramCache.cs | 31 ++- .../V2/MetalRenderHost.ConcurrentResolve.cs | 122 +++++++++ .../V2/MetalRenderHost.Pipelines.cs | 35 +++ ...etalClearFoldingTests.GuestWordsCompare.cs | 252 ++++++++++++++++++ .../ShaderPipelineCacheAllocationTests.cs | 5 +- 7 files changed, 451 insertions(+), 5 deletions(-) create mode 100644 tests/SharpEmu.Gpu.Metal.Tests/MetalClearFoldingTests.GuestWordsCompare.cs diff --git a/src/SharpEmu.Libs/Gpu/Pipelines/IShaderPipelineHost.cs b/src/SharpEmu.Libs/Gpu/Pipelines/IShaderPipelineHost.cs index 61d0df4d8..66e7081b2 100644 --- a/src/SharpEmu.Libs/Gpu/Pipelines/IShaderPipelineHost.cs +++ b/src/SharpEmu.Libs/Gpu/Pipelines/IShaderPipelineHost.cs @@ -181,6 +181,15 @@ void SynchronizeShaderCode(ulong address, ulong size) { } bool TryCompareResidentGuestBytes(ReadOnlySpan addresses, ReadOnlySpan lengths, ReadOnlySpan offsets, ReadOnlySpan recorded) => false; + // A program evaluation's recorded reads (SharpEmu.ShaderCompiler.Resources.GuestWordsComparer): true only when each + // range of whole words passes the ownership tests a TryReadGuestWord of its words makes, recorded as those reads record + // theirs, and holds the recorded bytes where those reads would find them (memory as it lies, or the pending copy that + // writes the range); false when one differs, is owned otherwise, or the host cannot tell. + bool TryCompareGuestWords(ReadOnlySpan addresses, ReadOnlySpan lengths, ReadOnlySpan recorded) => false; + + // Whether TryCompareGuestWords can answer true; without it evaluations record no read proofs. + bool ComparesGuestWords => false; + // Whether recorded GPU work may still write this dword, answered without waiting. A // host that returns a delegate lets a shader whose data-only table words the GPU writes // be re-planned to load them on the device (DeviceDataLoads); null keeps them flattened. diff --git a/src/SharpEmu.Libs/Gpu/Pipelines/ShaderPipelineCache.cs b/src/SharpEmu.Libs/Gpu/Pipelines/ShaderPipelineCache.cs index 6e0cedbe7..617f2a44d 100644 --- a/src/SharpEmu.Libs/Gpu/Pipelines/ShaderPipelineCache.cs +++ b/src/SharpEmu.Libs/Gpu/Pipelines/ShaderPipelineCache.cs @@ -851,7 +851,7 @@ public static string TakeKeptProgramsReport() => /// public static string TakeGraphicsResolveReport() => FormattableString.Invariant($"graphics_kept={_graphicsKept.Take()} graphics_resolved={_graphicsResolved.Take()} ") + - GraphicsResolveMemo.TakeReport(); + GraphicsResolveMemo.TakeReport() + " " + ResourceMaterializer.TakeReadProofReport(); // Besides upstream's register stamps, the fork's resolution reads the host viewport transform (dynamic // viewport registers, compared resolved), the depth aspects and triangle-list assembly (per-vertex pixel diff --git a/src/SharpEmu.Libs/Gpu/Pipelines/ShaderProgramCache.cs b/src/SharpEmu.Libs/Gpu/Pipelines/ShaderProgramCache.cs index 06eae3919..25672c888 100644 --- a/src/SharpEmu.Libs/Gpu/Pipelines/ShaderProgramCache.cs +++ b/src/SharpEmu.Libs/Gpu/Pipelines/ShaderProgramCache.cs @@ -361,7 +361,16 @@ public bool Revalidate(in ShaderStageResources stage) } var started = MaterializationTally.StartTiming(); - var fast = ResourceMaterializer.RevalidateFast(stage.Resources); + bool? fast; + try + { + fast = ResourceMaterializer.RevalidateFast(stage.Resources); + } + catch (ResourceMaterializer.ReadProofMismatchException mismatch) + { + throw GpuFatal.Fatal(mismatch.Message); + } + var current = fast ?? (Materializations is { } materializations && materializations.Revalidate(stage.Resources, _readResidentGuestBytes)); var outcome = current ? MaterializationTally.Outcome.KeptRevalidated : fast is not null && ResourceMaterializer.LastRevalidateRefused ? MaterializationTally.Outcome.RevalidateRefused @@ -383,7 +392,17 @@ public ResourceMaterializer.FastRevalidation RevalidateOrRebuild(in ShaderStageR } var started = MaterializationTally.StartTiming(); - var fast = ResourceMaterializer.RevalidateOrRebuildFast(stage.Resources, out var snapshot); + ResourceMaterializer.FastRevalidation fast; + ResourceSnapshot? snapshot; + try + { + fast = ResourceMaterializer.RevalidateOrRebuildFast(stage.Resources, out snapshot); + } + catch (ResourceMaterializer.ReadProofMismatchException mismatch) + { + throw GpuFatal.Fatal(mismatch.Message); + } + if (fast == ResourceMaterializer.FastRevalidation.NotFast) { // A cached materialization: revalidated as before, never rebuilt here. @@ -422,6 +441,7 @@ public ResourceMaterializer.FastRevalidation RevalidateOrRebuild(in ShaderStageR private readonly ResidentGuestBytesReader _readResidentGuestBytes; private readonly ResidentGuestBytesReader? _prefetchResidentGuestBytes; private readonly ResidentGuestBytesComparer? _compareResidentGuestBytes; + private readonly GuestWordsComparer? _compareGuestWords; // The functions the call tables name, decoded once while their code stays the same. private readonly ShaderFunctionCache _functions; @@ -446,6 +466,7 @@ public ShaderProgramCache(CpuContext context, IGuestGpuBackend compiler, IShader _readResidentGuestBytes = ReadResidentGuestBytes; _prefetchResidentGuestBytes = PrefetchEnabled ? _readResidentGuestBytes : null; _compareResidentGuestBytes = ResourceMaterializationCache.InPlaceValidateEnabled ? CompareResidentGuestBytes : null; + _compareGuestWords = host.ComparesGuestWords ? CompareGuestWords : null; _dataWritePending = host.DataWritePending; _functions = new ShaderFunctionCache(_readResidentGuestBytes); } @@ -481,6 +502,11 @@ private bool CompareResidentGuestBytes(ReadOnlySpan addresses, ReadOnlySp ReadOnlySpan recorded) => ReadLog is null && _host.TryCompareResidentGuestBytes(addresses, lengths, offsets, recorded); + // A revalidation's proof of its reads (ResourceMaterializer.ReadProofs): refused while lookups log or trace what they + // read, since a proved evaluation reads nothing word by word. + private bool CompareGuestWords(ReadOnlySpan addresses, ReadOnlySpan lengths, ReadOnlySpan recorded) => + !TracesLookups && _host.TryCompareGuestWords(addresses, lengths, recorded); + private readonly Func? _dataWritePending; private ResourceRuntimeInputs? _inputs; // The shader the reused inputs' image-candidate trace attributes candidates to. @@ -838,6 +864,7 @@ private ShaderProgram CompleteProgram(ProgramSourceEntry entry, bool sourceWasCa : null, ReadResidentMemory = _prefetchResidentGuestBytes, CompareResidentMemory = _compareResidentGuestBytes, + CompareGuestWords = _compareGuestWords, DataWritePending = _dataWritePending, NullsOffClassLoopRecords = NullsOffClassLoopRecords, }; diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.ConcurrentResolve.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.ConcurrentResolve.cs index f7d8b48ef..449f4f727 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.ConcurrentResolve.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.ConcurrentResolve.cs @@ -1269,4 +1269,126 @@ private unsafe bool TryCompareResidentGuestBytesConcurrent( return true; } + + // TryCompareGuestWords off the worker. Each range (whole words in one line) takes IsOwnedRecorded as a word read of + // it does (query Word: its page, its line, or the line's mask, recorded the same way), so the take's re-check + // (IsConcurrentResolveStillCurrent) tests every word compared here as it would the words read. A range a GPU write + // owns is read through the pending copy that writes all of it, as TryReadGuestWordConcurrentTested reads each of its + // words (TryReadThroughPendingCopyConcurrent: that copy the latest write over the range, its source owned by + // nothing, the source's answers recorded, the range's owned answer dropped), and compared there: any word of the + // range read alone finds that same copy, since a later write over it would be the range's latest. Any other owned + // range refuses the compare, its owned answer dropped: the caller then reads the words itself, recording their own + // answers. Then the other ranges' bytes, where they lie. + private bool TryCompareGuestWordsConcurrent(ReadOnlySpan addresses, ReadOnlySpan lengths, ReadOnlySpan recorded, + ConcurrentAssumptions assumptions) + { + if (_backing.SingleCopy is { ReleasedChunks: > 0 }) + { + return false; + } + + var count = addresses.Length; + var offset = 0; + // Ranges answered through a copy (at most 64), left out of the backing compare below. + ulong throughCopies = 0; + Span through = stackalloc byte[MaterializationProgramLineBytes]; + for (var index = 0; index < count; index++) + { + var address = addresses[index]; + var length = lengths[index]; + if (length <= 0 || length > MaterializationProgramLineBytes || ((address | (ulong)length) & 3) != 0 || offset > recorded.Length - length || + ulong.MaxValue - address < (ulong)length) + { + return false; + } + + var answers = assumptions.Answers.Count; + if (IsOwnedRecorded(ConcurrentQuery.Word, address, (ulong)length, assumptions)) + { + var owned = assumptions.Answers.Count > answers; + if (_lastConcurrentOwner == AbandonCause.GpuWrite && index < 64) + { + var before = assumptions.Answers.Count; + var bytes = through[..length]; + if (TryReadThroughPendingCopyConcurrent(address, bytes, assumptions)) + { + if (owned) + { + assumptions.Forget(ConcurrentQuery.Word, address, (ulong)length, before); + } + + if (!bytes.SequenceEqual(recorded.Slice(offset, length))) + { + return false; + } + + throughCopies |= 1UL << index; + offset += length; + continue; + } + } + + if (owned) + { + assumptions.Forget(ConcurrentQuery.Word, address, (ulong)length, assumptions.Answers.Count); + } + + return false; + } + + offset += length; + } + + return offset == recorded.Length && SameBackingBytes(addresses, lengths, recorded, throughCopies); + } + + // Whether each range's backing bytes are the recorded ones (range after range, the ranges skip names left out): + // compared where they lie through the backing's alias when it has one, else read out a range at a time. + private unsafe bool SameBackingBytes(ReadOnlySpan addresses, ReadOnlySpan lengths, ReadOnlySpan recorded, ulong skip = 0) + { + var aliased = _backing.TryEnterBackingAliasAccess(); + try + { + Span read = stackalloc byte[MaterializationProgramLineBytes]; + var offset = 0; + for (var index = 0; index < addresses.Length; index++) + { + var length = lengths[index]; + var expected = recorded.Slice(offset, length); + offset += length; + if (index < 64 && ((skip >> index) & 1) != 0) + { + continue; + } + + if (aliased && _backing.TryResolveBackingAlias(addresses[index], (ulong)length, out var alias)) + { + if (!new ReadOnlySpan((void*)alias, length).SequenceEqual(expected)) + { + return false; + } + + continue; + } + + var bytes = length <= read.Length ? read[..length] : new byte[length]; + if (!_backing.TryReadBacking(addresses[index], bytes) || !bytes.SequenceEqual(expected)) + { + return false; + } + } + } + finally + { + if (aliased) + { + _backing.ExitBackingAliasAccess(); + } + } + + return true; + } + + // The longest range a read proof compares (MaterializationProgram.ReadProof.LineBytes). + private const int MaterializationProgramLineBytes = 256; } diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Pipelines.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Pipelines.cs index 8a4e03801..774ed1f1d 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Pipelines.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Pipelines.cs @@ -2078,6 +2078,41 @@ public unsafe bool TryCompareResidentGuestBytes( return true; } + public bool ComparesGuestWords => true; + + // A program evaluation's recorded reads compared where they lie (IShaderPipelineHost.TryCompareGuestWords): off the + // worker, each range takes the ownership test a word read of it takes, recorded as that read records it + // (TryCompareGuestWordsConcurrent); on the worker, TryCompareResidentGuestBytes's refusals, under which a word read + // would read every byte straight from memory. + public bool TryCompareGuestWords(ReadOnlySpan addresses, ReadOnlySpan lengths, ReadOnlySpan recorded) + { + var count = addresses.Length; + if (lengths.Length != count) + { + return false; + } + + if (count == 0) + { + return recorded.IsEmpty; + } + + if (_concurrentAssumptions is { } assumptions) + { + return TryCompareGuestWordsConcurrent(addresses, lengths, recorded, assumptions); + } + + Span offsets = count <= 128 ? stackalloc int[count] : new int[count]; + var offset = 0; + for (var index = 0; index < count; index++) + { + offsets[index] = offset; + offset += Math.Max(lengths[index], 0); + } + + return offset == recorded.Length && TryCompareResidentGuestBytes(addresses, lengths, offsets, recorded); + } + private Func? _dataWritePending; // A data-only table word the GPU may still be writing: the shader is re-planned to load diff --git a/tests/SharpEmu.Gpu.Metal.Tests/MetalClearFoldingTests.GuestWordsCompare.cs b/tests/SharpEmu.Gpu.Metal.Tests/MetalClearFoldingTests.GuestWordsCompare.cs new file mode 100644 index 000000000..cde2b75b3 --- /dev/null +++ b/tests/SharpEmu.Gpu.Metal.Tests/MetalClearFoldingTests.GuestWordsCompare.cs @@ -0,0 +1,252 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using SharpEmu.Gpu.Metal.V2; +using SharpEmu.Libs.Gpu.Abstractions; +using SharpEmu.Libs.Gpu.GpuCommands; +using SharpEmu.Libs.Gpu.Rendering; +using Xunit; + +namespace SharpEmu.Gpu.Metal.Tests; + +/// +/// A program evaluation's recorded reads compared where they lie (MetalRenderHost.TryCompareGuestWords, the read +/// proof's comparer): off the worker, each range takes the ownership test a word read of it takes and records the +/// answer as that read does, so the worker's re-check at the take sees every compared word; a range a pending GPU write +/// or label owns refuses (the caller then reads the words), with no owned answer left behind; changed or unmapped bytes +/// say false. On the worker, the resident compare's refusals. +/// +public sealed unsafe partial class MetalClearFoldingTests +{ + // Two ranges in the owned page's clean lines and one in a clean page. + private static readonly (ulong Address, int Length)[] ProofRanges = + [(OwnedPage + 0x100, 16), (OwnedPage + 0x8C0, 64), (GuestBase + 0x70000, 8)]; + + // The ranges' backing bytes, range after range, as an evaluation would have recorded them. + private static byte[] ProofBytes(Rig rig, (ulong Address, int Length)[] ranges) + { + var bytes = new byte[ranges.Sum(range => range.Length)]; + var offset = 0; + foreach (var (address, length) in ranges) + { + for (var word = 0; word < length / sizeof(uint); word++) + { + BitConverter.TryWriteBytes(bytes.AsSpan(offset + word * sizeof(uint)), rig.ReadBacking32(address + (ulong)(word * sizeof(uint)))); + } + + offset += length; + } + + return bytes; + } + + // The comparison inside one concurrent resolution, with the answers it left recorded. + private static (bool Equal, string Answers, object Assumptions) CompareConcurrent(Rig rig, (ulong Address, int Length)[] ranges, byte[] recorded) + { + var host = rig.Host; + var concurrent = (IConcurrentResolveHost)host; + concurrent.BeginConcurrentResolve(); + bool equal; + object assumptions; + try + { + equal = host.TryCompareGuestWords([.. ranges.Select(range => range.Address)], [.. ranges.Select(range => range.Length)], recorded); + } + finally + { + assumptions = concurrent.EndConcurrentResolve(); + } + + var answers = string.Join(' ', ((MetalRenderHost.ConcurrentAssumptions)assumptions).Answers + .Select(answer => $"{answer.Query}:0x{answer.Address - GuestBase:X}+{answer.Size}:{answer.Owned}")); + return (equal, answers, assumptions); + } + + private static Rig ProofRig() + { + var rig = new Rig(Device.Value); + rig.Host.ConcurrentOwnedLines = true; + rig.Host.ConcurrentScopedSerial = true; + rig.Host.ConcurrentLineMasks = MetalRenderHost.LineMaskMode.On; + WriteOwnedPage(rig); + for (var word = 0UL; word < 4; word++) + { + rig.WriteBacking32(GuestBase + 0x70000 + word * sizeof(uint), 0xE000u + (uint)word); + } + + return rig; + } + + [Fact] + public void EqualWordsCompareTrueAndRecordAnswersTheTakeChecksAgain() + { + if (!RequireDevice()) return; + using var rig = ProofRig(); + var recorded = ProofBytes(rig, ProofRanges); + var (equal, answers, assumptions) = CompareConcurrent(rig, ProofRanges, recorded); + Assert.True(equal); + // The owned page's clean line, the range itself in the line a pending write shares (its mask), and the clean + // page, as word reads in them record. + Assert.Equal("Word:0x60100+256:False Word:0x608C0+64:False Word:0x70000+4096:False", answers); + var concurrent = (IConcurrentResolveHost)rig.Host; + Assert.True(concurrent.IsStillCurrent(assumptions)); + + // A GPU write recorded over a compared word after the compare: the take refuses the resolution. + rig.Host.NoteGuestMemoryWrite(OwnedPage + 0x8F0, sizeof(uint), MetalGpuWriteOrigin.StorageBuffer); + Assert.False(concurrent.IsStillCurrent(assumptions)); + concurrent.ReleaseAssumptions(assumptions); + } + + [Fact] + public void AChangedWordInsideARangeComparesFalseAndOneOutsideDoesNot() + { + if (!RequireDevice()) return; + using var rig = ProofRig(); + var recorded = ProofBytes(rig, ProofRanges); + rig.WriteBacking32(OwnedPage + 0x8C0 + 60, 0xBAD); + var inside = CompareConcurrent(rig, ProofRanges, recorded); + Assert.False(inside.Equal); + ((IConcurrentResolveHost)rig.Host).ReleaseAssumptions(inside.Assumptions); + + rig.WriteBacking32(OwnedPage + 0x8C0 + 60, 0xD000u + (0x8C0 + 60) / 4); + rig.WriteBacking32(OwnedPage + 0x8C0 + 64, 0xBAD); + rig.WriteBacking32(OwnedPage + 0x110, 0xBAD); + var outside = CompareConcurrent(rig, ProofRanges, recorded); + Assert.True(outside.Equal); + ((IConcurrentResolveHost)rig.Host).ReleaseAssumptions(outside.Assumptions); + } + + [Theory] + [InlineData("gpu_write")] + [InlineData("label")] + public void ARangeAPendingWriteOwnsRefusesWithNoOwnedAnswerLeft(string owner) + { + if (!RequireDevice()) return; + using var rig = ProofRig(); + // The owned page's pending write sits at 0x800 .. 0x810, under the second range; or a label pending over a word + // of the first range, in a line of the page no write owns. + (ulong Address, int Length)[] ranges = owner == "gpu_write" + ? [(OwnedPage + 0x100, 16), (OwnedPage + 0x808, 32), (GuestBase + 0x70000, 8)] + : [(OwnedPage + 0x100, 16), (OwnedPage + 0x880, 32), (GuestBase + 0x70000, 8)]; + var recorded = ProofBytes(rig, ranges); + if (owner == "label") + { + rig.Host.LabelOverlayEnabled = true; + rig.Host.RecordEndOfPipe(new EndOfPipeWrite(EndOfPipeWriteKind.Write32, 1, OwnedPage + 0x104, 0x1234)); + } + + var (equal, answers, assumptions) = CompareConcurrent(rig, ranges, recorded); + Assert.False(equal); + Assert.DoesNotContain(":True", answers); + ((IConcurrentResolveHost)rig.Host).ReleaseAssumptions(assumptions); + } + + [Fact] + public void ARangeAPendingCopyWritesComparesThroughTheCopyAndTheTakeChecksItsSource() + { + if (!RequireDevice()) return; + using var rig = ProofRig(); + RecordPendingCopy(rig); + // Words 4 .. 11 of the destination: the source's period twice. + (ulong Address, int Length)[] ranges = [(CopyDestination + 0x10, 32), (GuestBase + 0x70000, 8)]; + var recorded = ProofBytes(rig, [(GuestBase + 0x70000, 8)]); + var copied = new byte[32]; + for (var word = 0; word < 8; word++) + { + BitConverter.TryWriteBytes(copied.AsSpan(word * sizeof(uint)), 0xA000u + (uint)(word % (int)CopyPeriod)); + } + + recorded = [.. copied, .. recorded]; + var (equal, answers, assumptions) = CompareConcurrent(rig, ranges, recorded); + Assert.True(equal); + // The destination's owned answer is dropped; its source's answer stands in for it. + Assert.DoesNotContain(":True", answers); + Assert.Contains("0x30000", answers); + var concurrent = (IConcurrentResolveHost)rig.Host; + Assert.True(concurrent.IsStillCurrent(assumptions)); + concurrent.ReleaseAssumptions(assumptions); + + // Bytes the copy would write other than those recorded compare false. + copied[4] ^= 1; + recorded = [.. copied, .. recorded.AsSpan(32)]; + var changed = CompareConcurrent(rig, ranges, recorded); + Assert.False(changed.Equal); + concurrent.ReleaseAssumptions(changed.Assumptions); + + // A write recorded after the copy over a compared word comes from stream items after the draw, so the take + // accepts a compare made before it exactly as it accepts a word read through the copy made then + // (TryReadThroughPendingCopyConcurrent); a compare made after it refuses, the copy no longer the range's latest + // write, with no owned answer left behind. + copied[4] ^= 1; + recorded = [.. copied, .. recorded.AsSpan(32)]; + var before = CompareConcurrent(rig, ranges, recorded); + Assert.True(before.Equal); + concurrent.BeginConcurrentResolve(); + object read; + try + { + Assert.True(rig.Host.TryReadGuestWord(CopyDestination + 0x18, out var word)); + Assert.Equal(0xA002u, word); + } + finally + { + read = concurrent.EndConcurrentResolve(); + } + + rig.Host.NoteGuestMemoryWrite(CopyDestination + 0x18, sizeof(uint), MetalGpuWriteOrigin.StorageBuffer); + Assert.True(concurrent.IsStillCurrent(read)); + Assert.True(concurrent.IsStillCurrent(before.Assumptions)); + concurrent.ReleaseAssumptions(read); + concurrent.ReleaseAssumptions(before.Assumptions); + var after = CompareConcurrent(rig, ranges, recorded); + Assert.False(after.Equal); + Assert.DoesNotContain(":True", after.Answers); + concurrent.ReleaseAssumptions(after.Assumptions); + } + + [Fact] + public void AWriteOverTheCopySourceAfterAThroughCopyCompareFailsTheTake() + { + if (!RequireDevice()) return; + using var rig = ProofRig(); + RecordPendingCopy(rig); + (ulong Address, int Length)[] ranges = [(CopyDestination + 0x10, 16)]; + var recorded = new byte[16]; + for (var word = 0; word < 4; word++) + { + BitConverter.TryWriteBytes(recorded.AsSpan(word * sizeof(uint)), 0xA000u + (uint)word); + } + + var (equal, _, assumptions) = CompareConcurrent(rig, ranges, recorded); + Assert.True(equal); + var concurrent = (IConcurrentResolveHost)rig.Host; + rig.Host.NoteGuestMemoryWrite(CopySource + 4, sizeof(uint), MetalGpuWriteOrigin.StorageBuffer); + Assert.False(concurrent.IsStillCurrent(assumptions)); + concurrent.ReleaseAssumptions(assumptions); + } + + [Fact] + public void UnmappedOrMalformedRangesCompareFalse() + { + if (!RequireDevice()) return; + using var rig = ProofRig(); + var far = (Address: GuestBase + 0x4000_0000UL, Length: 8); + Assert.False(CompareConcurrent(rig, [far], new byte[8]).Equal); + // Unaligned, a length past the recorded bytes, and recorded bytes left over. + Assert.False(CompareConcurrent(rig, [(GuestBase + 0x70002, 4)], new byte[4]).Equal); + Assert.False(CompareConcurrent(rig, [(GuestBase + 0x70000, 8)], new byte[4]).Equal); + Assert.False(CompareConcurrent(rig, [(GuestBase + 0x70000, 4)], new byte[8]).Equal); + } + + [Fact] + public void OnTheWorkerAPendingGpuWriteRefusesAndCleanWordsCompare() + { + if (!RequireDevice()) return; + using var rig = ProofRig(); + rig.AliasAccess = true; + (ulong Address, int Length)[] clean = [(GuestBase + 0x70000, 8)]; + Assert.True(rig.Host.TryCompareGuestWords([clean[0].Address], [clean[0].Length], ProofBytes(rig, clean))); + (ulong Address, int Length)[] owned = [(OwnedPage + 0x800, 16)]; + Assert.False(rig.Host.TryCompareGuestWords([owned[0].Address], [owned[0].Length], ProofBytes(rig, owned))); + } +} diff --git a/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/ShaderPipelineCacheAllocationTests.cs b/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/ShaderPipelineCacheAllocationTests.cs index cad87c469..5eef573d5 100644 --- a/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/ShaderPipelineCacheAllocationTests.cs +++ b/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/ShaderPipelineCacheAllocationTests.cs @@ -52,8 +52,9 @@ long Draw() // The upstream merge (tessellation, frontend and kept-pipeline fields) grew these to 520 and 880 bytes, and the binding // packet slot on each stage's resource snapshot (ResourceSnapshot.BindingPacket) to 528 and 896, and the draw's own // user data, shader base and compute state on each fast snapshot's origin (ResourceMaterializer.FastOrigin) to 576 and 992, - // and the specialization that origin keeps (whether a resolve memo rebuild keeps the program) to 584 and 1008. - Assert.True(perDraw[^1] <= (pixelActive ? 1008 : 584), $"bytes={perDraw[^1]}"); + // and the specialization that origin keeps (whether a resolve memo rebuild keeps the program) to 584 and 1008, and the + // read proof comparer on each stage's runtime inputs (ResourceRuntimeInputs.CompareGuestWords) to 592 and 1024. + Assert.True(perDraw[^1] <= (pixelActive ? 1024 : 592), $"bytes={perDraw[^1]}"); var first = cache.GetGraphicsPrograms(banks.Shader.Vertex, banks.Shader.Pixel, banks.Context.ShaderInterface, banks.Context, mappings, pixelActive, depthBound: false, depthAspectBound: false); var second = cache.GetGraphicsPrograms(banks.Shader.Vertex, banks.Shader.Pixel, banks.Context.ShaderInterface, From 5f66c043e415a1c35de35bf2711f406e0ccbd01e Mon Sep 17 00:00:00 2001 From: kuba Date: Sun, 15 Nov 2026 16:07:41 +0000 Subject: [PATCH 077/178] [Metal] Commit the open buffer when the GPU has run dry and it holds enough to split a pass A commit was wanted only once the guest flushed, so a long render pass kept growing in the open buffer while the GPU sat idle (Demon's Souls: idle 18.4-23.1 and 31.8-33.9 ms into the frame with G-buffer draws recorded, and that idle time is frame time). A draw or dispatch about to prepare now commits the buffer, ending an open pass as the Budget commit does there, once everything committed has completed (completion hint; event polled every 50 us only without a completion handler) and the buffer holds at least SHARPEMU_METAL_V2_GPU_DRY_MIN_COMMANDS (64) draws and dispatches and SHARPEMU_METAL_V2_GPU_DRY_MIN_US (500) of recording plus SHARPEMU_METAL_V2_GPU_DRY_SPLIT_PCT (200) percent of the split's cost: the open pass's attachment bytes stored and loaded again at SHARPEMU_METAL_V2_GPU_DRY_SPLIT_US_PER_MB (12). G-buffer set (68 MB): ~3.8 ms; 1024x1024 depth: ~0.7 ms. Flush cause gpu-dry (flush_by gpudry=, end_flush_by gpu-dry:), TBDR gpu_dry=[commits, refused_commands,refused_split] (refusals once per dry spell). SHARPEMU_METAL_V2_COMMIT_WHEN_GPU_DRY=0 off. --- .../V2/MetalCommandStream.cs | 165 ++++++++++++++++++ .../V2/MetalRenderHost.Descriptors.cs | 3 + .../V2/MetalRenderHost.Rendering.cs | 14 +- .../SharpEmu.Gpu.Metal/V2/MetalRenderHost.cs | 4 +- .../V2/MetalV2Diagnostics.cs | 20 +++ 5 files changed, 203 insertions(+), 3 deletions(-) diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalCommandStream.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalCommandStream.cs index 40b9aac0d..7b3a2ece6 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalCommandStream.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalCommandStream.cs @@ -258,6 +258,7 @@ private void NotePassEndFlush() MetalFlushCause.WaitUncommitted => "wait-uncommitted", MetalFlushCause.Poll => "poll", MetalFlushCause.Transient => "transient", + MetalFlushCause.GpuDry => "gpu-dry", _ => "other", }; @@ -424,6 +425,170 @@ private void CommitCoalescedIfOverdue() CommitStream(hold == PassHold.Capped ? "stream-capped" : "stream-overdue"); } + // ---- committing when the GPU has run dry (SHARPEMU_METAL_V2_COMMIT_WHEN_GPU_DRY) ---- + // + // A commit is wanted only once the guest flushes, so between two guest flushes the open buffer + // just grows, even with the GPU idle. Demon's Souls records its G-buffer pass from ~14 to ~33 ms + // into the frame and the guest flushes inside it rarely: the GPU finished the depth prepass at + // 18.4 ms and sat idle until 23.1 with ~4 ms of G-buffer draws recorded, and again from 31.8 to + // 33.9, and from the G-buffer on it works without a gap up to the label that releases the next + // frame, so that idle time is frame time. So a draw or dispatch about to prepare (where the + // Budget commit already ends an open pass) commits the open buffer when the GPU has finished + // everything committed and the buffer holds enough work to pay for the split: the open pass, + // ended there, resumes in the next buffer with its attachments loaded, as after a capped commit. + // + // The bars (GpuDryVerdict): a floor of draws and dispatches since the last commit, so a dry GPU + // does not turn into a command buffer every few draws; and recording time since the buffer's + // first command (the proxy for the GPU work it holds: in that trace the first G-buffer part took + // 8.4 ms to record and 8.7 ms of GPU) of at least a floor plus a share of what the split costs, + // the open pass's attachment bytes stored and loaded once more at a GPU rate per MB. With the + // defaults a 1024x1024 depth-only pass splits after ~0.7 ms of recording, the 68 MB G-buffer set + // after ~3.8 ms. A commit held because the GPU is busy is untouched (the GPU is not dry then); + // one held for the open pass within the hold limit is made here once the bars are met. + // + // The dry test reads the completion hint, which the completion handler keeps current; with no + // handler bound (completions polled), the shared event itself at most every 50 microseconds while + // the hint shows work in flight, so a draw never pays a native call on its own. + + internal enum GpuDryVerdict + { + Commit, + TooFewCommands, + TooLittleForSplit, + } + + /// + /// Whether a buffer the GPU waits for is committed now, given what it recorded since the last + /// commit and the bytes the open pass would store and reload. Pure, so testable without a device. + /// + internal static GpuDryVerdict GpuDryVerdictFor( + long commands, long recordedTicks, long passAttachmentBytes, + long minCommands, long minTicks, long splitTicksPerMb, int splitPercent) + { + if (commands < minCommands) + { + return GpuDryVerdict.TooFewCommands; + } + + // Ending the pass stores its attachments and resuming it loads them: twice the bytes. + var splitTicks = 2.0 * passAttachmentBytes / 1_000_000.0 * splitTicksPerMb * splitPercent / 100.0; + return recordedTicks >= minTicks + splitTicks ? GpuDryVerdict.Commit : GpuDryVerdict.TooLittleForSplit; + } + + /// Whether the worker commits the open buffer for a GPU that has run dry. + internal bool CommitWhenGpuDry { get; set; } = MetalV2Diagnostics.CommitWhenGpuDry; + + internal long GpuDryMinCommands { get; set; } = MetalV2Diagnostics.GpuDryMinCommands; + + internal long GpuDryMinTicks { get; set; } = + MetalV2Diagnostics.GpuDryMinMicroseconds * System.Diagnostics.Stopwatch.Frequency / 1_000_000L; + + internal long GpuDrySplitTicksPerMb { get; set; } = + MetalV2Diagnostics.GpuDrySplitMicrosecondsPerMb * System.Diagnostics.Stopwatch.Frequency / 1_000_000L; + + internal int GpuDrySplitPercent { get; set; } = MetalV2Diagnostics.GpuDrySplitPercent; + + private static readonly long GpuDryPollTicks = System.Diagnostics.Stopwatch.Frequency / 20_000; + + // When the open buffer's recording began (the preparation after its first command); 0 when not yet. + private long _gpuDryRecordSince; + private long _gpuDryPolledTicks; + private long _gpuDryCommits; + private long _gpuDryRefusedCommands; + private long _gpuDryRefusedSplit; + + // The dry spell (submitted serial + 1) each bar last refused, so a refusal counts once per spell. + private ulong _gpuDryCommandsRefusedSpell; + private ulong _gpuDrySplitRefusedSpell; + + internal (long Commits, long RefusedCommands, long RefusedSplit) TakeGpuDryCommits() => + (Interlocked.Exchange(ref _gpuDryCommits, 0), Interlocked.Exchange(ref _gpuDryRefusedCommands, 0), + Interlocked.Exchange(ref _gpuDryRefusedSplit, 0)); + + private string FormatGpuDryCommits() + { + var (commits, commands, split) = TakeGpuDryCommits(); + return $"gpu_dry=[commits:{commits},refused_commands:{commands},refused_split:{split}]"; + } + + // Whether everything committed has completed, reading the shared event at most every GpuDryPollTicks. + private bool GpuRanDry(long now, ulong submitted) + { + if (AssumeGpuBusy is { } busy) + { + return !busy; + } + + if (_completions is not { } completions) + { + return false; + } + + if (completions.CompletedHint >= submitted) + { + return true; + } + + // Every committed buffer carries the completion handler when one is bound, and the handler + // publishes the event's value to the hint: the hint is then as current as a read would be. + if (completions.WantsCompletionHandler || now - _gpuDryPolledTicks < GpuDryPollTicks) + { + return false; + } + + _gpuDryPolledTicks = now; + return ReadCompletedSerial(useCompletedSnapshot: false) >= submitted; + } + + // A draw or dispatch is about to prepare: commits the open buffer if the GPU waits for it. + private void CommitIfGpuDry() + { + if (!CommitWhenGpuDry || _commandBuffer == 0 || _recordedCommands == 0) + { + return; + } + + var now = System.Diagnostics.Stopwatch.GetTimestamp(); + if (_gpuDryRecordSince == 0) + { + _gpuDryRecordSince = now; + return; + } + + var submitted = Volatile.Read(ref _submittedSerial); + if (!GpuRanDry(now, submitted)) + { + return; + } + + var verdict = GpuDryVerdictFor( + _recordedCommands, now - _gpuDryRecordSince, _renderEncoder != 0 ? _openPassAttachmentBytes : 0, + GpuDryMinCommands, GpuDryMinTicks, GpuDrySplitTicksPerMb, GpuDrySplitPercent); + var spell = submitted + 1; + switch (verdict) + { + case GpuDryVerdict.TooFewCommands: + if (_gpuDryCommandsRefusedSpell != spell) + { + _gpuDryCommandsRefusedSpell = spell; + _gpuDryRefusedCommands++; + } + + return; + case GpuDryVerdict.TooLittleForSplit: + if (_gpuDrySplitRefusedSpell != spell) + { + _gpuDrySplitRefusedSpell = spell; + _gpuDryRefusedSplit++; + } + + return; + } + + _gpuDryCommits++; + FlushCommandBuffer(MetalFlushCause.GpuDry); + } + void ICommandStreamHost.FlushAndWait() { if (RunOnWorker(() => ((ICommandStreamHost)this).FlushAndWait())) diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Descriptors.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Descriptors.cs index 92a011d10..94d165825 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Descriptors.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Descriptors.cs @@ -226,6 +226,9 @@ public IResourcePreparation BeginPreparation() { CommitCoalescedIfOverdue(); } + + // Inside a render pass too, like the Budget commit above, when the bars say the split pays. + CommitIfGpuDry(); } _ = EnsureCommandBuffer(); diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Rendering.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Rendering.cs index 55e017982..98bd4f3b1 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Rendering.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Rendering.cs @@ -259,6 +259,9 @@ internal string TakeTransferCauses() // pays it again. Counted as the descriptor is built, from the real pixel size. private long _loadBytes; private long _storeBytes; + + // The open pass's attachment bytes (NoteAttachmentTraffic), 0 with none open: the commit-when-dry bar. + private long _openPassAttachmentBytes; private long _clearedBytes; private long _passesEmpty; private long _discardedBytes; @@ -314,8 +317,10 @@ private void NotePassIdentity(in RenderingState state) private static long AttachmentBytes(in RenderingState state, uint texelBytes) => MetalPassStores.AttachmentBytes(state.Width, state.Height, state.Samples, texelBytes); - private void NoteAttachmentTraffic(in RenderingState state) + // Returns the pass's attachment bytes: what ending it early stores, and resuming it loads, once more. + private long NoteAttachmentTraffic(in RenderingState state) { + long attached = 0; for (var index = 0; index < state.ColorAttachmentCount; index++) { var bytes = AttachmentBytes( @@ -336,6 +341,7 @@ private void NoteAttachmentTraffic(in RenderingState state) } _storeBytes += bytes; + attached += bytes; } ref readonly var depthStencil = ref state.DepthStencilAttachment; @@ -352,6 +358,7 @@ private void NoteAttachmentTraffic(in RenderingState state) } _storeBytes += bytes; + attached += bytes; } if (depthStencil.HasStencil && depthStencil.View.Handle != 0) @@ -369,7 +376,9 @@ private void NoteAttachmentTraffic(in RenderingState state) } _storeBytes += bytes; + attached += bytes; } + return attached; } internal (long Clear, long Target, long Transfer, long Compute, long Flush, long Present, long Other, @@ -1245,7 +1254,7 @@ public void BeginRendering(in RenderingState state) _renderPasses++; var loadBefore = _loadBytes; var storeBefore = _storeBytes; - NoteAttachmentTraffic(in opening); + _openPassAttachmentBytes = NoteAttachmentTraffic(in opening); if (PassProfileEnabled) { PassProfileDescribe(in opening, _loadBytes - loadBefore, _storeBytes - storeBefore); @@ -1368,6 +1377,7 @@ private void FinishRendering(in RenderingState next, bool hasNext) OcclusionAuditClose(); EndAndReleaseEncoder(_renderEncoder, render: true); _renderEncoder = 0; + _openPassAttachmentBytes = 0; _passScratchMask = 0; // The fills the pass held land right behind it (MetalRenderHost.DeferredFills.cs). EncodeDeferredFills(); diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.cs index fc28626ab..76619a4bf 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.cs @@ -569,6 +569,7 @@ internal enum MetalFlushCause : byte WaitUncommitted, // a wait targeted the submission being recorded Poll, // a guest poll with a pending write Transient, // transient staging over budget + GpuDry, // the GPU finished everything committed and the open buffer held enough to split Other, } @@ -733,6 +734,7 @@ private ulong FlushCommandBuffer(PassEndCause cause, MetalFlushCause why) _previousSerial = serial; _commandBuffer = 0; _recordedCommands = 0; + _gpuDryRecordSince = 0; // Whatever cause committed it, a deferred Stream flush is now satisfied. _encodersInBuffer = 0; _commitWantedSince = 0; @@ -2958,7 +2960,7 @@ public void ReportCounters() $"clears_encoded={encodedClears} depth_joins={depthJoins} depth_join_sampled={depthJoinsSampled} depth_join_copies={depthJoinsCopies} " + $"subset_joins={subsetJoins} subset_join_sampled={subsetJoinsSampled}{TakeSubsetRefusals()} " + $"join_device_ranges=[{FormatDeviceRangeJoinChecks()}] " + - $"{TakeUnionPassText()} flush_hold=[{FormatHeldCommits()}] {FormatDeferredFills()} " + + $"{TakeUnionPassText()} flush_hold=[{FormatHeldCommits()}] {FormatGpuDryCommits()} {FormatDeferredFills()} " + $"transfers=[{TakeTransferCauses()}] {TakePreludeText()}" + (CopiesShareCompute ? $" copies_in_encoder={_copiesInEncoder}" : "") + $" alias_writes_discarded={_imageCache.TakeAliasWritesDiscarded()} " + diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalV2Diagnostics.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalV2Diagnostics.cs index 95acd77e5..d839ae1bc 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalV2Diagnostics.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalV2Diagnostics.cs @@ -422,6 +422,26 @@ internal static MetalHostKernelCopyMode ParseHostKernelCopy(string? text) public static readonly int HoldFlushBusyMaxMicroseconds = PositiveInt("SHARPEMU_METAL_V2_FLUSH_HOLD_BUSY_US", 16000); + // SHARPEMU_METAL_V2_COMMIT_WHEN_GPU_DRY=0 leaves the open buffer to the stream's own flushes + // and limits. On, a draw or dispatch about to prepare commits it once the GPU has finished + // everything committed and the buffer holds enough to be worth a split, ending an open render + // pass if one is (MetalCommandStream.cs, GpuDryVerdict). The bars: at least + // SHARPEMU_METAL_V2_GPU_DRY_MIN_COMMANDS draws and dispatches since the last commit, and at least + // SHARPEMU_METAL_V2_GPU_DRY_MIN_US of recording plus SHARPEMU_METAL_V2_GPU_DRY_SPLIT_PCT percent of + // what splitting the open pass costs the GPU, estimated as its attachment bytes stored and loaded + // once more at SHARPEMU_METAL_V2_GPU_DRY_SPLIT_US_PER_MB microseconds per MB (Demon's Souls: a + // 16 MB target loaded and stored in ~0.5 ms, so the 68 MB G-buffer set ~1.6 ms a split). + public static readonly bool CommitWhenGpuDry = + !string.Equals(Environment.GetEnvironmentVariable("SHARPEMU_METAL_V2_COMMIT_WHEN_GPU_DRY"), "0", StringComparison.Ordinal); + + public static readonly int GpuDryMinCommands = PositiveInt("SHARPEMU_METAL_V2_GPU_DRY_MIN_COMMANDS", 64); + + public static readonly int GpuDryMinMicroseconds = PositiveInt("SHARPEMU_METAL_V2_GPU_DRY_MIN_US", 500); + + public static readonly int GpuDrySplitMicrosecondsPerMb = PositiveInt("SHARPEMU_METAL_V2_GPU_DRY_SPLIT_US_PER_MB", 12); + + public static readonly int GpuDrySplitPercent = PositiveInt("SHARPEMU_METAL_V2_GPU_DRY_SPLIT_PCT", 200); + // SHARPEMU_METAL_V2_JOIN_DEVICE_RANGES=0 refuses every depth-only and subset join of a // device-address draw while a label copy is held, as before. Otherwise only one with a held // copy over a range its program reaches that binding did not order (MetalRenderHost.DepthOnlyJoin.cs). From 09cd9c472be13a712d95475fe99990e9b8483878 Mon Sep 17 00:00:00 2001 From: kuba Date: Sun, 15 Nov 2026 16:07:41 +0000 Subject: [PATCH 078/178] [Tests] Cover the commit-when-dry bars and a dry split that resumes the pass with the same image --- .../MetalGpuDryCommitTests.cs | 183 ++++++++++++++++++ 1 file changed, 183 insertions(+) create mode 100644 tests/SharpEmu.Gpu.Metal.Tests/MetalGpuDryCommitTests.cs diff --git a/tests/SharpEmu.Gpu.Metal.Tests/MetalGpuDryCommitTests.cs b/tests/SharpEmu.Gpu.Metal.Tests/MetalGpuDryCommitTests.cs new file mode 100644 index 000000000..8297b8bdc --- /dev/null +++ b/tests/SharpEmu.Gpu.Metal.Tests/MetalGpuDryCommitTests.cs @@ -0,0 +1,183 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using System.Globalization; +using SharpEmu.Gpu.Metal.V2; +using SharpEmu.Libs.Gpu.Abstractions; +using Xunit; +using Xunit.Abstractions; + +namespace SharpEmu.Gpu.Metal.Tests; + +/// +/// With the GPU dry and enough recorded since the last commit, a draw about to prepare commits the +/// open buffer, ending the open render pass: the pass resumes in the next buffer with its +/// attachments loaded, and the image is that of the unsplit pass. A busy GPU, too few commands or +/// too little recording for what the split costs leave the pass whole. Device work is behind the +/// exclusive device gate. +/// +public sealed class MetalGpuDryCommitTests(ITestOutputHelper output) +{ + private const uint Width = 64; + private const uint Height = 8; + private const ulong Address = MetalPassRig.GuestBase + 0x10000; + + // Times in microseconds: 12 us per MB of split traffic, 200 percent of it, a 500 us floor. + private const long MinTicks = 500; + private const long SplitTicksPerMb = 12; + private const int SplitPercent = 200; + + // MetalRenderHost.GpuDryVerdict, as the theory data takes it. + private const int Commit = 0; + private const int TooFew = 1; + private const int TooLittle = 2; + + // Demon's Souls' G-buffer set: 1920x1080, four R32Uint, R16G16Sfloat, R16G16B16A16Sfloat, D32 and S8. + private const long GBufferBytes = 1920L * 1080 * (4 * 4 + 4 + 8 + 4 + 1); + + // A 1024x1024 depth-only shadow map. + private const long ShadowBytes = 1024L * 1024 * 4; + + [Theory] + // No pass open: the floor alone. + [InlineData(64L, 500L, 0L, Commit)] + [InlineData(64L, 499L, 0L, TooLittle)] + [InlineData(63L, 100_000L, 0L, TooFew)] + // The shadow map: 500 + 2 * 4.19 MB * 12 us * 2 = ~701 us. + [InlineData(200L, 710L, ShadowBytes, Commit)] + [InlineData(200L, 690L, ShadowBytes, TooLittle)] + // The G-buffer: 500 + 2 * 68.4 MB * 12 us * 2 = ~3784 us; the trace's dry point had ~4.1 ms recorded. + [InlineData(385L, 4100L, GBufferBytes, Commit)] + [InlineData(300L, 3700L, GBufferBytes, TooLittle)] + [InlineData(10L, 100_000L, GBufferBytes, TooFew)] + public void ADryGpuGetsTheBufferOnlyWhenItHoldsMoreThanTheSplitCosts( + long commands, long recorded, long passBytes, int expected) => + Assert.Equal((MetalRenderHost.GpuDryVerdict)expected, MetalRenderHost.GpuDryVerdictFor( + commands, recorded, passBytes, minCommands: 64, MinTicks, SplitTicksPerMb, SplitPercent)); + + [Fact] + public void TheSplitBarScalesWithThePassAttachmentBytes() + { + static long Bar(long bytes) + { + var low = 0L; + var high = 1_000_000L; + while (low < high) + { + var middle = (low + high) / 2; + if (MetalRenderHost.GpuDryVerdictFor(1000, middle, bytes, 1, MinTicks, SplitTicksPerMb, SplitPercent) == + MetalRenderHost.GpuDryVerdict.Commit) + { + high = middle; + } + else + { + low = middle + 1; + } + } + + return low; + } + + Assert.Equal(MinTicks, Bar(0)); + Assert.InRange(Bar(ShadowBytes), 700, 702); + Assert.InRange(Bar(GBufferBytes), 3780, 3790); + } + + [Fact] + public void ADryGpuSplitsTheOpenPassAndItResumesWithTheSameImage() + { + if (!RequireDevice()) return; + var dry = Run(enabled: true, gpuBusy: false); + var whole = Run(enabled: false, gpuBusy: false); + + Assert.Equal(2L, dry.Passes); + Assert.Equal("gpu-dry:1", dry.EndFlushBy); + Assert.Equal(1L, dry.Commits); + Assert.Equal(1L, whole.Passes); + Assert.Equal(whole.Pixels, dry.Pixels); + for (var x = 0u; x < Width; x++) + { + var texel = (int)(x * 4); + Assert.Equal(x < Width / 2 ? (byte)0xFF : (byte)0x00, dry.Pixels[texel]); + Assert.Equal(x < Width / 2 ? (byte)0x00 : (byte)0xFF, dry.Pixels[texel + 1]); + } + } + + [Theory] + [InlineData(true, 2L, 0L, "busy")] + [InlineData(false, 1000L, 0L, "commands")] + [InlineData(false, 2L, long.MaxValue / 4, "split")] + public void ABusyGpuOrTooLittleRecordedLeavesThePassWhole(bool gpuBusy, long minCommands, long minTicks, string bar) + { + if (!RequireDevice()) return; + var outcome = Run(enabled: true, gpuBusy, minCommands, minTicks); + + Assert.Equal(1L, outcome.Passes); + Assert.Equal("", outcome.EndFlushBy); + Assert.Equal(0L, outcome.Commits); + Assert.Equal(bar == "commands" ? 1L : 0L, outcome.RefusedCommands); + Assert.Equal(bar == "split" ? 1L : 0L, outcome.RefusedSplit); + } + + private sealed record Outcome( + byte[] Pixels, long Passes, string EndFlushBy, long Commits, long RefusedCommands, long RefusedSplit); + + private Outcome Run(bool enabled, bool gpuBusy, long minCommands = 2, long minTicks = 0) + { + using var rig = new MetalPassRig(Device.Value, 1024 * 1024); + var host = rig.Host; + host.CommitWhenGpuDry = enabled; + host.AssumeGpuBusy = gpuBusy; + host.AssumeStreamBusy = true; + host.GpuDryMinCommands = minCommands; + host.GpuDryMinTicks = minTicks; + var formats = new[] { GpuFormat.R8G8B8A8Unorm }; + var red = rig.Pipeline(formats, ["1.0f, 0.0f, 0.0f, 1.0f"], -1f, 0f); + var green = rig.Pipeline(formats, ["0.0f, 1.0f, 0.0f, 1.0f"], 0f, 1f); + var target = rig.MakeTarget(Address, GpuFormat.R8G8B8A8Unorm, Width, Height); + _ = host.TakeGpuDryCommits(); + _ = host.TakePassEndFlushReasons(); + var first = host.RenderPassSerial; + // Two draws recorded (the second preparation starts the recording clock), then the third + // preparation finds the GPU dry and the bars met. + for (var draw = 0; draw < 2; draw++) + { + using (host.BeginPreparation()) + { + rig.Draw(red, [target]); + } + } + + using (host.BeginPreparation()) + { + rig.Draw(green, [target]); + host.EndRendering(); + } + + var passes = host.RenderPassSerial - first; + var endFlushBy = host.TakePassEndFlushReasons(); + var (commits, refusedCommands, refusedSplit) = host.TakeGpuDryCommits(); + host.FlushCommandBuffer(); + var pixels = rig.Read(Address, Width * Height * 4); + output.WriteLine(string.Create(CultureInfo.InvariantCulture, + $"enabled={enabled} gpu_busy={gpuBusy} min_commands={minCommands} passes={passes} end_flush_by=[{endFlushBy}] " + + $"commits={commits} refused_commands={refusedCommands} refused_split={refusedSplit}")); + return new Outcome(pixels, passes, endFlushBy, commits, refusedCommands, refusedSplit); + } + + private bool RequireDevice() + { + if (Environment.GetEnvironmentVariable("SHARPEMU_TEST_REQUIRE_DEVICE") != "1") + { + output.WriteLine("Dry commits are encoded on the device only behind the exclusive device gate."); + return false; + } + + Assert.True(OperatingSystem.IsMacOS()); + Assert.NotEqual(0, Device.Value); + return true; + } + + private static readonly Lazy Device = new(MetalNative.MTLCreateSystemDefaultDevice); +} From 7727e7c58b5a95ac5449e25c156f6d0ba39adc30 Mon Sep 17 00:00:00 2001 From: kuba Date: Sun, 15 Nov 2026 16:11:21 +0000 Subject: [PATCH 079/178] [GPU] Count unresolved draw takes by the kind of item that gated their job The prefetch counter line gains, per kind of the gated non-draw item a draw's job last waited for (dispatch, command-processor write, label/EOP event, fill or copy, wait, interrupt, idle commit, host call, other): the draws submitted with a gate above the draw before them (draw_gate_raises), the takes that found their job unresolved (unresolved_by_gate), the subset the resolving thread had reached before the gate opened (gate_bound_by_gate), and the worker's wait in them; takes_unresolved also counts the jobs already started. The DS-shaped bench gains SHARPEMU_DS_DRAW_BENCH_DISPATCH_EVERY to run a dispatch between draws. --- .../DeferredCommandThread.Recycling.cs | 1 + .../Gpu/GpuCommands/DeferredCommandThread.cs | 24 +++- .../Gpu/Rendering/ParallelProgramPrefetch.cs | 108 +++++++++++++++++- .../V2/MetalCommandStream.cs | 2 +- .../V2/MetalRenderHost.CommandThread.cs | 7 +- .../Scenes/DsDrawCostBenchTests.cs | 17 +++ 6 files changed, 147 insertions(+), 12 deletions(-) diff --git a/src/SharpEmu.Libs/Gpu/GpuCommands/DeferredCommandThread.Recycling.cs b/src/SharpEmu.Libs/Gpu/GpuCommands/DeferredCommandThread.Recycling.cs index 4d8419dc8..3d4573f12 100644 --- a/src/SharpEmu.Libs/Gpu/GpuCommands/DeferredCommandThread.Recycling.cs +++ b/src/SharpEmu.Libs/Gpu/GpuCommands/DeferredCommandThread.Recycling.cs @@ -77,6 +77,7 @@ private void RecycleAsyncItem(Item item) item.Ungated = false; item.IsFill = false; item.IsLabel = false; + item.GateKind = SharpEmu.Libs.Gpu.Rendering.ParallelProgramPrefetch.GateItemKind.None; item.FillValue = 0; item.RangeBytes = null; item.IsQwords = false; diff --git a/src/SharpEmu.Libs/Gpu/GpuCommands/DeferredCommandThread.cs b/src/SharpEmu.Libs/Gpu/GpuCommands/DeferredCommandThread.cs index b7d089db1..f8032dc23 100644 --- a/src/SharpEmu.Libs/Gpu/GpuCommands/DeferredCommandThread.cs +++ b/src/SharpEmu.Libs/Gpu/GpuCommands/DeferredCommandThread.cs @@ -74,6 +74,8 @@ private sealed class Item // An end-of-pipe label: the GPU writes it once the work before it retires, so a read on the // stream's thread finds the bytes as they are until then (PostLabel). public bool IsLabel; + // What kind of item this is, for the draws its gate holds (ParallelProgramPrefetch.NoteGateItem). + public ParallelProgramPrefetch.GateItemKind GateKind; public bool Sync; public volatile bool Done; public Exception? Failure; @@ -254,10 +256,14 @@ public long EnqueueDeferred(AgcExports.DeferredWork work, bool isDraw) return 0; } - public void Post(Action action) + public void Post(Action action) => Post(action, ParallelProgramPrefetch.GateItemKind.Call); + + // A host call of a known kind (an interrupt, a commit), for the gate counters. + public void Post(Action action, ParallelProgramPrefetch.GateItemKind kind) { var item = RentAsyncItem(Kind.Call); item.Action = action; + item.GateKind = kind; Enqueue(item); } @@ -273,7 +279,7 @@ public void PostOrdering(Action action) public void Run(Action action) { - var item = new Item { Kind = Kind.Call, Action = action, Sync = true }; + var item = new Item { Kind = Kind.Call, Action = action, Sync = true, GateKind = ParallelProgramPrefetch.GateItemKind.Wait }; Interlocked.Increment(ref _syncRuns); Enqueue(item); var started = Stopwatch.GetTimestamp(); @@ -293,6 +299,7 @@ public void PostWrite(ulong address, ReadOnlySpan data) var item = RentAsyncItem(Kind.Write); item.Address = address; item.Data = data.ToArray(); + item.GateKind = ParallelProgramPrefetch.GateItemKind.CommandProcessorWrite; lock (_writeLock) { _pendingWrites.Enqueue(item); @@ -314,6 +321,7 @@ public void PostRange(Action action, ulong address, ulong size, bool ungated = f item.RangeSize = size; item.Ungated = ungated && size != 0; item.JobsBefore = _prefetch?.Submitted ?? 0; + item.GateKind = ParallelProgramPrefetch.GateItemKind.Range; if (size != 0) { lock (_writeLock) @@ -333,6 +341,7 @@ public void PostLabel(Action action, ulong address, ulong size, bool ungated = f { var item = RentAsyncItem(Kind.Call); item.IsLabel = size != 0; + item.GateKind = ParallelProgramPrefetch.GateItemKind.Label; item.Action = action; item.Address = address; item.RangeSize = size; @@ -357,6 +366,7 @@ public void PostFill(Action action, ulong address, ulong size, uint value, bool { var item = RentAsyncItem(Kind.Call); item.IsFill = size != 0; + item.GateKind = ParallelProgramPrefetch.GateItemKind.Range; item.FillValue = value; item.Action = action; item.Address = address; @@ -397,6 +407,7 @@ private void PostKnownRange(Action action, ulong address, ulong size, bool ungat item.RangeSize = size; item.Ungated = ungated && size != 0; item.JobsBefore = _prefetch?.Submitted ?? 0; + item.GateKind = ParallelProgramPrefetch.GateItemKind.CommandProcessorWrite; if (KnownRangeReads) { item.RangeBytes = bytes; @@ -694,6 +705,8 @@ private void Enqueue(Item item) _dispatchGate = _enqueuedNonDraw; } + _prefetch?.NoteGateItem(_enqueuedNonDraw, GateKindOf(item)); + if (TraceItemKinds) { NoteItemKind(item); @@ -725,6 +738,13 @@ private void Enqueue(Item item) } } + private static ParallelProgramPrefetch.GateItemKind GateKindOf(Item item) => item.Kind switch + { + Kind.Write => ParallelProgramPrefetch.GateItemKind.CommandProcessorWrite, + Kind.Deferred => item.IsDispatch ? ParallelProgramPrefetch.GateItemKind.Dispatch : ParallelProgramPrefetch.GateItemKind.Other, + _ => item.GateKind == ParallelProgramPrefetch.GateItemKind.None ? ParallelProgramPrefetch.GateItemKind.Other : item.GateKind, + }; + private void WaitForSpace() { lock (_lock) diff --git a/src/SharpEmu.Libs/Gpu/Rendering/ParallelProgramPrefetch.cs b/src/SharpEmu.Libs/Gpu/Rendering/ParallelProgramPrefetch.cs index 3ac5acd53..120f3d3ba 100644 --- a/src/SharpEmu.Libs/Gpu/Rendering/ParallelProgramPrefetch.cs +++ b/src/SharpEmu.Libs/Gpu/Rendering/ParallelProgramPrefetch.cs @@ -33,8 +33,37 @@ public sealed class Job(RegisterBanks banks, long gate, bool indexed = false, in internal long Index; // 0 queued, 1 resolved, 2 abandoned. internal volatile int State; + // The resolving thread (or the caller) has taken it from the queue; it found its gate still closed when it got to it. + internal volatile bool Started; + internal volatile bool GateWaited; } + // The kind of a gated non-draw item, as the command thread queues it (NoteGateItem): what the draws after it wait for. + public enum GateItemKind : byte + { + None, + Dispatch, + // A command-processor write of known bytes (WRITE_DATA, a DMA of known words) or one of the stream's own stores. + CommandProcessorWrite, + // An end-of-pipe event: a label, or with no destination only an interrupt or a signal. + Label, + // A fill or copy of a guest range. + Range, + // A call the stream waits on (a read the worker answers, a host call with a result). + Wait, + // An interrupt the worker raises. + Event, + // A commit the idle stream asks for. + Flush, + // Another posted host call. + Call, + // Other deferred work. + Other, + Count, + } + + private static readonly string[] GateItemKindNames = ["none", "dispatch", "cp", "label", "range", "wait", "event", "flush", "call", "other"]; + private readonly RenderExecutor _executor; private readonly IRenderHost _host; // host.Fatal as one delegate: a method group over an interface makes a new one per use, per draw. @@ -164,6 +193,39 @@ public long[] TakeProviderRefusals() public void NoteDispatchEffect() => Volatile.Write(ref _lastDispatchEffect, Volatile.Read(ref _executedGate)); + // The kind of each gated non-draw item by its gate number, for the counters below. A job's gate is never more than the + // command thread's queue depth (at most 4096 items) behind the newest, so a ring twice that holds every gate in use. + private const int GateKindRing = 8192; + private readonly GateItemKind[] _gateKinds = new GateItemKind[GateKindRing]; + + // On the command thread, as it queues the gated non-draw item that brings its gate count to gate. + public void NoteGateItem(long gate, GateItemKind kind) => _gateKinds[gate & (GateKindRing - 1)] = kind; + + private GateItemKind GateKindOf(long gate) => gate <= 0 ? GateItemKind.None : _gateKinds[gate & (GateKindRing - 1)]; + + // Per kind of the item that last gated a draw's job: the draws submitted with a gate above the draw before them + // (draw_gate_raises), the draw takes that found their job unresolved (busy or queued), the subset whose job the + // resolving thread had reached before its gate opened (gate-bound), and the worker's wait in them. + private long _lastDrawGate; + private readonly long[] _drawGateRaises = new long[(int)GateItemKind.Count]; + private readonly long[] _unresolvedByGate = new long[(int)GateItemKind.Count]; + private readonly long[] _gateBoundByGate = new long[(int)GateItemKind.Count]; + private readonly long[] _unresolvedWaitTicksByGate = new long[(int)GateItemKind.Count]; + private long _unresolvedStarted; + + private static string FormatByKind(long[] counts, Func? format = null) + { + var builder = new System.Text.StringBuilder(); + for (var kind = 1; kind < counts.Length; kind++) + { + var value = Interlocked.Exchange(ref counts[kind], 0); + builder.Append(kind == 1 ? string.Empty : ",").Append(GateItemKindNames[kind]).Append('=') + .Append(format is null ? value.ToString(System.Globalization.CultureInfo.InvariantCulture) : format(value)); + } + + return builder.ToString(); + } + public (long Resolved, long Abandoned, long Taken, long Refused, double WaitMilliseconds) TakeCounters() => (Interlocked.Exchange(ref _resolvedCount, 0), Interlocked.Exchange(ref _abandonedCount, 0), Interlocked.Exchange(ref _takenCount, 0), Interlocked.Exchange(ref _refusedCount, 0), @@ -171,8 +233,17 @@ public long[] TakeProviderRefusals() // A gate above zero holds the job until AdvanceGate reaches it: with the command stream on its own // thread, draws are submitted ahead of the work before them, which may change what they read. - public Job Submit(RegisterBanks banks, long gate = 0, bool indexed = false, int startInstanceUserData = -1) => - Enqueue(new Job(banks, gate, indexed, startInstanceUserData)); + public Job Submit(RegisterBanks banks, long gate = 0, bool indexed = false, int startInstanceUserData = -1) + { + // The command thread alone submits draws with a gate. + if (gate > _lastDrawGate) + { + Interlocked.Increment(ref _drawGateRaises[(int)GateKindOf(gate)]); + } + + _lastDrawGate = gate; + return Enqueue(new Job(banks, gate, indexed, startInstanceUserData)); + } private Job Enqueue(Job job) { @@ -304,7 +375,7 @@ public bool TryTakeGraphics(RegisterBanks banks, in GraphicsProgramInputs inputs // well-prefetched burst is one, and two clock reads per draw were measurable. if (job.State == 0) { - NoteUnresolvedTake(job); + var gateKind = NoteUnresolvedTake(job); var waitStarted = System.Diagnostics.Stopwatch.GetTimestamp(); // Caller work is reported separately, not disguised as a shorter resolver wait. // Keep long queues out of the claim routine's lock/finally frame. @@ -313,7 +384,9 @@ public bool TryTakeGraphics(RegisterBanks banks, in GraphicsProgramInputs inputs !TryResolveOnCaller(job)) { WaitFor(job); - Interlocked.Add(ref _waitTicks, System.Diagnostics.Stopwatch.GetTimestamp() - waitStarted); + var waited = System.Diagnostics.Stopwatch.GetTimestamp() - waitStarted; + Interlocked.Add(ref _waitTicks, waited); + Interlocked.Add(ref _unresolvedWaitTicksByGate[(int)gateKind], waited); } } @@ -398,11 +471,24 @@ public bool TryTakeCompute(RegisterBanks banks, uint dispatchInitiator, uint gro // thread busy with another job, or queued behind others with its gate open (takes_unresolved). private long _unresolvedGated, _unresolvedBusy, _unresolvedQueued; - private void NoteUnresolvedTake(Job job) + private GateItemKind NoteUnresolvedTake(Job job) { if (job.Gate > Volatile.Read(ref _executedGate)) Interlocked.Increment(ref _unresolvedGated); else if (Volatile.Read(ref _running)) Interlocked.Increment(ref _unresolvedBusy); else Interlocked.Increment(ref _unresolvedQueued); + var kind = GateKindOf(job.Gate); + Interlocked.Increment(ref _unresolvedByGate[(int)kind]); + if (job.Started) + { + Interlocked.Increment(ref _unresolvedStarted); + } + + if (job.GateWaited) + { + Interlocked.Increment(ref _gateBoundByGate[(int)kind]); + } + + return kind; } // The resolving thread's idle time in its queue wait and its wakes from it, its time spinning and sleeping on job @@ -428,7 +514,10 @@ public string TakeResolverReport() var lastCpu = Interlocked.Exchange(ref _lastResolverCpu, cpu); var cpuMs = cpu < 0 || lastCpu < 0 ? -1.0 : (cpu - lastCpu) / 1e6; return $"takes_unresolved=(busy={Interlocked.Exchange(ref _unresolvedBusy, 0)},gated={Interlocked.Exchange(ref _unresolvedGated, 0)}," + - $"queued={Interlocked.Exchange(ref _unresolvedQueued, 0)}) resolver_jobs={Interlocked.Exchange(ref _resolverJobs, 0)} " + + $"queued={Interlocked.Exchange(ref _unresolvedQueued, 0)},started={Interlocked.Exchange(ref _unresolvedStarted, 0)}) " + + $"unresolved_by_gate=({FormatByKind(_unresolvedByGate)}) gate_bound_by_gate=({FormatByKind(_gateBoundByGate)}) " + + $"unresolved_wait_ms_by_gate=({FormatByKind(_unresolvedWaitTicksByGate, ticks => Milliseconds(ticks).ToString("F1", culture))}) " + + $"draw_gate_raises=({FormatByKind(_drawGateRaises)}) resolver_jobs={Interlocked.Exchange(ref _resolverJobs, 0)} " + $"resolver_idle_ms={Milliseconds(Interlocked.Exchange(ref _idleTicks, 0)).ToString("F1", culture)} " + $"gate_sleep_ms={Milliseconds(Interlocked.Exchange(ref _gateTicks, 0)).ToString("F1", culture)} idle_wakes={Interlocked.Exchange(ref _idleWakes, 0)} " + $"idle_spin_takes={Interlocked.Exchange(ref _idleSpinTakes, 0)} " + @@ -519,6 +608,7 @@ internal bool TryResolveOnCaller(Job job) return false; _queue.Dequeue(); _running = true; + job.Started = true; if (claimed) { _claimSteals++; @@ -642,6 +732,11 @@ private void Run() job = _queue.Peek(); _workerClaimed = true; + if (job.Gate > Volatile.Read(ref _executedGate)) + { + job.GateWaited = true; + } + var gateStarted = job.Gate > Volatile.Read(ref _executedGate) || _paused ? System.Diagnostics.Stopwatch.GetTimestamp() : 0; if (job.Gate > Volatile.Read(ref _executedGate)) { @@ -696,6 +791,7 @@ private void Run() _queue.Dequeue(); _running = true; + job.Started = true; } var sampled = (++_resolverJobs & (AllocationSamplePeriod - 1)) == 0; diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalCommandStream.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalCommandStream.cs index 40b9aac0d..9f74b4ab8 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalCommandStream.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalCommandStream.cs @@ -2612,7 +2612,7 @@ private void ReportSlowCompletion(ulong serial, long queued, long ran) public void TriggerInterrupt(int eventId, uint contextId) { - if (PostToWorker(() => TriggerInterrupt(eventId, contextId))) + if (PostToWorker(() => TriggerInterrupt(eventId, contextId), SharpEmu.Libs.Gpu.Rendering.ParallelProgramPrefetch.GateItemKind.Event)) { return; } diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.CommandThread.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.CommandThread.cs index 5ccc4797e..737efca9b 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.CommandThread.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.CommandThread.cs @@ -114,7 +114,7 @@ private void RequestIdleCommit() Volatile.Write(ref _idleCommitQueued, 0); CommitCoalescedFlush(); FlushPendingLabelWrites(); - }); + }, SharpEmu.Libs.Gpu.Rendering.ParallelProgramPrefetch.GateItemKind.Flush); } private void RunDeferredWork(AgcExports.DeferredWork work) => _translation!.RunDeferred(work); @@ -188,14 +188,15 @@ internal void StopCommandThread() } // Host work for the worker, queued behind the work before it when called on the command thread. - private bool PostToWorker(Action action) + private bool PostToWorker(Action action, + SharpEmu.Libs.Gpu.Rendering.ParallelProgramPrefetch.GateItemKind kind = SharpEmu.Libs.Gpu.Rendering.ParallelProgramPrefetch.GateItemKind.Call) { if (!OnCommandThread) { return false; } - _commandThread!.Post(action); + _commandThread!.Post(action, kind); return true; } diff --git a/tests/SharpEmu.Gpu.Metal.Tests/Scenes/DsDrawCostBenchTests.cs b/tests/SharpEmu.Gpu.Metal.Tests/Scenes/DsDrawCostBenchTests.cs index a78f58133..96f974fc1 100644 --- a/tests/SharpEmu.Gpu.Metal.Tests/Scenes/DsDrawCostBenchTests.cs +++ b/tests/SharpEmu.Gpu.Metal.Tests/Scenes/DsDrawCostBenchTests.cs @@ -520,6 +520,11 @@ ulong DispatchTable(int dispatch, ulong writeBuffer) // read a table its copy kernel writes every frame: off the worker each table word is owned by the copy's pending // write and answered from its source (~20 word tests a draw, as in game). The destination holds the copy's result. var copiedTables = Environment.GetEnvironmentVariable("SHARPEMU_DS_DRAW_BENCH_COPIED_TABLES") == "1"; + // SHARPEMU_DS_DRAW_BENCH_DISPATCH_EVERY=n: one of the four buffer-storing dispatches after every nth draw of the game + // streams as well, as Demon's Souls runs its ~1000 dispatches a frame between draws: each holds the program + // resolution of the draw after it (its gate), unless that draw's job looks ahead of dispatches + // (SHARPEMU_PREFETCH_DRAW_LOOKAHEAD). 0 (the default) leaves the streams as they were. + var dispatchEvery = int.TryParse(Environment.GetEnvironmentVariable("SHARPEMU_DS_DRAW_BENCH_DISPATCH_EVERY"), out var every) && every > 0 ? every : 0; ulong copyDestination = 0, copySource = 0, copyWords = 0; void ArmCopiedTables() { @@ -617,6 +622,18 @@ void ArmCopiedTables() var emittedFrom = pm4!.Count; EmitDraw(pm4!, draw, pass, passStart || firstOfSubmission, mesh, material, newKey ? pixelConstantCopies[0] : 0); if (newKey) keyChurnStarts.Add((submission, emittedFrom, pm4!.Count)); + if (dispatchEvery != 0 && draw % dispatchEvery == dispatchEvery - 1) + { + var dispatch = draw / dispatchEvery % dispatchTables.Length; + var compute = new SceneState(1, 1); + compute.Context.Clear(); + compute.Uconfig.Clear(); + compute.ComputeShader(computePrograms[dispatch % computePrograms.Length], 8, 8, 1, + [Descriptors.Lo(dispatchTables[dispatch]), Descriptors.Hi(dispatchTables[dispatch])], true, true, false, 1, 0); + compute.Emit(pm4!); + pm4!.DispatchDirect(StorageEdge / 8, StorageEdge / 8, 1); + } + var commitFollows = (int)((submission + 1) / SubmissionsPerCommit) != (int)(submission / SubmissionsPerCommit); if (commitFollows && draw % 6 == 5) { From 93c8f3ff9ed99c80008181e323cf55aacf69a246 Mon Sep 17 00:00:00 2001 From: kuba Date: Sun, 15 Nov 2026 16:18:21 +0000 Subject: [PATCH 080/178] [GPU] Let draw jobs resolve ahead of the dispatches just before them A draw's prefetch job now gates on the sink's DispatchGate, as a dispatch's job does: its programs resolve while the dispatches between it and the last other gated item run, and its take accepts the resolution only when none of the dispatches that ran after the resolution began did more than encode GPU work (NoteDispatchEffect) and the host's answers hold across them (IsStillCurrentAcrossDispatches: ownership re-check plus the GPU write log). Every other gated item (interrupt, idle commit, label-less EOP, host call, wait) still holds the draw. The Metal cross-dispatch check also refuses a resolution that read a destination through a pending copy when a write logged since it began covers that destination: the copy read drops the destination's owned answer, so a later store over it (the destination's new latest write) was not seen. This hole applied to dispatch look-ahead too. SHARPEMU_PREFETCH_DRAW_LOOKAHEAD=0 holds draws behind dispatches again; =verify resolves every accepted look-ahead again on the worker and fails on any difference (GraphicsProgramsComparer). Counters: draw_lookahead=(jobs, taken, refused by abandoned/inputs/effects/ownership, verified). --- .../Agc/AgcExports.CommandStream.cs | 9 +- .../Gpu/Rendering/ParallelProgramPrefetch.cs | 148 +++++++++++- .../Gpu/Rendering/RenderExecutor.Prefetch.cs | 4 + .../V2/MetalRenderHost.ConcurrentResolve.cs | 38 ++- .../V2/MetalRenderHost.CopyReads.cs | 4 + ...MetalClearFoldingTests.DispatchPrefetch.cs | 47 ++++ ...rallelProgramPrefetchDrawLookaheadTests.cs | 228 ++++++++++++++++++ 7 files changed, 465 insertions(+), 13 deletions(-) create mode 100644 tests/SharpEmu.Libs.Tests/Gpu/Rendering/ParallelProgramPrefetchDrawLookaheadTests.cs diff --git a/src/SharpEmu.Libs/Agc/AgcExports.CommandStream.cs b/src/SharpEmu.Libs/Agc/AgcExports.CommandStream.cs index 29fda385a..ed5c9c5d8 100644 --- a/src/SharpEmu.Libs/Agc/AgcExports.CommandStream.cs +++ b/src/SharpEmu.Libs/Agc/AgcExports.CommandStream.cs @@ -236,7 +236,9 @@ internal CommandStreamTranslation(ICpuMemory memory, ICommandStreamHost host, bo _executor.Prefetch = _parallel; _prefetchesDispatches = concurrentHost.PrefetchesDispatches; _dispatchesCrossDispatches = concurrentHost.PrefetchedDispatchesCrossDispatches; - if (_prefetchesDispatches) + _drawsCrossDispatches = concurrentHost.PrefetchedDrawsCrossDispatches && + _parallel.LookaheadMode != ParallelProgramPrefetch.DrawLookaheadMode.Off; + if (_prefetchesDispatches || _drawsCrossDispatches) { _recorder.DispatchEffect = _parallel.NoteDispatchEffect; } @@ -359,6 +361,8 @@ private sealed record ResolvedDrawWork(ResolvedDraw Record) : DeferredWork; // Dispatches get prefetch jobs too, and their gate may leave out the dispatches just before them. private readonly bool _prefetchesDispatches; private readonly bool _dispatchesCrossDispatches; + // Draws' jobs too may leave out the dispatches just before them (ParallelProgramPrefetch.SubmitDrawAhead). + private readonly bool _drawsCrossDispatches; // The host resolves draws and dispatches where they run (PendingDraw/PendingDispatch), not on // the interpreting thread into resolved records (ResolvedDrawWork/ResolvedDispatchWork). @@ -691,7 +695,8 @@ private bool TryRunExecutorDraw(ulong submitId, SubmittedDcbState state, bool in { var snapshot = banks.Snapshot(); var pending = TakePendingDraw(producing, submitId, state, snapshot, indexed, in indexedArguments, in autoArguments, - _parallel?.Submit(snapshot, producing ? Sink!.Gate : 0, indexed, + _parallel?.SubmitDrawAhead(snapshot, producing ? (_drawsCrossDispatches ? Sink!.DispatchGate : Sink!.Gate) : 0, + producing ? Sink!.Gate : 0, indexed, indexed ? indexedArguments.StartInstanceUserData : autoArguments.StartInstanceUserData)); if (producing) { diff --git a/src/SharpEmu.Libs/Gpu/Rendering/ParallelProgramPrefetch.cs b/src/SharpEmu.Libs/Gpu/Rendering/ParallelProgramPrefetch.cs index 120f3d3ba..6ca70df7a 100644 --- a/src/SharpEmu.Libs/Gpu/Rendering/ParallelProgramPrefetch.cs +++ b/src/SharpEmu.Libs/Gpu/Rendering/ParallelProgramPrefetch.cs @@ -36,6 +36,84 @@ public sealed class Job(RegisterBanks banks, long gate, bool indexed = false, in // The resolving thread (or the caller) has taken it from the queue; it found its gate still closed when it got to it. internal volatile bool Started; internal volatile bool GateWaited; + // A draw's job: the gate it would have had without looking ahead (Gate may stop short of the dispatches just before + // it, SubmitDrawAhead), and the gated items that had run when its resolution began. A resolution that began before + // all FullGate items ran looked ahead of the ones that had not, and its take checks it against them. + internal long FullGate; + internal long ExecutedAtStart; + } + + /// + /// A draw's job may resolve before the dispatches just before the draw ran, as a dispatch's may + /// (SubmitCompute): its gate stops short of them, its program resolves while they run, and its take accepts the + /// resolution only when none of those dispatches did more than encode GPU work (NoteDispatchEffect) and the + /// host's ownership answers and GPU write log show nothing it read changed (IsStillCurrentAcrossDispatches); + /// otherwise the draw resolves its programs itself (draw_lookahead refused by reason). Only dispatches are looked + /// ahead of: every other gated item (an interrupt, a commit, an event with no label, a host call) still holds the + /// draws after it. SHARPEMU_PREFETCH_DRAW_LOOKAHEAD=0 holds draws behind dispatches again; =verify also resolves + /// every accepted look-ahead on the worker and fails on any difference in the programs or their bindings. + /// + public enum DrawLookaheadMode : byte + { + Off, + On, + Verify, + } + + public static readonly DrawLookaheadMode DrawLookahead = + ParseDrawLookahead(Environment.GetEnvironmentVariable("SHARPEMU_PREFETCH_DRAW_LOOKAHEAD")); + + internal static DrawLookaheadMode ParseDrawLookahead(string? value) => value switch + { + "0" => DrawLookaheadMode.Off, + "verify" => DrawLookaheadMode.Verify, + _ => Environment.GetEnvironmentVariable("SHARPEMU_PERF_VERIFY") == "1" ? DrawLookaheadMode.Verify : DrawLookaheadMode.On, + }; + + // The mode this prefetch checks takes in (tests set Verify on one instance). + internal DrawLookaheadMode LookaheadMode { get; set; } = DrawLookahead; + + // Why a draw's take refused a resolution that looked ahead of dispatches; Count is accepted. + public enum DrawLookaheadRefusal : byte + { + // The resolution threw (an owned read), so the draw resolves it as any abandoned job. + Abandoned, + // Different inputs. + Inputs, + // A dispatch it was resolved ahead of did more than encode GPU work. + Effects, + // An ownership answer changed, or a GPU write logged since it began covers what it read. + Ownership, + Count, + } + + private static readonly string[] DrawLookaheadRefusalNames = ["abandoned", "inputs", "effects", "ownership"]; + private long _lookaheadJobs, _lookaheadTaken, _lookaheadVerified; + private readonly long[] _lookaheadRefusals = new long[(int)DrawLookaheadRefusal.Count]; + + public (long Jobs, long Taken, long[] Refused, long Verified) TakeDrawLookaheadCounters() + { + var refused = new long[(int)DrawLookaheadRefusal.Count]; + for (var index = 0; index < refused.Length; index++) + { + refused[index] = Interlocked.Exchange(ref _lookaheadRefusals[index], 0); + } + + return (Interlocked.Exchange(ref _lookaheadJobs, 0), Interlocked.Exchange(ref _lookaheadTaken, 0), refused, + Interlocked.Exchange(ref _lookaheadVerified, 0)); + } + + private string TakeDrawLookaheadReport() + { + var (jobs, taken, refused, verified) = TakeDrawLookaheadCounters(); + var builder = new System.Text.StringBuilder("draw_lookahead=(mode=").Append(LookaheadMode.ToString().ToLowerInvariant()) + .Append(",over=dispatch,jobs=").Append(jobs).Append(",taken=").Append(taken).Append(",refused=("); + for (var index = 0; index < refused.Length; index++) + { + builder.Append(index == 0 ? string.Empty : ",").Append(DrawLookaheadRefusalNames[index]).Append('=').Append(refused[index]); + } + + return builder.Append("),verified=").Append(verified).Append(')').ToString(); } // The kind of a gated non-draw item, as the command thread queues it (NoteGateItem): what the draws after it wait for. @@ -233,16 +311,22 @@ private static string FormatByKind(long[] counts, Func? format = n // A gate above zero holds the job until AdvanceGate reaches it: with the command stream on its own // thread, draws are submitted ahead of the work before them, which may change what they read. - public Job Submit(RegisterBanks banks, long gate = 0, bool indexed = false, int startInstanceUserData = -1) + public Job Submit(RegisterBanks banks, long gate = 0, bool indexed = false, int startInstanceUserData = -1) => + SubmitDrawAhead(banks, gate, gate, indexed, startInstanceUserData); + + // A draw's job whose resolution may start once the first gate items ran, before the rest up to fullGate (dispatches + // only, the sink's DispatchGate) did; with gate == fullGate, Submit. + public Job SubmitDrawAhead(RegisterBanks banks, long gate, long fullGate, bool indexed = false, int startInstanceUserData = -1) { + fullGate = Math.Max(gate, fullGate); // The command thread alone submits draws with a gate. - if (gate > _lastDrawGate) + if (fullGate > _lastDrawGate) { - Interlocked.Increment(ref _drawGateRaises[(int)GateKindOf(gate)]); + Interlocked.Increment(ref _drawGateRaises[(int)GateKindOf(fullGate)]); } - _lastDrawGate = gate; - return Enqueue(new Job(banks, gate, indexed, startInstanceUserData)); + _lastDrawGate = fullGate; + return Enqueue(new Job(banks, gate, indexed, startInstanceUserData) { FullGate = fullGate }); } private Job Enqueue(Job job) @@ -391,25 +475,71 @@ public bool TryTakeGraphics(RegisterBanks banks, in GraphicsProgramInputs inputs } using var profile = RenderPhaseProfile.MeasureDetail(RenderPhaseProfile.Phase.ProgramPrefetchValidation); + // The resolution began before every gated item ahead of the draw ran: it looked ahead of dispatches. + var lookedAhead = job.ExecutedAtStart < job.FullGate; + if (lookedAhead) + { + Interlocked.Increment(ref _lookaheadJobs); + } + if (job.State != 1) { + if (lookedAhead) + { + Interlocked.Increment(ref _lookaheadRefusals[(int)DrawLookaheadRefusal.Abandoned]); + } + ReleaseAssumptions(job); return false; } - var current = job.Inputs.Equals(inputs) && _concurrent.IsStillCurrent(job.Assumptions!); + var refusal = !job.Inputs.Equals(inputs) ? DrawLookaheadRefusal.Inputs + : !lookedAhead ? (_concurrent.IsStillCurrent(job.Assumptions!) ? DrawLookaheadRefusal.Count : DrawLookaheadRefusal.Ownership) + // A dispatch that ran after the resolution began (gate above ExecutedAtStart) did more than encode GPU work. + : Volatile.Read(ref _lastDispatchEffect) >= job.ExecutedAtStart ? DrawLookaheadRefusal.Effects + : !_concurrent.IsStillCurrentAcrossDispatches(job.Assumptions!) ? DrawLookaheadRefusal.Ownership + : DrawLookaheadRefusal.Count; ReleaseAssumptions(job); - if (!current) + if (refusal != DrawLookaheadRefusal.Count) { + if (lookedAhead) + { + Interlocked.Increment(ref _lookaheadRefusals[(int)refusal]); + } + Interlocked.Increment(ref _refusedCount); return false; } Interlocked.Increment(ref _takenCount); programs = job.Programs!; + if (lookedAhead) + { + Interlocked.Increment(ref _lookaheadTaken); + if (LookaheadMode == DrawLookaheadMode.Verify) + { + programs = VerifyLookahead(job, banks, in inputs); + } + } + return true; } + // SHARPEMU_PREFETCH_DRAW_LOOKAHEAD=verify: the worker resolves the draw as it would have without the job, and the two + // must hand the executor the same programs, inputs and resources (GraphicsProgramsComparer). + private GraphicsPrograms VerifyLookahead(Job job, RegisterBanks banks, in GraphicsProgramInputs inputs) + { + var resolved = _executor.ResolveGraphicsPrograms(banks, in inputs); + Interlocked.Increment(ref _lookaheadVerified); + if (SharpEmu.Libs.Gpu.Pipelines.GraphicsProgramsComparer.Difference(job.Programs!, resolved) is { } difference) + { + throw _fatal($"A draw's programs resolved ahead of the dispatches before it differ from the worker's: {difference} " + + $"(job {job.Index}, gate {job.Gate}, full gate {job.FullGate}, executed at start {job.ExecutedAtStart})."); + } + + return resolved; + } + // The dispatch the worker runs now takes the program its job resolved when the job was resolved from the same banks // and arguments, the provider stood for it, no dispatch it was resolved ahead of did more than encode GPU work, // and the host's ownership answers still hold across those dispatches; otherwise it resolves the program itself. @@ -517,7 +647,7 @@ public string TakeResolverReport() $"queued={Interlocked.Exchange(ref _unresolvedQueued, 0)},started={Interlocked.Exchange(ref _unresolvedStarted, 0)}) " + $"unresolved_by_gate=({FormatByKind(_unresolvedByGate)}) gate_bound_by_gate=({FormatByKind(_gateBoundByGate)}) " + $"unresolved_wait_ms_by_gate=({FormatByKind(_unresolvedWaitTicksByGate, ticks => Milliseconds(ticks).ToString("F1", culture))}) " + - $"draw_gate_raises=({FormatByKind(_drawGateRaises)}) resolver_jobs={Interlocked.Exchange(ref _resolverJobs, 0)} " + + $"draw_gate_raises=({FormatByKind(_drawGateRaises)}) {TakeDrawLookaheadReport()} resolver_jobs={Interlocked.Exchange(ref _resolverJobs, 0)} " + $"resolver_idle_ms={Milliseconds(Interlocked.Exchange(ref _idleTicks, 0)).ToString("F1", culture)} " + $"gate_sleep_ms={Milliseconds(Interlocked.Exchange(ref _gateTicks, 0)).ToString("F1", culture)} idle_wakes={Interlocked.Exchange(ref _idleWakes, 0)} " + $"idle_spin_takes={Interlocked.Exchange(ref _idleSpinTakes, 0)} " + @@ -844,6 +974,8 @@ private void Resolve(Job job) private void ResolveCore(Job job) { + // Read before the host's state: the items counted had run before anything the resolution reads. + job.ExecutedAtStart = Volatile.Read(ref _executedGate); _concurrent.BeginConcurrentResolve(); _resolvingJob = job.Index + 1; try diff --git a/src/SharpEmu.Libs/Gpu/Rendering/RenderExecutor.Prefetch.cs b/src/SharpEmu.Libs/Gpu/Rendering/RenderExecutor.Prefetch.cs index f27debd79..5c8f00874 100644 --- a/src/SharpEmu.Libs/Gpu/Rendering/RenderExecutor.Prefetch.cs +++ b/src/SharpEmu.Libs/Gpu/Rendering/RenderExecutor.Prefetch.cs @@ -96,6 +96,10 @@ public interface IConcurrentResolveHost bool PrefetchedDispatchesCrossDispatches => false; + // A draw's resolution may start before the dispatches just before it ran (ParallelProgramPrefetch.SubmitDrawAhead), + // its take checked with IsStillCurrentAcrossDispatches; only a host whose check covers what those dispatches write. + bool PrefetchedDrawsCrossDispatches => false; + // On the render thread, for a dispatch's resolution that may have read guest memory before the dispatches ahead of // it ran: the answers hold, and none of the GPU writes those dispatches recorded covers what it read. bool IsStillCurrentAcrossDispatches(object assumptions) => IsStillCurrent(assumptions); diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.ConcurrentResolve.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.ConcurrentResolve.cs index 449f4f727..303d3d2dc 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.ConcurrentResolve.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.ConcurrentResolve.cs @@ -57,6 +57,10 @@ internal sealed partial class MetalRenderHost : IConcurrentResolveHost bool IConcurrentResolveHost.PrefetchedDispatchesCrossDispatches => DispatchPrefetchCrossesDispatches; + // The take of a draw resolved ahead of dispatches (ParallelProgramPrefetch.SubmitDrawAhead) checks the GPU write log + // and the copies read through as a dispatch's does (IsConcurrentResolveStillCurrentAcrossDispatches). + bool IConcurrentResolveHost.PrefetchedDrawsCrossDispatches => true; + bool IConcurrentResolveHost.IsStillCurrentAcrossDispatches(object assumptions) => IsConcurrentResolveStillCurrentAcrossDispatches(assumptions); private long _writeLogRefusals; @@ -382,6 +386,22 @@ internal sealed class ConcurrentAssumptions( // The GPU write log's count when the resolution began reading (MetalGpuWriteRanges.LoggedWriteSince). public ulong WriteLogVersion; + // The destinations read as the source of the pending copy that writes them, whose owned answers were dropped + // (TryReadThroughPendingCopyConcurrent, FillCopyLine): merged with the last range when they touch it. + public readonly List<(ulong Start, ulong End)> CopiedThrough = new(); + + public void NoteCopiedThrough(ulong address, ulong size) + { + var end = address + size; + if (CopiedThrough.Count != 0 && CopiedThrough[^1] is var (lastStart, lastEnd) && address <= lastEnd && lastStart <= end) + { + CopiedThrough[^1] = (Math.Min(lastStart, address), Math.Max(lastEnd, end)); + return; + } + + CopiedThrough.Add((address, end)); + } + // The last pages found unowned, for each kind of read. private readonly ulong[] _cleanPages = [ulong.MaxValue, ulong.MaxValue, ulong.MaxValue, ulong.MaxValue, ulong.MaxValue, ulong.MaxValue, ulong.MaxValue, ulong.MaxValue]; @@ -418,6 +438,7 @@ internal sealed class ConcurrentAssumptions( public void Reset((long Overlay, long Labels, ulong GpuWrites, long Images, long GpuModified) versions) { Answers.Clear(); + CopiedThrough.Clear(); Versions = versions; Array.Fill(_cleanPages, ulong.MaxValue); _nextCleanPage = 0; @@ -697,9 +718,11 @@ internal bool IsConcurrentResolveStillCurrent(object assumptionsObject) [ThreadStatic] private static MetalRenderHost? t_recheckHost; - // On the worker, for a dispatch's resolution that may have read guest memory before the dispatches ahead of it ran: - // as IsConcurrentResolveStillCurrent, and no GPU write logged since it began covers a range it read. A write those - // dispatches recorded may have landed and retired by now, which the ownership answers alone no longer show. + // On the worker, for a resolution (a dispatch's or a draw's) that may have read guest memory before the dispatches + // ahead of it ran: as IsConcurrentResolveStillCurrent, and no GPU write logged since it began covers a range it read, + // nor a destination it read through a pending copy. A write those dispatches recorded may have landed and retired by + // now, which the ownership answers alone no longer show; and one over a copied destination, whose owned answer the + // copy read dropped, makes it the destination's latest write instead of the copy. internal bool IsConcurrentResolveStillCurrentAcrossDispatches(object assumptionsObject) { var assumptions = (ConcurrentAssumptions)assumptionsObject; @@ -713,6 +736,15 @@ internal bool IsConcurrentResolveStillCurrentAcrossDispatches(object assumptions return false; } } + + foreach (var (start, end) in assumptions.CopiedThrough) + { + if (_gpuWrites.LoggedWriteSince(assumptions.WriteLogVersion, start, end - start)) + { + Interlocked.Increment(ref _writeLogRefusals); + return false; + } + } } return IsConcurrentResolveStillCurrent(assumptionsObject); diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.CopyReads.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.CopyReads.cs index fc1afbdb6..78321e284 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.CopyReads.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.CopyReads.cs @@ -351,6 +351,9 @@ private bool TryReadCopySourceConcurrent(PendingCopy copy, ulong address, Span this; + public bool IsStillCurrent(object assumptions) + { + Interlocked.Increment(ref Checks); + return Current; + } + + public bool IsStillCurrentAcrossDispatches(object assumptions) + { + Interlocked.Increment(ref CrossChecks); + return CurrentAcrossDispatches && IsStillCurrent(assumptions); + } + } + + // A draw job resolved once the gated items run so far (at least `gate` of them) ran, with `fullGate` items ahead of its draw. + private ParallelProgramPrefetch.Job Resolved(RegisterBanks banks, long gate, long fullGate) + { + var job = _prefetch.SubmitDrawAhead(banks, gate, fullGate); + _prefetch.WaitIdle(); + Assert.Equal(1, job.State); + return job; + } + + private bool Take(RegisterBanks banks, ParallelProgramPrefetch.Job job) + { + _prefetch.Current = job; + var inputs = RenderExecutor.ProgramInputsOf(banks, _host.FormatSupport, _host.Fatal); + return _prefetch.TryTakeGraphics(banks, in inputs, out _); + } + + private (long Jobs, long Taken, long[] Refused, long Verified) Counters() => _prefetch.TakeDrawLookaheadCounters(); + + [Fact] + public void ADrawResolvedAheadOfADispatchThatChangedNothingIsTaken() + { + var banks = Banks().Snapshot(); + var job = Resolved(banks, gate: 0, fullGate: 1); + Assert.Equal(0, job.ExecutedAtStart); + // The dispatch runs, encoding GPU work only. + _prefetch.AdvanceGate(1); + Assert.True(Take(banks, job)); + Assert.Equal(1, _concurrent.CrossChecks); + var counters = Counters(); + Assert.Equal((1L, 1L), (counters.Jobs, counters.Taken)); + Assert.All(counters.Refused, count => Assert.Equal(0, count)); + } + + // Resolved once the dispatches had run, the job looked ahead of nothing: its take is a draw's as before. + [Fact] + public void AJobResolvedAfterTheDispatchesRanIsCheckedAsBefore() + { + var banks = Banks().Snapshot(); + _prefetch.AdvanceGate(2); + var job = Resolved(banks, gate: 1, fullGate: 2); + _concurrent.CurrentAcrossDispatches = false; + Assert.True(Take(banks, job)); + Assert.Equal((0, 1), (_concurrent.CrossChecks, _concurrent.Checks)); + Assert.Equal(0, Counters().Jobs); + } + + [Fact] + public void ADrawWhoseAnswersChangedAcrossTheDispatchesIsRefused() + { + var banks = Banks().Snapshot(); + var job = Resolved(banks, gate: 0, fullGate: 1); + _prefetch.AdvanceGate(1); + _concurrent.CurrentAcrossDispatches = false; + Assert.False(Take(banks, job)); + Assert.Equal(1, Counters().Refused[(int)ParallelProgramPrefetch.DrawLookaheadRefusal.Ownership]); + Assert.Equal(1, _prefetch.TakeCounters().Refused); + } + + [Fact] + public void ADispatchThatDidMoreThanEncodeRefusesTheDrawsResolvedAheadOfItOnly() + { + var banks = Banks().Snapshot(); + // Three dispatches before the draws. `ahead` resolved before any ran; the first is consumed by a host fill. + var ahead = Resolved(banks, gate: 0, fullGate: 3); + _prefetch.NoteDispatchEffect(); + _prefetch.AdvanceGate(1); + // `behind` resolved after the first ran, ahead of the other two, which only encode. + var behind = Resolved(banks, gate: 1, fullGate: 3); + Assert.Equal(1, behind.ExecutedAtStart); + _prefetch.AdvanceGate(3); + Assert.False(Take(banks, ahead)); + Assert.True(Take(banks, behind)); + var counters = Counters(); + Assert.Equal((2L, 1L), (counters.Jobs, counters.Taken)); + Assert.Equal(1, counters.Refused[(int)ParallelProgramPrefetch.DrawLookaheadRefusal.Effects]); + } + + [Fact] + public void AnEffectOfTheLastDispatchAheadRefusesEveryDrawResolvedBeforeIt() + { + var banks = Banks().Snapshot(); + var first = Resolved(banks, gate: 0, fullGate: 2); + _prefetch.AdvanceGate(1); + var second = Resolved(banks, gate: 1, fullGate: 2); + // The second dispatch (gated item 2) copies an image. + _prefetch.NoteDispatchEffect(); + _prefetch.AdvanceGate(2); + Assert.False(Take(banks, first)); + Assert.False(Take(banks, second)); + Assert.Equal(2, Counters().Refused[(int)ParallelProgramPrefetch.DrawLookaheadRefusal.Effects]); + } + + [Fact] + public void OtherInputsAreRefused() + { + var banks = Banks().Snapshot(); + var job = Resolved(banks, gate: 0, fullGate: 1); + _prefetch.AdvanceGate(1); + _prefetch.Current = job; + var inputs = RenderExecutor.ProgramInputsOf(banks, _host.FormatSupport, _host.Fatal, indexed: true); + Assert.False(_prefetch.TryTakeGraphics(banks, in inputs, out _)); + Assert.Equal(1, Counters().Refused[(int)ParallelProgramPrefetch.DrawLookaheadRefusal.Inputs]); + } + + // =verify: the worker resolves an accepted look-ahead again, and a resolution that does not match is fatal. + [Fact] + public void VerifyResolvesAnAcceptedLookaheadAgainAndFailsOnADifference() + { + _prefetch.LookaheadMode = ParallelProgramPrefetch.DrawLookaheadMode.Verify; + var banks = Banks().Snapshot(); + var job = Resolved(banks, gate: 0, fullGate: 1); + _prefetch.AdvanceGate(1); + Assert.True(Take(banks, job)); + Assert.Equal(1, Counters().Verified); + + // The host wrongly stands for a resolution the dispatch changed: the provider now resolves other programs. + job = Resolved(banks, gate: 1, fullGate: 2); + _pipelines.Graphics = Programs(vertexBuffers: [new VertexInputBuffer(VertexBase, 16, 4)]); + _prefetch.AdvanceGate(2); + Assert.Throws(() => Take(banks, job)); + Assert.Equal(1, Counters().Verified); + } + + // A gated item other than a dispatch (here an interrupt) still holds the resolution of the draw after it, while the + // dispatch between them does not. + [Fact] + public void AnInterruptBeforeTheDispatchStillHoldsTheDraw() + { + var host = new RecordingCommandStreamHost(); + var queue = new CommandStreamQueue(host); + var producer = new DeferredCommandThread(queue, host.Memory, _ => { }, _prefetch, () => { }, false); + ParallelProgramPrefetch.Job? job = null; + var stateWhenTheInterruptRan = -1; + var done = 0; + Assert.True(queue.TryEnqueueControlBarrier(() => + { + producer.Post(() => stateWhenTheInterruptRan = job!.State, ParallelProgramPrefetch.GateItemKind.Event); + producer.EnqueueDeferredDispatch(new Work(), hasJob: false); + job = _prefetch.SubmitDrawAhead(Banks().Snapshot(), producer.DispatchGate, producer.Gate); + producer.EnqueueDeferred(new Work(), isDraw: true); + producer.Post(() => Volatile.Write(ref done, 1)); + }, () => { })); + producer.Start(); + try + { + Assert.True(SpinWait.SpinUntil(() => + { + producer.RunBatch(long.MaxValue, 64, () => { }); + return Volatile.Read(ref done) == 1; + }, TimeSpan.FromSeconds(10))); + producer.ThrowIfFailed(); + } + finally + { + producer.Stop(() => producer.RunBatch(long.MaxValue, 64, () => { })); + } + + _prefetch.WaitIdle(); + Assert.Equal((1L, 2L), (job!.Gate, job.FullGate)); + Assert.Equal(0, stateWhenTheInterruptRan); + Assert.True(job.ExecutedAtStart >= 1); + } + + private sealed record Work : SharpEmu.Libs.Agc.AgcExports.DeferredWork; +} From 20b804a3e3792058ec12932a21bdaa0198d6049f Mon Sep 17 00:00:00 2001 From: kuba Date: Sun, 15 Nov 2026 16:25:56 +0000 Subject: [PATCH 081/178] [Shader] Back read proofs off for origins whose words change on every rebuild An origin chain whose revalidations find their words changed twice in a row (each followed by a rebuild) stops comparing and recording proofs for its next 16 revalidations, which evaluate in full as with proofs off; a revalidation that finds the snapshot current ends the back-off and the next one records again. Rebuilt snapshots carry the back-off on, and a backed-off rebuild attaches no proof. The read_proof counters gain backoff, backoffs and backed_off. SHARPEMU_RESOURCE_READ_PROOF_BACKOFF=0 compares and records on every revalidation, as before. The DS-shaped bench gains SHARPEMU_DS_DRAW_BENCH_CHURN_EVERY and _MESH_REPEAT to change every mesh's table. --- .../Resources/ResourceMaterializer.cs | 88 ++++++++++++-- .../Scenes/DsDrawCostBenchTests.cs | 10 +- .../Resources/ReadProofTests.cs | 114 ++++++++++++++++++ 3 files changed, 203 insertions(+), 9 deletions(-) diff --git a/src/SharpEmu.ShaderCompiler/Resources/ResourceMaterializer.cs b/src/SharpEmu.ShaderCompiler/Resources/ResourceMaterializer.cs index 6d33e307d..a10617266 100644 --- a/src/SharpEmu.ShaderCompiler/Resources/ResourceMaterializer.cs +++ b/src/SharpEmu.ShaderCompiler/Resources/ResourceMaterializer.cs @@ -388,6 +388,19 @@ public MaterializationProgram.ReadProof? Proof get => Volatile.Read(ref _proof); set => Volatile.Write(ref _proof, value); } + + // The read-proof back-off (ReadProofBackoff): revalidations in a row whose proof did not hold and whose words + // changed, and the revalidations left that neither compare nor record a proof. Plain fields: a lost update moves + // only the heuristic, never an answer, since a backed-off revalidation evaluates in full. + public int ProofChanges; + public int ProofSkips; + + // A snapshot rebuilt from this origin's revalidation stands for the same draw: its origin carries the back-off on. + public void CarryBackoffTo(FastOrigin rebuilt) + { + rebuilt.ProofChanges = ProofChanges; + rebuilt.ProofSkips = ProofSkips; + } } // SHARPEMU_RESOURCE_READ_PROOF: on (default), 0 (every revalidation evaluates the program word by word, as before), @@ -417,6 +430,19 @@ internal enum ReadProofMode internal static ReadProofMode ReadProofs { get; set; } = ParseReadProofMode(Environment.GetEnvironmentVariable("SHARPEMU_RESOURCE_READ_PROOF")); + // An origin whose words keep changing pays for its proof without ever using it: the compare that fails, then a full + // evaluation that records a new proof, and on a rebuild the check that the new snapshot matches it. Demon's Souls: + // ~3.0k of ~18k revalidations a frame changed, and read proofs saved nothing in game. After BackoffAfterChanges + // changed revalidations in a row, the origin (and the snapshots rebuilt from it) skips proofs for the next + // BackoffRevalidations revalidations, which evaluate in full as with proofs off; a revalidation that finds the + // snapshot current ends the back-off at once, and the next one records a proof again. + // SHARPEMU_RESOURCE_READ_PROOF_BACKOFF=0 compares and records on every revalidation, as before. + internal static bool ReadProofBackoff { get; set; } = + Environment.GetEnvironmentVariable("SHARPEMU_RESOURCE_READ_PROOF_BACKOFF") != "0"; + + internal const int BackoffAfterChanges = 2; + internal const int BackoffRevalidations = 16; + // A verify-mode proof whose replay differs from the full evaluation (the full one compared its words again first). public sealed class ReadProofMismatchException(string message) : InvalidOperationException(message); @@ -431,6 +457,8 @@ public sealed class ReadProofMismatchException(string message) : InvalidOperatio private static readonly ThreadCounter _proofUnmatched = new(); private static readonly ThreadCounter _proofVerified = new(); private static readonly ThreadCounter _proofVerifyRaced = new(); + private static readonly ThreadCounter _proofBackoffs = new(); + private static readonly ThreadCounter _proofBackedOff = new(); private static long _proofVerifyFailed; // The read_proof=(...) part of the prefetch counters: revalidations proved current (hits); revalidations evaluated in @@ -438,12 +466,14 @@ public sealed class ReadProofMismatchException(string message) : InvalidOperatio // through the host (normalized), or because the proof did not hold and the words then evaluated to the snapshot // (refused: owned or unreadable words, or changes the output does not show) or not (changed); proofs recorded, // refused (torn: one address read as two values) and not kept (unmatched: a snapshot that differs from the words - // its evaluation emitted); verify counts. + // its evaluation emitted); verify counts; origins that entered the back-off (backoffs) and revalidations that skipped + // their proof in it (backed_off). public static string TakeReadProofReport() => FormattableString.Invariant( $"read_proof=(mode={ReadProofs.ToString().ToLowerInvariant()},hits={_proofHits.Take()},none={_proofNone.Take()},") + FormattableString.Invariant($"no_comparer={_proofNoComparer.Take()},normalized={_proofNormalized.Take()},refused={_proofRefusedCurrent.Take()},changed={_proofChanged.Take()},") + FormattableString.Invariant($"recorded={_proofRecorded.Take()},torn={_proofTorn.Take()},unmatched={_proofUnmatched.Take()},verified={_proofVerified.Take()},") + - FormattableString.Invariant($"verify_raced={_proofVerifyRaced.Take()},verify_failed={Interlocked.Read(ref _proofVerifyFailed)})"); + FormattableString.Invariant($"verify_raced={_proofVerifyRaced.Take()},verify_failed={Interlocked.Read(ref _proofVerifyFailed)},") + + FormattableString.Invariant($"backoff={(ReadProofBackoff ? "on" : "off")},backoffs={_proofBackoffs.Take()},backed_off={_proofBackedOff.Take()})"); // The proof a fast snapshot's origin holds (tests). internal static MaterializationProgram.ReadProof? ReadProofOf(ResourceSnapshot snapshot) => (snapshot.Origin as FastOrigin)?.Proof; @@ -525,7 +555,7 @@ public static FastRevalidation RevalidateOrRebuildFast(ResourceSnapshot snapshot } var same = SameAsOutput(plan, snapshot, output); - NoteRevalidation(origin, proof, path, same); + NoteRevalidation(origin, proof, path, same, rebuilds: true); if (same) { return FastRevalidation.Current; @@ -556,7 +586,16 @@ public static FastRevalidation RevalidateOrRebuildFast(ResourceSnapshot snapshot } // The rebuilt snapshot's origin has this origin's draw values and readers: the reads just made are its own. - AttachProof(plan, next, output, proof); + // A rebuilt origin that carries a back-off on would not use the proof: it is not checked against the snapshot. + if (next.Origin is FastOrigin rebuiltOrigin) + { + origin.CarryBackoffTo(rebuiltOrigin); + } + + if (next.Origin is not FastOrigin { ProofSkips: > 0 }) + { + AttachProof(plan, next, output, proof); + } rebuilt = next; return FastRevalidation.Rebuilt; @@ -622,7 +661,7 @@ public static FastRevalidation RevalidateOrRebuildFast(ResourceSnapshot snapshot } var same = SameAsOutput(plan, snapshot, output); - NoteRevalidation(origin, proof, path, same); + NoteRevalidation(origin, proof, path, same, rebuilds: false); return same; } finally @@ -651,6 +690,8 @@ private enum ProofPath Proved, // A word compared unequal or owned, an unreadable word read, or the active sources differ: evaluated in full. Refused, + // The origin's words kept changing (ReadProofBackoff): evaluated in full, nothing compared or recorded. + BackedOff, } // Whether the origin's proof shows its snapshot current without evaluating its program (ReadProofMode). The proof is @@ -680,6 +721,13 @@ private static ProofPath TryProve(ShaderResourcePlan plan, ResourceSnapshot snap return ProofPath.NoComparer; } + if (ReadProofBackoff && origin.ProofSkips > 0) + { + origin.ProofSkips--; + _proofBackedOff.Increment(); + return ProofPath.BackedOff; + } + if (origin.Proof is not { } proof) { return ProofPath.None; @@ -691,6 +739,12 @@ private static ProofPath TryProve(ShaderResourcePlan plan, ResourceSnapshot snap } _proofHits.Increment(); + // Proved: the changes before it were not in a row. + if (origin.ProofChanges != 0) + { + origin.ProofChanges = 0; + } + if (mode == ReadProofMode.Verify) { VerifyProof(plan, snapshot, proof, inputs, output); @@ -722,8 +776,10 @@ private static bool Holds(ShaderResourcePlan plan, MaterializationProgram.ReadPr } // After a full revalidation: counted by why it was not proved, and its proof kept on the origin when its words were - // the snapshot's (a rebuild hands it to the rebuilt snapshot's origin instead, AttachProof). - private static void NoteRevalidation(FastOrigin origin, MaterializationProgram.ReadProof? proof, ProofPath path, bool same) + // the snapshot's (a rebuild hands it to the rebuilt snapshot's origin instead, AttachProof). A change found where a + // rebuild follows (rebuilds) counts toward the back-off: each is a new generation of the snapshot's words, where a + // snapshot only revalidated stays stale and may be asked again about the same change. + private static void NoteRevalidation(FastOrigin origin, MaterializationProgram.ReadProof? proof, ProofPath path, bool same, bool rebuilds) { switch (path) { @@ -738,13 +794,31 @@ private static void NoteRevalidation(FastOrigin origin, MaterializationProgram.R case ProofPath.Normalized: _proofNormalized.Increment(); break; + case ProofPath.BackedOff: + // Current again: the next revalidation records a proof. + if (same) + { + origin.ProofSkips = 0; + origin.ProofChanges = 0; + } + + return; default: (same ? _proofRefusedCurrent : _proofChanged).Increment(); + if (!same && rebuilds && ReadProofBackoff && ++origin.ProofChanges >= BackoffAfterChanges) + { + origin.ProofChanges = 0; + origin.ProofSkips = BackoffRevalidations; + origin.Proof = null; + _proofBackoffs.Increment(); + } + break; } if (same) { + origin.ProofChanges = 0; origin.Proof = proof; } } diff --git a/tests/SharpEmu.Gpu.Metal.Tests/Scenes/DsDrawCostBenchTests.cs b/tests/SharpEmu.Gpu.Metal.Tests/Scenes/DsDrawCostBenchTests.cs index 96f974fc1..5b4d28a36 100644 --- a/tests/SharpEmu.Gpu.Metal.Tests/Scenes/DsDrawCostBenchTests.cs +++ b/tests/SharpEmu.Gpu.Metal.Tests/Scenes/DsDrawCostBenchTests.cs @@ -524,6 +524,12 @@ ulong DispatchTable(int dispatch, ulong writeBuffer) // streams as well, as Demon's Souls runs its ~1000 dispatches a frame between draws: each holds the program // resolution of the draw after it (its gate), unless that draw's job looks ahead of dispatches // (SHARPEMU_PREFETCH_DRAW_LOOKAHEAD). 0 (the default) leaves the streams as they were. + // SHARPEMU_DS_DRAW_BENCH_CHURN_EVERY=n: GameWords changes the table of every nth mesh between rounds (3 by default); + // 1 changes them all, so nearly every revalidation of a kept stage finds its words changed. + var churnEvery = Setting("CHURN_EVERY", 3); + // SHARPEMU_DS_DRAW_BENCH_MESH_REPEAT=n: each game mesh is drawn in n draws in a row (2 by default). With 1, _MESHES + // at _GAME_DRAWS and _CHURN_EVERY=1, every draw has a mesh of its own whose table changes every round. + var meshRepeat = Setting("MESH_REPEAT", 2); var dispatchEvery = int.TryParse(Environment.GetEnvironmentVariable("SHARPEMU_DS_DRAW_BENCH_DISPATCH_EVERY"), out var every) && every > 0 ? every : 0; ulong copyDestination = 0, copySource = 0, copyWords = 0; void ArmCopiedTables() @@ -577,7 +583,7 @@ void ArmCopiedTables() var passLength = (gameDrawCount + Passes - 1) / Passes; var labelWrites = 0; var wordChurn = churnWords - ? gameMeshes.Where((_, index) => index % 3 == 0).Select(mesh => + ? gameMeshes.Where((_, index) => index % churnEvery == 0).Select(mesh => (mesh.table + 0x40, rig.Read(mesh.table + 0x40, 4), Descriptors.Buffer(alternateConstants, 16, 2))).ToArray() : []; var keyChurn = new List<(int Stream, int Word)>(); @@ -614,7 +620,7 @@ void ArmCopiedTables() var firstOfSubmission = (int)((long)draw * GameSubmissions / gameDrawCount) != (int)((long)(draw - 1) * GameSubmissions / gameDrawCount) || draw == 0; var mesh = draw % 16 == 15 ? dynamicMeshes[draw / 16 % dynamicMeshes.Length] - : gameMeshes[(int)((ulong)(draw / 2) * 7919UL % (ulong)gameMeshCount)]; + : gameMeshes[(int)((ulong)(draw / meshRepeat) * 7919UL % (ulong)gameMeshCount)]; var material = firstOfSubmission ? churnMaterials[submission % ChurnTextures] : materials[(draw * 11 + pass * 3) % Materials]; diff --git a/tests/SharpEmu.ShaderCompiler.Tests/Resources/ReadProofTests.cs b/tests/SharpEmu.ShaderCompiler.Tests/Resources/ReadProofTests.cs index 9daea0b37..9602a9607 100644 --- a/tests/SharpEmu.ShaderCompiler.Tests/Resources/ReadProofTests.cs +++ b/tests/SharpEmu.ShaderCompiler.Tests/Resources/ReadProofTests.cs @@ -303,4 +303,118 @@ public void ProofRangesStayInsideLinesAndATornReadIsRefused() scratch.NoteRead(0x2000, 2); Assert.Null(MaterializationProgram.ReadProof.Build(program, scratch, [])); } + + private static T WithBackoff(bool backoff, Func body) + { + var previous = ResourceMaterializer.ReadProofBackoff; + ResourceMaterializer.ReadProofBackoff = backoff; + try + { + return WithMode(ResourceMaterializer.ReadProofMode.On, body); + } + finally + { + ResourceMaterializer.ReadProofBackoff = previous; + } + } + + // A rebuild of the snapshot after the V#'s record count changed to `records`: the rebuilt snapshot. + private static ResourceSnapshot RebuildAfterChange(TestWordMemory memory, ResourceSnapshot snapshot, uint records) + { + memory.Words[2] = records; + Assert.Equal(ResourceMaterializer.FastRevalidation.Rebuilt, ResourceMaterializer.RevalidateOrRebuildFast(snapshot, out var rebuilt)); + return rebuilt!; + } + + // Words that change on every rebuild back the origin's chain off proofs: after two changes in a row its revalidations + // neither compare nor record one, and still answer as a full evaluation does; one that finds the snapshot current + // ends the back-off, and the next records a proof that proves the one after. + [Fact] + public void AnOriginWhoseWordsChangeEveryRebuildBacksOffUntilItIsCurrentAgain() + { + WithBackoff(true, () => + { + var (plan, memory, comparer, inputs) = Setup(); + var snapshot = Materialize(plan, inputs); + _ = ResourceMaterializer.TakeReadProofReport(); + snapshot = RebuildAfterChange(memory, snapshot, 128); + Assert.NotNull(ResourceMaterializer.ReadProofOf(snapshot)); + snapshot = RebuildAfterChange(memory, snapshot, 256); + // Backed off: the rebuilt snapshot holds no proof. + Assert.Null(ResourceMaterializer.ReadProofOf(snapshot)); + var report = ResourceMaterializer.TakeReadProofReport(); + Assert.Equal((2L, 1L), (Counter(report, "changed"), Counter(report, "backoffs"))); + + var calls = comparer.Calls; + snapshot = RebuildAfterChange(memory, snapshot, 64); + Assert.Null(ResourceMaterializer.ReadProofOf(snapshot)); + Assert.Equal(ResourceMaterializer.FastRevalidation.Current, ResourceMaterializer.RevalidateOrRebuildFast(snapshot, out _)); + Assert.Equal(calls, comparer.Calls); + report = ResourceMaterializer.TakeReadProofReport(); + Assert.Equal((2L, 0L, 0L), (Counter(report, "backed_off"), Counter(report, "changed"), Counter(report, "recorded"))); + + // Re-armed: recorded again, then proved without reading a word. + Assert.Equal(ResourceMaterializer.FastRevalidation.Current, ResourceMaterializer.RevalidateOrRebuildFast(snapshot, out _)); + Assert.NotNull(ResourceMaterializer.ReadProofOf(snapshot)); + var reads = memory.Reads; + Assert.True(ResourceMaterializer.RevalidateFast(snapshot)); + Assert.Equal(reads, memory.Reads); + report = ResourceMaterializer.TakeReadProofReport(); + Assert.Equal((1L, 1L, 0L), (Counter(report, "none"), Counter(report, "hits"), Counter(report, "backed_off"))); + return 0; + }); + } + + // The back-off lasts BackoffRevalidations revalidations whatever the words do, then compares and records again. + [Fact] + public void TheBackoffEndsAfterItsRevalidations() + { + WithBackoff(true, () => + { + var (plan, memory, _, inputs) = Setup(); + var snapshot = Materialize(plan, inputs); + snapshot = RebuildAfterChange(memory, snapshot, 128); + snapshot = RebuildAfterChange(memory, snapshot, 256); + _ = ResourceMaterializer.TakeReadProofReport(); + for (var change = 0; change < ResourceMaterializer.BackoffRevalidations; change++) + { + snapshot = RebuildAfterChange(memory, snapshot, (uint)(change % 2 == 0 ? 64 : 32)); + } + + var report = ResourceMaterializer.TakeReadProofReport(); + Assert.Equal((ResourceMaterializer.BackoffRevalidations, 0L), (Counter(report, "backed_off"), Counter(report, "changed"))); + snapshot = RebuildAfterChange(memory, snapshot, 16); + report = ResourceMaterializer.TakeReadProofReport(); + Assert.Equal((0L, 1L), (Counter(report, "backed_off"), Counter(report, "none"))); + Assert.NotNull(ResourceMaterializer.ReadProofOf(snapshot)); + return 0; + }); + } + + // A change, a proved revalidation, a change: not in a row, so no back-off. With the switch off, none ever. + [Theory] + [InlineData(true, true)] + [InlineData(false, false)] + public void OnlyChangesInARowBackOffAndOnlyWithTheSwitchOn(bool backoff, bool provedBetween) + { + WithBackoff(backoff, () => + { + var (plan, memory, _, inputs) = Setup(); + var snapshot = Materialize(plan, inputs); + _ = ResourceMaterializer.TakeReadProofReport(); + for (var change = 0; change < 4; change++) + { + snapshot = RebuildAfterChange(memory, snapshot, (uint)(change % 2 == 0 ? 128 : 256)); + if (provedBetween) + { + Assert.True(ResourceMaterializer.RevalidateFast(snapshot)); + } + } + + var report = ResourceMaterializer.TakeReadProofReport(); + Assert.Equal((4L, 0L, 0L), (Counter(report, "changed"), Counter(report, "backoffs"), Counter(report, "backed_off"))); + Assert.NotNull(ResourceMaterializer.ReadProofOf(snapshot)); + return 0; + }); + } } From b0be9fb4eca5eef4e36da502ab9ffe12cb3cc062 Mon Sep 17 00:00:00 2001 From: kuba Date: Sun, 15 Nov 2026 16:31:38 +0000 Subject: [PATCH 082/178] [Tests] Allow the read-proof back-off counters in a cached draw's allocation bound Each fast snapshot's origin carries two ints for the back-off: a cached draw now allocates 600 bytes (1040 with a pixel stage) instead of 592 (1024). --- .../Gpu/Pipelines/ShaderPipelineCacheAllocationTests.cs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/ShaderPipelineCacheAllocationTests.cs b/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/ShaderPipelineCacheAllocationTests.cs index 5eef573d5..e062d3f30 100644 --- a/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/ShaderPipelineCacheAllocationTests.cs +++ b/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/ShaderPipelineCacheAllocationTests.cs @@ -53,8 +53,9 @@ long Draw() // packet slot on each stage's resource snapshot (ResourceSnapshot.BindingPacket) to 528 and 896, and the draw's own // user data, shader base and compute state on each fast snapshot's origin (ResourceMaterializer.FastOrigin) to 576 and 992, // and the specialization that origin keeps (whether a resolve memo rebuild keeps the program) to 584 and 1008, and the - // read proof comparer on each stage's runtime inputs (ResourceRuntimeInputs.CompareGuestWords) to 592 and 1024. - Assert.True(perDraw[^1] <= (pixelActive ? 1024 : 592), $"bytes={perDraw[^1]}"); + // read proof comparer on each stage's runtime inputs (ResourceRuntimeInputs.CompareGuestWords) to 592 and 1024, and the + // read-proof back-off counters on each fast snapshot's origin (FastOrigin.ProofChanges, ProofSkips) to 600 and 1040. + Assert.True(perDraw[^1] <= (pixelActive ? 1040 : 600), $"bytes={perDraw[^1]}"); var first = cache.GetGraphicsPrograms(banks.Shader.Vertex, banks.Shader.Pixel, banks.Context.ShaderInterface, banks.Context, mappings, pixelActive, depthBound: false, depthAspectBound: false); var second = cache.GetGraphicsPrograms(banks.Shader.Vertex, banks.Shader.Pixel, banks.Context.ShaderInterface, From 39ccccd97815259287d9528dea122726384b8f8a Mon Sep 17 00:00:00 2001 From: kuba Date: Sun, 15 Nov 2026 16:55:12 +0000 Subject: [PATCH 083/178] [Metal] Make the dry-GPU commit opt-in and give the overlay's phase capture a time floor The dry-GPU commit measured neutral in Demon's Souls (82.2 ms a frame on, 82.1 off, same build and scene) for 17 more render passes a frame, so SHARPEMU_METAL_V2_COMMIT_WHEN_GPU_DRY=1 now turns it on. The overlay's sampled phase capture also waits a second since the last captured frame (SHARPEMU_OVERLAY_PHASE_MIN_MS): at 12 fps one frame in four was drawn about 5 ms slower. --- .../VideoOut/RenderPhaseProfile.cs | 12 +++- .../V2/MetalV2Diagnostics.cs | 10 ++- .../VideoOut/Overlay/OverlayTelemetryTests.cs | 67 +++++++++++++++---- 3 files changed, 73 insertions(+), 16 deletions(-) diff --git a/src/SharpEmu.Libs/VideoOut/RenderPhaseProfile.cs b/src/SharpEmu.Libs/VideoOut/RenderPhaseProfile.cs index fb7c59bf6..8551c5407 100644 --- a/src/SharpEmu.Libs/VideoOut/RenderPhaseProfile.cs +++ b/src/SharpEmu.Libs/VideoOut/RenderPhaseProfile.cs @@ -301,6 +301,15 @@ internal static void SetOverlayCapture(bool phases, bool timeline) ? Math.Clamp(sample, 1, 64) : 4; + // A captured frame also has to be this long after the last one began. At a low frame rate one frame in four is + // still several a second, and each costs the render thread: Demon's Souls at 12 fps drew every fourth frame about + // 5 ms slower (80 against 85 ms), a visible beat in the frame pacing for a breakdown nobody reads that often. + // SHARPEMU_OVERLAY_PHASE_MIN_MS=0 samples by frame count alone. + internal static long OverlayPhaseMinTicks { get; set; } = + (int.TryParse(Environment.GetEnvironmentVariable("SHARPEMU_OVERLAY_PHASE_MIN_MS"), out var minMs) + ? Math.Clamp(minMs, 0, 10_000) + : 1000) * Stopwatch.Frequency / 1000; + private static bool _overlayPhasesWanted; private static bool _overlayTimelineWanted; // Render thread: presented frames left before the next captured one. @@ -750,7 +759,8 @@ private static void RecordOverlayFrame() { Overlay.OverlayTelemetry.EndRenderFrame(now, null, null); _overlaySegments?.Clear(); - if (_overlayPhasesWanted && --_overlaySkip <= 0) + if (_overlayPhasesWanted && --_overlaySkip <= 0 && + now - Volatile.Read(ref _overlayCaptureStart) >= OverlayPhaseMinTicks) { // The next frame is captured from here. Array.Clear(_framePhaseTicks); diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalV2Diagnostics.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalV2Diagnostics.cs index d839ae1bc..7976506b0 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalV2Diagnostics.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalV2Diagnostics.cs @@ -422,8 +422,12 @@ internal static MetalHostKernelCopyMode ParseHostKernelCopy(string? text) public static readonly int HoldFlushBusyMaxMicroseconds = PositiveInt("SHARPEMU_METAL_V2_FLUSH_HOLD_BUSY_US", 16000); - // SHARPEMU_METAL_V2_COMMIT_WHEN_GPU_DRY=0 leaves the open buffer to the stream's own flushes - // and limits. On, a draw or dispatch about to prepare commits it once the GPU has finished + // SHARPEMU_METAL_V2_COMMIT_WHEN_GPU_DRY=1 (off by default) commits early for a starved GPU; off, the open buffer + // is left to the stream's own flushes and limits. Off because it bought nothing where it was measured: Demon's + // Souls, same build and scene, 82.2 ms a frame with it and 82.1 without, for 17 more render passes and 18 more + // commits a frame. The GPU does starve there (~17 ms a frame), but while the worker records passes that are cheap + // for the GPU and dear for the CPU; the frame ends when the passes recorded last have run, and those were never + // waiting. On, a draw or dispatch about to prepare commits it once the GPU has finished // everything committed and the buffer holds enough to be worth a split, ending an open render // pass if one is (MetalCommandStream.cs, GpuDryVerdict). The bars: at least // SHARPEMU_METAL_V2_GPU_DRY_MIN_COMMANDS draws and dispatches since the last commit, and at least @@ -432,7 +436,7 @@ internal static MetalHostKernelCopyMode ParseHostKernelCopy(string? text) // once more at SHARPEMU_METAL_V2_GPU_DRY_SPLIT_US_PER_MB microseconds per MB (Demon's Souls: a // 16 MB target loaded and stored in ~0.5 ms, so the 68 MB G-buffer set ~1.6 ms a split). public static readonly bool CommitWhenGpuDry = - !string.Equals(Environment.GetEnvironmentVariable("SHARPEMU_METAL_V2_COMMIT_WHEN_GPU_DRY"), "0", StringComparison.Ordinal); + string.Equals(Environment.GetEnvironmentVariable("SHARPEMU_METAL_V2_COMMIT_WHEN_GPU_DRY"), "1", StringComparison.Ordinal); public static readonly int GpuDryMinCommands = PositiveInt("SHARPEMU_METAL_V2_GPU_DRY_MIN_COMMANDS", 64); diff --git a/tests/SharpEmu.Libs.Tests/VideoOut/Overlay/OverlayTelemetryTests.cs b/tests/SharpEmu.Libs.Tests/VideoOut/Overlay/OverlayTelemetryTests.cs index 4f3dfcc1c..fa13387de 100644 --- a/tests/SharpEmu.Libs.Tests/VideoOut/Overlay/OverlayTelemetryTests.cs +++ b/tests/SharpEmu.Libs.Tests/VideoOut/Overlay/OverlayTelemetryTests.cs @@ -131,24 +131,67 @@ public void AnOverlaySnapshotDoesNotResumeAPausedCapture() return; } - OverlayTelemetry.DataSource.SetCaptureDemand(OverlayCaptureDemand.RenderPhases | OverlayCaptureDemand.Timeline); - Assert.True(RenderPhaseProfile.Measuring); - RenderPhaseProfile.RecordFrame(); - Assert.False(RenderPhaseProfile.Measuring); - for (var frame = 1; frame < RenderPhaseProfile.OverlayPhaseSample; frame++) + var floor = RenderPhaseProfile.OverlayPhaseMinTicks; + RenderPhaseProfile.OverlayPhaseMinTicks = 0; + try { - _ = OverlayTelemetry.DataSource.Capture(); OverlayTelemetry.DataSource.SetCaptureDemand(OverlayCaptureDemand.RenderPhases | OverlayCaptureDemand.Timeline); + Assert.True(RenderPhaseProfile.Measuring); + RenderPhaseProfile.RecordFrame(); Assert.False(RenderPhaseProfile.Measuring); + for (var frame = 1; frame < RenderPhaseProfile.OverlayPhaseSample; frame++) + { + _ = OverlayTelemetry.DataSource.Capture(); + OverlayTelemetry.DataSource.SetCaptureDemand(OverlayCaptureDemand.RenderPhases | OverlayCaptureDemand.Timeline); + Assert.False(RenderPhaseProfile.Measuring); + RenderPhaseProfile.RecordFrame(); + } + + // The sampled frame, and a changed demand still takes effect at once. + Assert.True(RenderPhaseProfile.Measuring); RenderPhaseProfile.RecordFrame(); + Assert.False(RenderPhaseProfile.Measuring); + OverlayTelemetry.DataSource.SetCaptureDemand(OverlayCaptureDemand.RenderPhases); + Assert.True(RenderPhaseProfile.Measuring); + } + finally + { + RenderPhaseProfile.OverlayPhaseMinTicks = floor; + } + } + + // A capture also waits out the time floor: frames past the sample count stay untimed until it has passed. + [Fact] + public void ACaptureWaitsForTheTimeFloorAfterTheLastOne() + { + if (RenderPhaseProfile.OverlayPhaseSample == 1 || RenderPhaseProfile.Enabled) + { + return; } - // The sampled frame, and a changed demand still takes effect at once. - Assert.True(RenderPhaseProfile.Measuring); - RenderPhaseProfile.RecordFrame(); - Assert.False(RenderPhaseProfile.Measuring); - OverlayTelemetry.DataSource.SetCaptureDemand(OverlayCaptureDemand.RenderPhases); - Assert.True(RenderPhaseProfile.Measuring); + var floor = RenderPhaseProfile.OverlayPhaseMinTicks; + RenderPhaseProfile.OverlayPhaseMinTicks = 3600 * Stopwatch.Frequency; + try + { + OverlayTelemetry.DataSource.SetCaptureDemand(OverlayCaptureDemand.RenderPhases | OverlayCaptureDemand.Timeline); + Assert.True(RenderPhaseProfile.Measuring); + RenderPhaseProfile.RecordFrame(); + for (var frame = 0; frame < RenderPhaseProfile.OverlayPhaseSample * 3; frame++) + { + Assert.False(RenderPhaseProfile.Measuring); + RenderPhaseProfile.RecordFrame(); + } + + Assert.False(RenderPhaseProfile.Measuring); + RenderPhaseProfile.OverlayPhaseMinTicks = 0; + RenderPhaseProfile.RecordFrame(); + Assert.True(RenderPhaseProfile.Measuring); + } + finally + { + RenderPhaseProfile.OverlayPhaseMinTicks = floor; + RenderPhaseProfile.SetOverlayCapture(false, false); + } } [Fact] From 425656f95308dd9df9bb4cf18a8eb03dec9944e8 Mon Sep 17 00:00:00 2001 From: kuba Date: Sun, 15 Nov 2026 17:18:42 +0000 Subject: [PATCH 084/178] [GPU] Let draw and dispatch jobs resolve ahead of the per-submission collector call The host's garbage-collector call after every completed submission (ICommandStreamHost.RunGarbageCollector) was a gated item: at every submission boundary the program resolver waited until the worker had run it, and the worker then ran right behind the resolver (Demon's Souls: unresolved_by_gate call=4554..6025 per 2 s, gate-bound 100..129). The call now queues as GateItemKind.Collect ("gc" in the gate counters) and, where draws look ahead of dispatches (ParallelProgramPrefetch.LooksAheadOfCollects), leaves the sink's DispatchGate where it is: the draws and dispatches after it resolve while it runs. On the worker it reports whether it did anything a resolution may have read (NoteCollect), and a resolution that began before such a call ran is refused (draw take: gc_effects; dispatch take: effects), as behind a dispatch's effect; otherwise the take's existing cross-dispatch check applies. What counts as an effect (MetalImageCache.Collect, MetalCommandStream.RunGarbageCollector): a deferred draw drained, any image released (ImageSetVersion moved: retirement, staleness, budget eviction, with their writebacks and single-copy restores), the GPU-modified epoch moved, or any single-copy tick work (unwatches, punches taken, chunks due for emptying, arming candidates). Not an effect: the collection tick and access clock, idle-clock samples, the budget evaluation and the expiry of recently dropped images (bookkeeping only the worker reads), pruning completed fenced writebacks (they only hold guest CPU stores; no resolution read or ownership test consults them) and disposing retired images (Metal objects of images already unregistered). SHARPEMU_PREFETCH_DRAW_LOOKAHEAD=0 gates behind the call again; =verify re-resolves accepted look-aheads over it too. SHARPEMU_PREFETCH_GC_LOOKAHEAD=0 gates behind the call alone. Counters on the prefetch PERF line: draw_lookahead=(mode,over_gc=on|off,...,refused=(...,gc_effects),...,gc=(jobs,taken,refused,calls,effects)). Bench (DsDrawCostBench GameShaped COPIED_TABLES DISPATCH_EVERY=9, new _BURST=1 queueing a round's submissions at once): gc-gated unresolved takes 947..977 -> 0 and resolver gate sleep 126..131 -> 0 ms per 20 rounds, 24.4..24.9k draws taken over a collector call per run (27..31 refused, ownership), 0 of 780 calls noted an effect; verify re-resolved 145,706 look-aheads (24,842 over a collector call) with no difference; checksum BE7D933F56D34425 unchanged; bench wall/CPU flat (6.55..6.65 / 4.69..4.76 us either way). --- .../Agc/AgcExports.CommandStream.cs | 5 +- .../Gpu/GpuCommands/DeferredCommandThread.cs | 5 +- .../Gpu/Rendering/ParallelProgramPrefetch.cs | 122 +++++++++++++--- .../V2/MetalCommandStream.cs | 10 +- .../V2/MetalImageCache.Tracking.cs | 26 +++- .../SharpEmu.Gpu.Metal/V2/MetalSingleCopy.cs | 49 +++++-- .../MetalImageBudgetTests.cs | 36 ++++- .../Scenes/DsDrawCostBenchTests.cs | 20 +++ .../ParallelProgramPrefetchComputeTests.cs | 19 +++ ...rallelProgramPrefetchDrawLookaheadTests.cs | 130 +++++++++++++++++- 10 files changed, 375 insertions(+), 47 deletions(-) diff --git a/src/SharpEmu.Libs/Agc/AgcExports.CommandStream.cs b/src/SharpEmu.Libs/Agc/AgcExports.CommandStream.cs index ed5c9c5d8..962766d3b 100644 --- a/src/SharpEmu.Libs/Agc/AgcExports.CommandStream.cs +++ b/src/SharpEmu.Libs/Agc/AgcExports.CommandStream.cs @@ -53,8 +53,9 @@ public interface IDeferredWorkSink long EnqueueDeferred(DeferredWork work, bool isDraw); - // The non-draw items handed over so far up to the last that is not a dispatch: a dispatch's program may - // resolve once they ran, while the dispatches after them still wait (ParallelProgramPrefetch.SubmitCompute). + // The non-draw items handed over so far up to the last that is not a dispatch (nor a collector call the + // resolutions look ahead of): a dispatch's program may resolve once they ran, while the dispatches after them + // still wait (ParallelProgramPrefetch.SubmitCompute, LooksAheadOfCollects). long DispatchGate => Gate; // A dispatch whose program a job submitted just before it resolves: the item waits for the jobs before that diff --git a/src/SharpEmu.Libs/Gpu/GpuCommands/DeferredCommandThread.cs b/src/SharpEmu.Libs/Gpu/GpuCommands/DeferredCommandThread.cs index f8032dc23..ada3eaf86 100644 --- a/src/SharpEmu.Libs/Gpu/GpuCommands/DeferredCommandThread.cs +++ b/src/SharpEmu.Libs/Gpu/GpuCommands/DeferredCommandThread.cs @@ -181,7 +181,8 @@ public void Start() public long Gate => _enqueuedNonDraw; - // _enqueuedNonDraw as of the last gated non-draw item that was not a dispatch (AgcExports.IDeferredWorkSink.DispatchGate). + // _enqueuedNonDraw as of the last gated non-draw item that was not a dispatch, nor a collector call the resolutions + // look ahead of (ParallelProgramPrefetch.LooksAheadOfCollects; AgcExports.IDeferredWorkSink.DispatchGate). private long _dispatchGate; public long DispatchGate => _dispatchGate; @@ -700,7 +701,7 @@ private void Enqueue(Item item) { item.JobsBefore = (_prefetch?.Submitted ?? 0) - (item.OwnsLastJob ? 1 : 0); _enqueuedNonDraw++; - if (!item.IsDispatch) + if (!item.IsDispatch && !(item.GateKind == ParallelProgramPrefetch.GateItemKind.Collect && _prefetch is { LooksAheadOfCollects: true })) { _dispatchGate = _enqueuedNonDraw; } diff --git a/src/SharpEmu.Libs/Gpu/Rendering/ParallelProgramPrefetch.cs b/src/SharpEmu.Libs/Gpu/Rendering/ParallelProgramPrefetch.cs index 6ca70df7a..b17c242ec 100644 --- a/src/SharpEmu.Libs/Gpu/Rendering/ParallelProgramPrefetch.cs +++ b/src/SharpEmu.Libs/Gpu/Rendering/ParallelProgramPrefetch.cs @@ -41,6 +41,9 @@ public sealed class Job(RegisterBanks banks, long gate, bool indexed = false, in // all FullGate items ran looked ahead of the ones that had not, and its take checks it against them. internal long FullGate; internal long ExecutedAtStart; + // The gate number of the last collector call (GateItemKind.Collect) queued before the job: above ExecutedAtStart, + // the resolution looked ahead of it (draw_lookahead over_gc). + internal long LastCollectGate; } /// @@ -48,9 +51,13 @@ public sealed class Job(RegisterBanks banks, long gate, bool indexed = false, in /// (SubmitCompute): its gate stops short of them, its program resolves while they run, and its take accepts the /// resolution only when none of those dispatches did more than encode GPU work (NoteDispatchEffect) and the /// host's ownership answers and GPU write log show nothing it read changed (IsStillCurrentAcrossDispatches); - /// otherwise the draw resolves its programs itself (draw_lookahead refused by reason). Only dispatches are looked - /// ahead of: every other gated item (an interrupt, a commit, an event with no label, a host call) still holds the - /// draws after it. SHARPEMU_PREFETCH_DRAW_LOOKAHEAD=0 holds draws behind dispatches again; =verify also resolves + /// otherwise the draw resolves its programs itself (draw_lookahead refused by reason). The host's collector call + /// after each completed submission (GateItemKind.Collect) is looked ahead of the same way (LooksAheadOfCollects): + /// it notes an effect when it did anything a resolution may have read (NoteCollect), and a resolution that began + /// before such a call ran is refused (gc_effects). Every other gated item (an interrupt, a commit, an event with + /// no label, another host call) still holds the draws after it. SHARPEMU_PREFETCH_DRAW_LOOKAHEAD=0 holds draws + /// behind dispatches and collector calls again (and dispatches behind collector calls), and + /// SHARPEMU_PREFETCH_GC_LOOKAHEAD=0 behind collector calls only; =verify also resolves /// every accepted look-ahead on the worker and fails on any difference in the programs or their bindings. /// public enum DrawLookaheadMode : byte @@ -73,7 +80,19 @@ public enum DrawLookaheadMode : byte // The mode this prefetch checks takes in (tests set Verify on one instance). internal DrawLookaheadMode LookaheadMode { get; set; } = DrawLookahead; - // Why a draw's take refused a resolution that looked ahead of dispatches; Count is accepted. + // The command thread queues a collector call (GateItemKind.Collect) without moving the dispatch gate: the draws and + // dispatches after it gate on the items before it, and their takes check NoteCollect. Only where draws look ahead + // (the mode, and a host whose cross-dispatch check covers it), so SHARPEMU_PREFETCH_DRAW_LOOKAHEAD=0 gates again; + // SHARPEMU_PREFETCH_GC_LOOKAHEAD=0 gates behind collector calls alone and keeps the look-ahead over dispatches. + private static readonly bool CollectLookaheadDefault = + Environment.GetEnvironmentVariable("SHARPEMU_PREFETCH_GC_LOOKAHEAD") != "0"; + + internal bool CollectLookahead { get; set; } = CollectLookaheadDefault; + + public bool LooksAheadOfCollects => + CollectLookahead && LookaheadMode != DrawLookaheadMode.Off && _concurrent.PrefetchedDrawsCrossDispatches; + + // Why a draw's take refused a resolution that looked ahead of dispatches or collector calls; Count is accepted. public enum DrawLookaheadRefusal : byte { // The resolution threw (an owned read), so the draw resolves it as any abandoned job. @@ -84,13 +103,42 @@ public enum DrawLookaheadRefusal : byte Effects, // An ownership answer changed, or a GPU write logged since it began covers what it read. Ownership, + // A collector call it was resolved ahead of did something a resolution may have read (NoteCollect). + CollectEffects, Count, } - private static readonly string[] DrawLookaheadRefusalNames = ["abandoned", "inputs", "effects", "ownership"]; + private static readonly string[] DrawLookaheadRefusalNames = ["abandoned", "inputs", "effects", "ownership", "gc_effects"]; private long _lookaheadJobs, _lookaheadTaken, _lookaheadVerified; private readonly long[] _lookaheadRefusals = new long[(int)DrawLookaheadRefusal.Count]; + // The subset of the look-aheads above that began before a collector call ran (over_gc), and the collector calls + // the worker ran and those of them that noted an effect (gc_calls). + private long _collectLookaheadJobs, _collectLookaheadTaken, _collectLookaheadRefused, _collectCalls, _collectEffectCalls; + + public (long Jobs, long Taken, long Refused, long Calls, long Effects) TakeCollectLookaheadCounters() => + (Interlocked.Exchange(ref _collectLookaheadJobs, 0), Interlocked.Exchange(ref _collectLookaheadTaken, 0), + Interlocked.Exchange(ref _collectLookaheadRefused, 0), Interlocked.Exchange(ref _collectCalls, 0), + Interlocked.Exchange(ref _collectEffectCalls, 0)); + + // The collector call the worker runs now (GateItemKind.Collect) did something a resolution may have read: images + // released, deferred draws run, single-copy chunks armed, emptied or unwatched. A job resolved ahead of + // it is refused, as behind a dispatch's effect. -1 while none did. + private long _lastCollectEffect = -1; + + public void NoteCollect(bool effect) + { + Interlocked.Increment(ref _collectCalls); + if (effect) + { + Interlocked.Increment(ref _collectEffectCalls); + Volatile.Write(ref _lastCollectEffect, Volatile.Read(ref _executedGate)); + } + } + + // The last collector call's gate number (command thread only, NoteGateItem), for Job.LastCollectGate. + private long _lastCollectGate; + public (long Jobs, long Taken, long[] Refused, long Verified) TakeDrawLookaheadCounters() { var refused = new long[(int)DrawLookaheadRefusal.Count]; @@ -106,14 +154,18 @@ public enum DrawLookaheadRefusal : byte private string TakeDrawLookaheadReport() { var (jobs, taken, refused, verified) = TakeDrawLookaheadCounters(); + var collect = TakeCollectLookaheadCounters(); var builder = new System.Text.StringBuilder("draw_lookahead=(mode=").Append(LookaheadMode.ToString().ToLowerInvariant()) - .Append(",over=dispatch,jobs=").Append(jobs).Append(",taken=").Append(taken).Append(",refused=("); + .Append(",over_gc=").Append(LooksAheadOfCollects ? "on" : "off") + .Append(",jobs=").Append(jobs).Append(",taken=").Append(taken).Append(",refused=("); for (var index = 0; index < refused.Length; index++) { builder.Append(index == 0 ? string.Empty : ",").Append(DrawLookaheadRefusalNames[index]).Append('=').Append(refused[index]); } - return builder.Append("),verified=").Append(verified).Append(')').ToString(); + return builder.Append("),verified=").Append(verified) + .Append(",gc=(jobs=").Append(collect.Jobs).Append(",taken=").Append(collect.Taken).Append(",refused=").Append(collect.Refused) + .Append(",calls=").Append(collect.Calls).Append(",effects=").Append(collect.Effects).Append("))").ToString(); } // The kind of a gated non-draw item, as the command thread queues it (NoteGateItem): what the draws after it wait for. @@ -135,12 +187,15 @@ public enum GateItemKind : byte Flush, // Another posted host call. Call, + // The host's collector call after a completed submission (ICommandStreamHost.RunGarbageCollector); with + // LooksAheadOfCollects the draws and dispatches after it do not gate on it. + Collect, // Other deferred work. Other, Count, } - private static readonly string[] GateItemKindNames = ["none", "dispatch", "cp", "label", "range", "wait", "event", "flush", "call", "other"]; + private static readonly string[] GateItemKindNames = ["none", "dispatch", "cp", "label", "range", "wait", "event", "flush", "call", "gc", "other"]; private readonly RenderExecutor _executor; private readonly IRenderHost _host; @@ -225,7 +280,8 @@ public enum ComputeRefusal Inputs, // The ownership answers it read under changed (IConcurrentResolveHost.IsStillCurrentAcrossDispatches). Ownership, - // A dispatch it was resolved ahead of did more than encode GPU work (NoteDispatchEffect). + // A dispatch it was resolved ahead of did more than encode GPU work (NoteDispatchEffect), or a collector call it + // was resolved ahead of noted an effect (NoteCollect). Effects, Count, } @@ -277,7 +333,14 @@ public long[] TakeProviderRefusals() private readonly GateItemKind[] _gateKinds = new GateItemKind[GateKindRing]; // On the command thread, as it queues the gated non-draw item that brings its gate count to gate. - public void NoteGateItem(long gate, GateItemKind kind) => _gateKinds[gate & (GateKindRing - 1)] = kind; + public void NoteGateItem(long gate, GateItemKind kind) + { + _gateKinds[gate & (GateKindRing - 1)] = kind; + if (kind == GateItemKind.Collect) + { + _lastCollectGate = gate; + } + } private GateItemKind GateKindOf(long gate) => gate <= 0 ? GateItemKind.None : _gateKinds[gate & (GateKindRing - 1)]; @@ -315,7 +378,7 @@ public Job Submit(RegisterBanks banks, long gate = 0, bool indexed = false, int SubmitDrawAhead(banks, gate, gate, indexed, startInstanceUserData); // A draw's job whose resolution may start once the first gate items ran, before the rest up to fullGate (dispatches - // only, the sink's DispatchGate) did; with gate == fullGate, Submit. + // and collector calls only, the sink's DispatchGate) did; with gate == fullGate, Submit. public Job SubmitDrawAhead(RegisterBanks banks, long gate, long fullGate, bool indexed = false, int startInstanceUserData = -1) { fullGate = Math.Max(gate, fullGate); @@ -326,7 +389,7 @@ public Job SubmitDrawAhead(RegisterBanks banks, long gate, long fullGate, bool i } _lastDrawGate = fullGate; - return Enqueue(new Job(banks, gate, indexed, startInstanceUserData) { FullGate = fullGate }); + return Enqueue(new Job(banks, gate, indexed, startInstanceUserData) { FullGate = fullGate, LastCollectGate = _lastCollectGate }); } private Job Enqueue(Job job) @@ -475,11 +538,17 @@ public bool TryTakeGraphics(RegisterBanks banks, in GraphicsProgramInputs inputs } using var profile = RenderPhaseProfile.MeasureDetail(RenderPhaseProfile.Phase.ProgramPrefetchValidation); - // The resolution began before every gated item ahead of the draw ran: it looked ahead of dispatches. + // The resolution began before every gated item ahead of the draw ran: it looked ahead of dispatches, and of a + // collector call when one of those items was one. var lookedAhead = job.ExecutedAtStart < job.FullGate; + var overCollect = lookedAhead && job.LastCollectGate > job.ExecutedAtStart; if (lookedAhead) { Interlocked.Increment(ref _lookaheadJobs); + if (overCollect) + { + Interlocked.Increment(ref _collectLookaheadJobs); + } } if (job.State != 1) @@ -487,6 +556,10 @@ public bool TryTakeGraphics(RegisterBanks banks, in GraphicsProgramInputs inputs if (lookedAhead) { Interlocked.Increment(ref _lookaheadRefusals[(int)DrawLookaheadRefusal.Abandoned]); + if (overCollect) + { + Interlocked.Increment(ref _collectLookaheadRefused); + } } ReleaseAssumptions(job); @@ -495,7 +568,8 @@ public bool TryTakeGraphics(RegisterBanks banks, in GraphicsProgramInputs inputs var refusal = !job.Inputs.Equals(inputs) ? DrawLookaheadRefusal.Inputs : !lookedAhead ? (_concurrent.IsStillCurrent(job.Assumptions!) ? DrawLookaheadRefusal.Count : DrawLookaheadRefusal.Ownership) - // A dispatch that ran after the resolution began (gate above ExecutedAtStart) did more than encode GPU work. + // A collector call or a dispatch that ran after the resolution began (gate above ExecutedAtStart) noted an effect. + : Volatile.Read(ref _lastCollectEffect) >= job.ExecutedAtStart ? DrawLookaheadRefusal.CollectEffects : Volatile.Read(ref _lastDispatchEffect) >= job.ExecutedAtStart ? DrawLookaheadRefusal.Effects : !_concurrent.IsStillCurrentAcrossDispatches(job.Assumptions!) ? DrawLookaheadRefusal.Ownership : DrawLookaheadRefusal.Count; @@ -505,6 +579,10 @@ public bool TryTakeGraphics(RegisterBanks banks, in GraphicsProgramInputs inputs if (lookedAhead) { Interlocked.Increment(ref _lookaheadRefusals[(int)refusal]); + if (overCollect) + { + Interlocked.Increment(ref _collectLookaheadRefused); + } } Interlocked.Increment(ref _refusedCount); @@ -516,6 +594,11 @@ public bool TryTakeGraphics(RegisterBanks banks, in GraphicsProgramInputs inputs if (lookedAhead) { Interlocked.Increment(ref _lookaheadTaken); + if (overCollect) + { + Interlocked.Increment(ref _collectLookaheadTaken); + } + if (LookaheadMode == DrawLookaheadMode.Verify) { programs = VerifyLookahead(job, banks, in inputs); @@ -533,16 +616,17 @@ private GraphicsPrograms VerifyLookahead(Job job, RegisterBanks banks, in Graphi Interlocked.Increment(ref _lookaheadVerified); if (SharpEmu.Libs.Gpu.Pipelines.GraphicsProgramsComparer.Difference(job.Programs!, resolved) is { } difference) { - throw _fatal($"A draw's programs resolved ahead of the dispatches before it differ from the worker's: {difference} " + - $"(job {job.Index}, gate {job.Gate}, full gate {job.FullGate}, executed at start {job.ExecutedAtStart})."); + throw _fatal($"A draw's programs resolved ahead of the dispatches or collector calls before it differ from the worker's: {difference} " + + $"(job {job.Index}, gate {job.Gate}, full gate {job.FullGate}, executed at start {job.ExecutedAtStart}, last collector call {job.LastCollectGate})."); } return resolved; } // The dispatch the worker runs now takes the program its job resolved when the job was resolved from the same banks - // and arguments, the provider stood for it, no dispatch it was resolved ahead of did more than encode GPU work, - // and the host's ownership answers still hold across those dispatches; otherwise it resolves the program itself. + // and arguments, the provider stood for it, no dispatch it was resolved ahead of did more than encode GPU work (nor + // collector call noted an effect), and the host's ownership answers still hold across those items; otherwise it + // resolves the program itself. public bool TryTakeCompute(RegisterBanks banks, uint dispatchInitiator, uint groupsX, uint groupsY, uint groupsZ, bool indirect, out ComputeProgram program) { @@ -576,7 +660,7 @@ public bool TryTakeCompute(RegisterBanks banks, uint dispatchInitiator, uint gro var refusal = job.State != 1 ? ComputeRefusal.Abandoned : job.ComputeResult is null ? ComputeRefusal.Provider : !arguments.Matches(dispatchInitiator, groupsX, groupsY, groupsZ, indirect) ? ComputeRefusal.Inputs - : Volatile.Read(ref _lastDispatchEffect) >= job.Gate ? ComputeRefusal.Effects + : Volatile.Read(ref _lastDispatchEffect) >= job.Gate || Volatile.Read(ref _lastCollectEffect) >= job.Gate ? ComputeRefusal.Effects : !_concurrent.IsStillCurrentAcrossDispatches(job.Assumptions!) ? ComputeRefusal.Ownership : ComputeRefusal.Count; ReleaseAssumptions(job); diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalCommandStream.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalCommandStream.cs index e32719358..4fc10db5c 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalCommandStream.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalCommandStream.cs @@ -612,15 +612,21 @@ public void SynchronizeGpu() FlushAndWaitForGpu(MetalWaitReason.Synchronize); } + // Posted after every completed submission. The draws and dispatches after it may resolve their programs before it + // runs (ParallelProgramPrefetch.LooksAheadOfCollects): on the worker it tells the prefetch whether it did anything + // such a resolution may have read, and those that began before it are then refused (NoteCollect). An effect is any + // deferred draw it ran or anything MetalImageCache.Collect reports (an image released, single-copy work). public void RunGarbageCollector() { - if (PostToWorker(RunGarbageCollector)) + if (PostToWorker(RunGarbageCollector, SharpEmu.Libs.Gpu.Rendering.ParallelProgramPrefetch.GateItemKind.Collect)) { return; } + var drained = _translation is { HasPendingDraws: true }; DrainDraws(); - _imageCache.Collect(); + var collected = _imageCache.Collect(); + _translation?.Prefetch?.NoteCollect(effect: drained || collected); } // SHARPEMU_TRACE_GDS=1: the first data share fills and copies, offsets and guest addresses. diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.Tracking.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.Tracking.cs index d17a93fbc..5158b2882 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.Tracking.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.Tracking.cs @@ -609,11 +609,30 @@ public void MarkFrame() /// /// Advances the collection tick, re-reads the budget when it is due, retires images past - /// the retirement age and evicts stale images over the budget. + /// the retirement age and evicts stale images over the budget. Returns whether it did anything a program + /// resolution running on another thread may have read (ParallelProgramPrefetch.NoteCollect). /// - public void Collect() + /// + /// A resolution reads guest bytes, the ownership answers (registered GPU-modified images, pending GPU writes, the + /// overlays, queued writes) and pending copies. What each step can change, and whether it counts: + /// - the collection tick and the access clock, the idle clock sample, the budget evaluation and the expiry of + /// recently dropped images: least-recently-used and budget bookkeeping the worker reads when it creates, evicts + /// or overlaps images, never a resolution; not an effect; + /// - pruning completed fenced writebacks: the fences only hold guest CPU stores until a writeback's submission + /// completes, and none is consulted by a resolution's reads or ownership tests; not an effect; + /// - an image released (housekeeping's retirement or staleness, budget eviction): it changes the image set and + /// ownership, may write the image back into guest memory and may restore single-copy chunks, which a re-check of + /// the answers alone can miss (owned and released again since the read); an effect, seen as a moved ImageSetVersion; + /// - retired images disposed: only the Metal views and texture of an image already unregistered (its release + /// moved ImageSetVersion then, and its slot is gone), which no resolution reads; not an effect; + /// - single-copy arming, emptying, punch bookkeeping and unwatching (MetalSingleCopy.Tick): they change what guest + /// memory backs and how a resolution's compares answer; an effect. + /// + public bool Collect() { using var held = _lock.Hold(); + var imageSet = ImageSetVersion; + var gpuModified = Epochs.GpuModified; _collectionTick++; if (SharpEmu.Logging.MemoryTelemetry.Enabled) { @@ -627,7 +646,8 @@ public void Collect() MaybeEvaluateBudgetLocked(now); HousekeepLocked(now); CollectIfOverBudget(now); - SingleCopy?.Tick(this, now); + var singleCopyWork = SingleCopy?.Tick(this, now) == true; + return singleCopyWork || ImageSetVersion != imageSet || Epochs.GpuModified != gpuModified; } private void CollectIfOverBudget() => CollectIfOverBudget(_clock()); diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalSingleCopy.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalSingleCopy.cs index cd6e5b7ba..99490cca4 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalSingleCopy.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalSingleCopy.cs @@ -508,38 +508,43 @@ internal bool IsEmptied(int chunk) // ---- The tick: arm, empty, unwatch ------------------------------------------------ - /// From the image cache's Collect, on the GPU worker, with the image lock held. - public void Tick(MetalImageCache cache, long now) + /// From the image cache's Collect, on the GPU worker, with the image lock held. Returns whether it + /// unwatched, took a punch, emptied or tried to arm anything: what guest memory backs may have changed + /// (MetalImageCache.Collect counts it as an effect). + public bool Tick(MetalImageCache cache, long now) { if (_disposed) { - return; + return false; } - DrainUnwatches(); + var changed = DrainUnwatches(); if (_stopped) { - return; + return changed; } - TakePunched(now); + changed |= TakePunched(now); if (DeviceAddressSeen) { // Nothing new is armed; what was armed was given back when the program ran. - return; + return changed; } - EmptyDue(cache, now); + changed |= EmptyDue(cache, now); if (!ArmingPaused && now - _lastScan >= Ticks(_settings.ScanInterval)) { _lastScan = now; - ArmCandidates(cache, now); + changed |= ArmCandidates(cache, now); } + + return changed; } private static long Ticks(TimeSpan span) => (long)(span.TotalSeconds * Stopwatch.Frequency); - private void ArmCandidates(MetalImageCache cache, long now) + // Whether it found a candidate to arm. + private bool ArmCandidates(MetalImageCache cache, long now) { var budget = _settings.ArmBytesPerScan; var idle = Ticks(_settings.Idle); @@ -562,7 +567,7 @@ private void ArmCandidates(MetalImageCache cache, long now) if (candidates is null) { - return; + return false; } foreach (var image in candidates) @@ -574,6 +579,8 @@ private void ArmCandidates(MetalImageCache cache, long now) budget -= Math.Min(budget, TryArm(cache, image, now)); } + + return true; } // The image-level rules; the chunk-level ones are in TryArm. @@ -762,10 +769,13 @@ private bool IsReleasableChunk( return cache.IsSoleSingleCopyOwnerLocked(image, address, _chunkBytes); } - private void TakePunched(long now) + // Whether it took any. + private bool TakePunched(long now) { + var took = false; while (_memory.TryTakeSingleCopyPunched(out var punched)) { + took = true; lock (_m) { if (_chunks.TryGetValue(punched.Chunk, out var chunk) && chunk.State == ChunkState.Pending && @@ -775,10 +785,12 @@ private void TakePunched(long now) } } } + + return took; } - // Empties every pending chunk whose punch has settled, a record at a time. - private void EmptyDue(MetalImageCache cache, long now) + // Empties every pending chunk whose punch has settled, a record at a time; whether any was due. + private bool EmptyDue(MetalImageCache cache, long now) { var completed = _completedSerial(); var grace = Ticks(_settings.Grace); @@ -827,6 +839,8 @@ private void EmptyDue(MetalImageCache cache, long now) ReEmpty(chunk, now); } } + + return due is not null || reEmpty is not null; } private void EmptyRecord(Record record, long now, long grace) @@ -1023,15 +1037,20 @@ private void ReEmpty(Chunk chunk, long now) } } - private void DrainUnwatches() + // Whether it dequeued any. + private bool DrainUnwatches() { + var any = false; while (_unwatch.TryDequeue(out var address)) { + any = true; lock (_w) { TryUnwatchLocked(address); } } + + return any; } // Caller holds W. Removes the watch at a chunk address once no released chunk is there. diff --git a/tests/SharpEmu.Gpu.Metal.Tests/MetalImageBudgetTests.cs b/tests/SharpEmu.Gpu.Metal.Tests/MetalImageBudgetTests.cs index 76b7a622c..3cf9cbda3 100644 --- a/tests/SharpEmu.Gpu.Metal.Tests/MetalImageBudgetTests.cs +++ b/tests/SharpEmu.Gpu.Metal.Tests/MetalImageBudgetTests.cs @@ -295,6 +295,32 @@ public void ARetiredGpuWrittenImageIsWrittenBackBeforeItsTextureIsReleased() Assert.Equal(0, image.Texture); } + // The collector call after each submission tells the program resolutions running ahead of it whether it did + // anything they may have read (ParallelProgramPrefetch.NoteCollect): no effect while every image stays, one when + // an image is released, and none for disposing the released texture once its submission completed. + [Fact] + public void ACollectionReportsAnEffectOnlyWhenItReleasesAnImage() + { + if (!RequireDevice()) return; + using var rig = new Rig(Device.Value); + rig.Configure(retireFrames: 2, retireSeconds: 1); + var idle = rig.Acquire(GuestBase, ImageRole.Texture); + var busy = GuestBase + 0x10000; + rig.Acquire(busy, ImageRole.Texture); + Assert.Equal(0, rig.Frame(seconds: 0.1, touch: busy)); + + var effects = 0; + for (var frame = 0; frame < 6 && rig.Cache.TryGetImage(idle, out _); frame++) + { + effects += rig.Frame(seconds: 1, touch: busy); + } + + Assert.False(rig.Cache.TryGetImage(idle, out _)); + Assert.Equal(1, effects); + Assert.Equal(0, rig.Frame(seconds: 0.1, touch: busy)); + Assert.False(rig.Cache.Collect()); + } + // Budget eviction takes only images outside the working set and idle for the minimum time; // critical pressure drops the time requirement but never the frame guard. [Fact] @@ -630,9 +656,11 @@ public void Configure( } // One presented frame lasting this long: the touched image is used in it, the frame is - // marked, and enough submissions complete that the tick guard is past. - public void Frame(double seconds, ulong? touch = null, bool submit = true) + // marked, and enough submissions complete that the tick guard is past. Returns how many of + // its collections reported an effect (MetalImageCache.Collect). + public int Frame(double seconds, ulong? touch = null, bool submit = true) { + var effects = 0; if (touch is { } address) { Acquire(address, ImageRole.Texture); @@ -649,8 +677,10 @@ public void Frame(double seconds, ulong? touch = null, bool submit = true) Harness.Begin(); } - Cache.Collect(); + effects += Cache.Collect() ? 1 : 0; } + + return effects; } public void WriteGuest(ulong address, byte[] bytes) => Assert.True(_backing.TryWriteBacking(address, bytes)); diff --git a/tests/SharpEmu.Gpu.Metal.Tests/Scenes/DsDrawCostBenchTests.cs b/tests/SharpEmu.Gpu.Metal.Tests/Scenes/DsDrawCostBenchTests.cs index 5b4d28a36..90179ad48 100644 --- a/tests/SharpEmu.Gpu.Metal.Tests/Scenes/DsDrawCostBenchTests.cs +++ b/tests/SharpEmu.Gpu.Metal.Tests/Scenes/DsDrawCostBenchTests.cs @@ -531,6 +531,11 @@ ulong DispatchTable(int dispatch, ulong writeBuffer) // at _GAME_DRAWS and _CHURN_EVERY=1, every draw has a mesh of its own whose table changes every round. var meshRepeat = Setting("MESH_REPEAT", 2); var dispatchEvery = int.TryParse(Environment.GetEnvironmentVariable("SHARPEMU_DS_DRAW_BENCH_DISPATCH_EVERY"), out var every) && every > 0 ? every : 0; + // SHARPEMU_DS_DRAW_BENCH_BURST=1: a round's game streams are all submitted before the worker records any, as + // Demon's Souls submits ~13 command buffers at once, so the collector call after each submission lies between + // draws (and is looked ahead of with SHARPEMU_PREFETCH_DRAW_LOOKAHEAD); one commit and one copy arming a round, + // and the churned textures unregistered after it. 0 (the default) records each submission as it is queued. + var burst = Environment.GetEnvironmentVariable("SHARPEMU_DS_DRAW_BENCH_BURST") == "1"; ulong copyDestination = 0, copySource = 0, copyWords = 0; void ArmCopiedTables() { @@ -712,6 +717,21 @@ void ArmCopiedTables() { rig.RecordPending(); } + else if (burst) + { + ArmCopiedTables(); + for (var index = 0; index < gameStreams.Length; index++) + { + rig.Host.CommandStream.EnqueueGraphics(gameStreams[index].Address, gameStreams[index].Length, ++submissionId, null); + } + + rig.RecordPending(); + rig.Host.FlushCommandBuffer(); + for (var index = 2; index < gameStreams.Length; index += 3) + { + ((SharpEmu.HLE.GpuMemory.IGuestImageStore)rig.Host.ImageCache).Unregister(game.Churn[index % ChurnTextures], 0x10000); + } + } else { ArmCopiedTables(); diff --git a/tests/SharpEmu.Libs.Tests/Gpu/Rendering/ParallelProgramPrefetchComputeTests.cs b/tests/SharpEmu.Libs.Tests/Gpu/Rendering/ParallelProgramPrefetchComputeTests.cs index 488bcd302..d3b12de3b 100644 --- a/tests/SharpEmu.Libs.Tests/Gpu/Rendering/ParallelProgramPrefetchComputeTests.cs +++ b/tests/SharpEmu.Libs.Tests/Gpu/Rendering/ParallelProgramPrefetchComputeTests.cs @@ -157,6 +157,25 @@ public void ADispatchEffectRefusesOnlyTheJobsResolvedAheadOfIt() Assert.True(Take(banks, behind)); } + // A collector call that noted an effect refuses the dispatch jobs resolved ahead of it as a dispatch's effect does; + // one that did nothing refuses none. + [Theory] + [InlineData(false)] + [InlineData(true)] + public void ACollectorCallEffectRefusesOnlyTheJobsResolvedAheadOfIt(bool effect) + { + var banks = Banks().Snapshot(); + var ahead = Resolved(banks, gate: 3); + var behind = _prefetch.SubmitCompute(banks, 4, Initiator, 4, 2, 1, false); + // Item 3 (the fourth gated non-draw) is the collector call. + _prefetch.NoteCollect(effect); + _prefetch.AdvanceGate(4); + _prefetch.WaitIdle(); + Assert.Equal(!effect, Take(banks, ahead)); + Assert.Equal(effect ? 1 : 0, Refused(ParallelProgramPrefetch.ComputeRefusal.Effects)); + Assert.True(Take(banks, behind)); + } + [Fact] public void ADrawDoesNotTakeADispatchJobNorADispatchADrawJob() { diff --git a/tests/SharpEmu.Libs.Tests/Gpu/Rendering/ParallelProgramPrefetchDrawLookaheadTests.cs b/tests/SharpEmu.Libs.Tests/Gpu/Rendering/ParallelProgramPrefetchDrawLookaheadTests.cs index 16c820e6a..881d6a23d 100644 --- a/tests/SharpEmu.Libs.Tests/Gpu/Rendering/ParallelProgramPrefetchDrawLookaheadTests.cs +++ b/tests/SharpEmu.Libs.Tests/Gpu/Rendering/ParallelProgramPrefetchDrawLookaheadTests.cs @@ -15,7 +15,8 @@ namespace SharpEmu.Libs.Tests.Gpu.Rendering; // A draw's job may resolve before the dispatches just before the draw ran (SubmitDrawAhead). Its take accepts the // resolution only when none of the dispatches that ran after it began did more than encode GPU work and the host's // answers still hold across them (IsStillCurrentAcrossDispatches); otherwise the draw resolves its programs itself. -// Every other gated item still holds the draw's resolution. +// The host's collector call after a submission is looked ahead of the same way (NoteCollect). Every other gated item +// still holds the draw's resolution. [Collection(SchedulingStateCollection.Name)] public sealed class ParallelProgramPrefetchDrawLookaheadTests : IDisposable { @@ -46,6 +47,7 @@ private sealed class ConcurrentHost : IConcurrentResolveHost internal bool Current = true; internal bool CurrentAcrossDispatches = true; internal int Checks, CrossChecks; + public bool PrefetchedDrawsCrossDispatches => true; public void BeginConcurrentResolve() { } public object EndConcurrentResolve() => this; public bool IsStillCurrent(object assumptions) @@ -224,5 +226,131 @@ public void AnInterruptBeforeTheDispatchStillHoldsTheDraw() Assert.True(job.ExecutedAtStart >= 1); } + // A draw job submitted after a collector call queued as gated item `collectGate`, resolved once `executed` items ran. + private ParallelProgramPrefetch.Job ResolvedAfterCollect(RegisterBanks banks, long collectGate, long gate, long fullGate) + { + _prefetch.NoteGateItem(collectGate, ParallelProgramPrefetch.GateItemKind.Collect); + var job = Resolved(banks, gate, fullGate); + Assert.Equal(collectGate, job.LastCollectGate); + return job; + } + + // The collector call after a submission released nothing, disposed nothing and armed nothing: a draw resolved + // before it ran is taken, and counted as a look-ahead over it. + [Fact] + public void ADrawResolvedAheadOfACollectorCallThatDidNothingIsTaken() + { + var banks = Banks().Snapshot(); + var job = ResolvedAfterCollect(banks, collectGate: 1, gate: 0, fullGate: 1); + Assert.Equal(0, job.ExecutedAtStart); + // The worker runs the call (gated item 1). + _prefetch.NoteCollect(effect: false); + _prefetch.AdvanceGate(1); + Assert.True(Take(banks, job)); + Assert.Equal(1, _concurrent.CrossChecks); + var counters = Counters(); + Assert.Equal((1L, 1L), (counters.Jobs, counters.Taken)); + Assert.All(counters.Refused, count => Assert.Equal(0, count)); + Assert.Equal((1L, 1L, 0L, 1L, 0L), _prefetch.TakeCollectLookaheadCounters()); + } + + // A collector call that noted an effect (an image released, single-copy work) refuses the draws resolved before it + // ran, and only those: one resolved after it ran, still ahead of a dispatch, is taken and not counted over the call. + [Fact] + public void ACollectorCallThatNotedAnEffectRefusesTheDrawsResolvedAheadOfItOnly() + { + var banks = Banks().Snapshot(); + // Gated item 1 is the collector call, item 2 a dispatch. + var ahead = ResolvedAfterCollect(banks, collectGate: 1, gate: 0, fullGate: 2); + _prefetch.NoteCollect(effect: true); + _prefetch.AdvanceGate(1); + var behind = Resolved(banks, gate: 1, fullGate: 2); + Assert.Equal(1, behind.ExecutedAtStart); + _prefetch.AdvanceGate(2); + Assert.False(Take(banks, ahead)); + Assert.True(Take(banks, behind)); + var counters = Counters(); + Assert.Equal((2L, 1L), (counters.Jobs, counters.Taken)); + Assert.Equal(1, counters.Refused[(int)ParallelProgramPrefetch.DrawLookaheadRefusal.CollectEffects]); + Assert.Equal(0, counters.Refused[(int)ParallelProgramPrefetch.DrawLookaheadRefusal.Effects]); + Assert.Equal((1L, 0L, 1L, 1L, 1L), _prefetch.TakeCollectLookaheadCounters()); + } + + // =verify covers a look-ahead over a collector call: the worker resolves it again, and a difference is fatal. + [Fact] + public void VerifyResolvesALookaheadOverACollectorCallAgainAndFailsOnADifference() + { + _prefetch.LookaheadMode = ParallelProgramPrefetch.DrawLookaheadMode.Verify; + var banks = Banks().Snapshot(); + var job = ResolvedAfterCollect(banks, collectGate: 1, gate: 0, fullGate: 1); + _prefetch.NoteCollect(effect: false); + _prefetch.AdvanceGate(1); + Assert.True(Take(banks, job)); + Assert.Equal(1, Counters().Verified); + Assert.Equal(1, _prefetch.TakeCollectLookaheadCounters().Taken); + + // The collector wrongly reported nothing for a change the resolution read: the provider now resolves other programs. + job = ResolvedAfterCollect(banks, collectGate: 2, gate: 1, fullGate: 2); + _pipelines.Graphics = Programs(vertexBuffers: [new VertexInputBuffer(VertexBase, 16, 4)]); + _prefetch.NoteCollect(effect: false); + _prefetch.AdvanceGate(2); + Assert.Throws(() => Take(banks, job)); + } + + // On the command thread: with look-ahead on, a collector call leaves the dispatch gate where it is, so the draw after + // it resolves before the call runs (the call waits here until it did); with SHARPEMU_PREFETCH_DRAW_LOOKAHEAD=0 the + // call moves the gate and still holds the draw, as with SHARPEMU_PREFETCH_GC_LOOKAHEAD=0 alone. + [Theory] + [InlineData(ParallelProgramPrefetch.DrawLookaheadMode.On, true)] + [InlineData(ParallelProgramPrefetch.DrawLookaheadMode.Verify, true)] + [InlineData(ParallelProgramPrefetch.DrawLookaheadMode.Off, true)] + [InlineData(ParallelProgramPrefetch.DrawLookaheadMode.On, false)] + public void ACollectorCallHoldsTheDrawAfterItOnlyWithLookaheadOff(ParallelProgramPrefetch.DrawLookaheadMode mode, bool collectLookahead) + { + _prefetch.LookaheadMode = mode; + _prefetch.CollectLookahead = collectLookahead; + var lookahead = mode != ParallelProgramPrefetch.DrawLookaheadMode.Off && collectLookahead; + Assert.Equal(lookahead, _prefetch.LooksAheadOfCollects); + var host = new RecordingCommandStreamHost(); + var queue = new CommandStreamQueue(host); + var producer = new DeferredCommandThread(queue, host.Memory, _ => { }, _prefetch, () => { }, false); + ParallelProgramPrefetch.Job? job = null; + var resolvedBeforeTheCall = false; + var done = 0; + Assert.True(queue.TryEnqueueControlBarrier(() => + { + producer.Post(() => + { + // Held, the job cannot resolve before this call returns: wait briefly; ahead, it resolves now. + // The command thread may not have submitted the job yet when the worker gets here. + resolvedBeforeTheCall = SpinWait.SpinUntil(() => Volatile.Read(ref job) is { State: not 0 }, + TimeSpan.FromMilliseconds(lookahead ? 10_000 : 200)); + _prefetch.NoteCollect(effect: false); + }, ParallelProgramPrefetch.GateItemKind.Collect); + job = _prefetch.SubmitDrawAhead(Banks().Snapshot(), producer.DispatchGate, producer.Gate); + producer.EnqueueDeferred(new Work(), isDraw: true); + producer.Post(() => Volatile.Write(ref done, 1)); + }, () => { })); + producer.Start(); + try + { + Assert.True(SpinWait.SpinUntil(() => + { + producer.RunBatch(long.MaxValue, 64, () => { }); + return Volatile.Read(ref done) == 1; + }, TimeSpan.FromSeconds(20))); + producer.ThrowIfFailed(); + } + finally + { + producer.Stop(() => producer.RunBatch(long.MaxValue, 64, () => { })); + } + + _prefetch.WaitIdle(); + Assert.Equal((lookahead ? 0L : 1L, 1L, 1L), (job!.Gate, job.FullGate, job.LastCollectGate)); + Assert.Equal(lookahead, resolvedBeforeTheCall); + Assert.True(lookahead ? job.ExecutedAtStart == 0 : job.ExecutedAtStart >= 1); + } + private sealed record Work : SharpEmu.Libs.Agc.AgcExports.DeferredWork; } From 538ca280d9cde6d6b5367196ae6d60e0e2e607e9 Mon Sep 17 00:00:00 2001 From: kuba Date: Sun, 15 Nov 2026 17:40:54 +0000 Subject: [PATCH 085/178] [Shader] Make the materializer's read proofs opt-in A Demon's Souls run with SHARPEMU_RESOURCE_READ_PROOF=verify found one proof that held before and after a full evaluation that did not give the snapshot (plan 0x4DFFC096614D79ED, vertex stage), not yet explained, and the proofs bought no resolver time in that game. SHARPEMU_RESOURCE_READ_PROOF=1 turns them on, =verify checks them. --- .../Resources/ResourceMaterializer.cs | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/src/SharpEmu.ShaderCompiler/Resources/ResourceMaterializer.cs b/src/SharpEmu.ShaderCompiler/Resources/ResourceMaterializer.cs index a10617266..6fa9152d1 100644 --- a/src/SharpEmu.ShaderCompiler/Resources/ResourceMaterializer.cs +++ b/src/SharpEmu.ShaderCompiler/Resources/ResourceMaterializer.cs @@ -403,9 +403,14 @@ public void CarryBackoffTo(FastOrigin rebuilt) } } - // SHARPEMU_RESOURCE_READ_PROOF: on (default), 0 (every revalidation evaluates the program word by word, as before), + // SHARPEMU_RESOURCE_READ_PROOF: off (default: every revalidation evaluates the program word by word), 1 or on, // verify (a proved revalidation also evaluates in full and stops when the snapshot is not current). // + // Off by default since 2026-11-15: a Demon's Souls verify run found one proof that held before and after a full + // evaluation that did not give the snapshot ("[SHADER][READ_PROOF] verify mismatch", plan 0x4DFFC096614D79ED, vertex + // stage, 8 ranges, 156 bytes; about one in 200,000 proved revalidations), not yet explained, and in that game the + // proofs bought no resolver time (as many origins change or are recorded again as are proved). + // // A fast snapshot's revalidation evaluates its program again with the snapshot's own user data, shader base and // readers and compares the words it emits with the snapshot. The evaluation that made the snapshot (or last found it // current) records what it read (MaterializationProgram.ReadProof); with it on, the revalidation compares those words @@ -423,9 +428,9 @@ internal enum ReadProofMode internal static ReadProofMode ParseReadProofMode(string? value) => value?.Trim().ToLowerInvariant() switch { - "0" or "off" => ReadProofMode.Off, + "1" or "on" => ReadProofMode.On, "verify" => ReadProofMode.Verify, - _ => ReadProofMode.On, + _ => ReadProofMode.Off, }; internal static ReadProofMode ReadProofs { get; set; } = ParseReadProofMode(Environment.GetEnvironmentVariable("SHARPEMU_RESOURCE_READ_PROOF")); From 810fed3eb557afc31311ecf1e93d84661834c77d Mon Sep 17 00:00:00 2001 From: kuba Date: Sun, 15 Nov 2026 17:53:21 +0000 Subject: [PATCH 086/178] [GPU] Name the programs, looked-over items and cache state in the look-ahead verify fatal The DS look-ahead verify fatal named only its first differing field (pixel_program), and the read-proof verify mismatch did not say whether the evaluation was refused or differed. Neither could be told apart from a hole in the take check by reading code and the log. The look-ahead fatal now names every differing group, both resolutions' program ids, modules and stage hashes, whether a second worker resolution matches the first, the gated items the resolution looked over (a dispatch's program hash), the effect gates, and the program cache state (content epoch, learned device loads, header registrations, vertex tables, linked lookups) at the end of the look-ahead resolution and now. The read-proof mismatch names the first differing word, the outcome of a second evaluation, and the thread. --- .../Gpu/Pipelines/GraphicsProgramsComparer.cs | 34 ++++++++ .../Gpu/Pipelines/ShaderPipelineCache.cs | 4 + .../Gpu/Rendering/IShaderPipelineProvider.cs | 4 + .../Gpu/Rendering/ParallelProgramPrefetch.cs | 58 ++++++++++++- .../Gpu/Rendering/RenderExecutor.Compute.cs | 1 + .../Gpu/Rendering/RenderExecutor.Prefetch.cs | 7 ++ .../Resources/ResourceMaterializer.cs | 86 ++++++++++++++++++- ...rallelProgramPrefetchDrawLookaheadTests.cs | 11 ++- .../Resources/ReadProofTests.cs | 10 ++- 9 files changed, 210 insertions(+), 5 deletions(-) diff --git a/src/SharpEmu.Libs/Gpu/Pipelines/GraphicsProgramsComparer.cs b/src/SharpEmu.Libs/Gpu/Pipelines/GraphicsProgramsComparer.cs index a82b83fce..6006182c3 100644 --- a/src/SharpEmu.Libs/Gpu/Pipelines/GraphicsProgramsComparer.cs +++ b/src/SharpEmu.Libs/Gpu/Pipelines/GraphicsProgramsComparer.cs @@ -26,6 +26,40 @@ internal static class GraphicsProgramsComparer return VertexDifference(memo.VertexInput, full.VertexInput) ?? PixelDifference(memo.PixelInput, full.PixelInput); } + // Every group that differs, for a fatal that has to name more than the first field: the top-level fields one by one, + // then the first difference within the vertex input and within the pixel input. Empty when none does. + public static string Differences(GraphicsPrograms memo, GraphicsPrograms full) + { + var differences = new List(); + if (memo.Available != full.Available) differences.Add("available"); + if (memo.Vertex != full.Vertex) differences.Add("vertex_program"); + if (memo.Pixel != full.Pixel) differences.Add("pixel_program"); + if (!ReferenceEquals(memo.MeshInput, full.MeshInput) && memo.MeshInput != full.MeshInput) differences.Add("mesh_input"); + if (memo.Tessellation is not null || full.Tessellation is not null) differences.Add("tessellation"); + if (memo.SolidClear != full.SolidClear) differences.Add("solid_clear"); + if (memo.DisableBlending != full.DisableBlending) differences.Add("disable_blending"); + if (memo.DropUnwrittenColorTargets != full.DropUnwrittenColorTargets) differences.Add("drop_unwritten"); + if (memo.PositionStream != full.PositionStream) differences.Add("position_stream"); + if (VertexDifference(memo.VertexInput, full.VertexInput) is { } vertex) differences.Add(vertex); + if (PixelDifference(memo.PixelInput, full.PixelInput) is { } pixel) differences.Add(pixel); + return string.Join(",", differences); + } + + // The identities of a resolution's programs and stages, for the same fatal: each program's id and module, and each + // stage's compiled program hash, shader base and resource counts. + public static string Describe(GraphicsPrograms programs) + { + static string Stage(in ShaderStageResources stage) => stage.Program is not { } program + ? "none" + : $"hash=0x{program.Hash:X16} base=0x{stage.ShaderBase:X} buffers={stage.Resources.Buffers.Length} " + + $"images={stage.Resources.Images.Length} samplers={stage.Resources.Samplers.Length} table={stage.Resources.FlattenedResourceTable.Length}"; + + return $"available={programs.Available} vs=0x{programs.Vertex.Id:X}/0x{programs.Vertex.Module:X} " + + $"ps=0x{programs.Pixel.Id:X}/0x{programs.Pixel.Module:X} drop_unwritten={programs.DropUnwrittenColorTargets} " + + $"vertex_stage=[{Stage(programs.VertexInput.Stage)}] pixel_stage=[{Stage(programs.PixelInput.Stage)}] " + + $"pixel_inputs={programs.PixelInput.InputCount} custom=0x{programs.PixelInput.CustomInterpolationMask:X}"; + } + private static string? VertexDifference(VertexInputInfo memo, VertexInputInfo full) { if (memo.Tessellation is not null || full.Tessellation is not null) return "vertex.tessellation"; diff --git a/src/SharpEmu.Libs/Gpu/Pipelines/ShaderPipelineCache.cs b/src/SharpEmu.Libs/Gpu/Pipelines/ShaderPipelineCache.cs index 617f2a44d..8f71073b6 100644 --- a/src/SharpEmu.Libs/Gpu/Pipelines/ShaderPipelineCache.cs +++ b/src/SharpEmu.Libs/Gpu/Pipelines/ShaderPipelineCache.cs @@ -341,6 +341,10 @@ public GraphicsPrograms GetGraphicsPrograms( } } + public string DescribeProgramState() => + $"content_epoch={_programs.ContentEpoch} device_data={DeviceDataLoads.Generation} " + + $"registrations={ShaderHeaderRegistry.Registrations} tables={_vertexTables.Generation} linked={_programs.LinkedLookups}"; + // The resolve memo of this cache (GraphicsResolveMemo), or null with it off; SHARPEMU_DRAW_REUSE=0 turns it off too. private GraphicsResolveMemo? _resolveMemo = DrawReuseDisabled || GraphicsResolveMemo.DefaultMode == ResolveMemoMode.Off ? null diff --git a/src/SharpEmu.Libs/Gpu/Rendering/IShaderPipelineProvider.cs b/src/SharpEmu.Libs/Gpu/Rendering/IShaderPipelineProvider.cs index 4d450bafd..05140bf67 100644 --- a/src/SharpEmu.Libs/Gpu/Rendering/IShaderPipelineProvider.cs +++ b/src/SharpEmu.Libs/Gpu/Rendering/IShaderPipelineProvider.cs @@ -164,6 +164,10 @@ public interface IShaderPipelineProvider // executor then stops skipping culling primitive-shader draws; see IGuestGpuBackend. bool SupportsPrimitiveShaderMeshPipelines => false; + // The cache-wide state a draw's resolution depends on beyond its registers and guest reads (program cache epoch, + // learned device loads, header registrations...), for the look-ahead verify's fatal (ParallelProgramPrefetch). + string DescribeProgramState() => string.Empty; + // Optional capture of rejected stage inputs; it never admits or executes the draw. void RecordUnsupportedGraphics(VertexStageRegisters vertex, ContextRegisters context) { } diff --git a/src/SharpEmu.Libs/Gpu/Rendering/ParallelProgramPrefetch.cs b/src/SharpEmu.Libs/Gpu/Rendering/ParallelProgramPrefetch.cs index b17c242ec..17043a16b 100644 --- a/src/SharpEmu.Libs/Gpu/Rendering/ParallelProgramPrefetch.cs +++ b/src/SharpEmu.Libs/Gpu/Rendering/ParallelProgramPrefetch.cs @@ -44,6 +44,8 @@ public sealed class Job(RegisterBanks banks, long gate, bool indexed = false, in // The gate number of the last collector call (GateItemKind.Collect) queued before the job: above ExecutedAtStart, // the resolution looked ahead of it (draw_lookahead over_gc). internal long LastCollectGate; + // =verify: the program cache state the resolution ended under (IShaderPipelineProvider.DescribeProgramState). + internal string? ResolveState; } /// @@ -327,6 +329,41 @@ public long[] TakeProviderRefusals() public void NoteDispatchEffect() => Volatile.Write(ref _lastDispatchEffect, Volatile.Read(ref _executedGate)); + // =verify: the compute program hash of each dispatch by the gate number it brings the count to (the worker runs item + // _executedGate + 1), so a fatal names the dispatches a draw looked over. Written and read on the worker only. + private readonly ulong[] _gateDispatchHashes = new ulong[GateKindRing]; + + public void NoteDispatchProgram(ComputeProgram program) + { + if (LookaheadMode == DrawLookaheadMode.Verify) + { + _gateDispatchHashes[(Volatile.Read(ref _executedGate) + 1) & (GateKindRing - 1)] = program.Input.Stage.Program?.Hash ?? 0; + } + } + + // The gated items a resolution that began after `executedAtStart` of them ran looked over, up to the draw's full gate: + // each one's kind, and a dispatch's program hash when the worker resolved one for it. + private string DescribeLookedOver(long executedAtStart, long fullGate) + { + var builder = new System.Text.StringBuilder(); + for (var gate = executedAtStart + 1; gate <= fullGate && gate <= executedAtStart + 16; gate++) + { + var kind = GateKindOf(gate); + builder.Append(builder.Length == 0 ? string.Empty : ",").Append(gate).Append(':').Append(GateItemKindNames[(int)kind]); + if (kind == GateItemKind.Dispatch) + { + builder.Append("=0x").Append(_gateDispatchHashes[gate & (GateKindRing - 1)].ToString("X16")); + } + } + + if (fullGate > executedAtStart + 16) + { + builder.Append(",..."); + } + + return builder.ToString(); + } + // The kind of each gated non-draw item by its gate number, for the counters below. A job's gate is never more than the // command thread's queue depth (at most 4096 items) behind the newest, so a ring twice that holds every gate in use. private const int GateKindRing = 8192; @@ -616,8 +653,22 @@ private GraphicsPrograms VerifyLookahead(Job job, RegisterBanks banks, in Graphi Interlocked.Increment(ref _lookaheadVerified); if (SharpEmu.Libs.Gpu.Pipelines.GraphicsProgramsComparer.Difference(job.Programs!, resolved) is { } difference) { + // What the next verify run needs to tell a hole in the take check from a resolution that differs whatever ran + // before it: every differing group, both resolutions' programs, whether the worker resolves the same again, + // the items looked over (a dispatch's program hash) and the effects noted, and the program cache state the + // look-ahead resolution ended under against the state now. + var again = _executor.ResolveGraphicsPrograms(banks, in inputs); + var stable = SharpEmu.Libs.Gpu.Pipelines.GraphicsProgramsComparer.Difference(resolved, again) is { } againDifference + ? "differs again: " + againDifference + : "same"; throw _fatal($"A draw's programs resolved ahead of the dispatches or collector calls before it differ from the worker's: {difference} " + - $"(job {job.Index}, gate {job.Gate}, full gate {job.FullGate}, executed at start {job.ExecutedAtStart}, last collector call {job.LastCollectGate})."); + $"(job {job.Index}, gate {job.Gate}, full gate {job.FullGate}, executed at start {job.ExecutedAtStart}, last collector call {job.LastCollectGate}). " + + $"differences=[{SharpEmu.Libs.Gpu.Pipelines.GraphicsProgramsComparer.Differences(job.Programs!, resolved)}] " + + $"ahead=[{SharpEmu.Libs.Gpu.Pipelines.GraphicsProgramsComparer.Describe(job.Programs!)}] " + + $"worker=[{SharpEmu.Libs.Gpu.Pipelines.GraphicsProgramsComparer.Describe(resolved)}] worker_again={stable} " + + $"looked_over=[{DescribeLookedOver(job.ExecutedAtStart, job.FullGate)}] " + + $"last_dispatch_effect={Volatile.Read(ref _lastDispatchEffect)} last_collect_effect={Volatile.Read(ref _lastCollectEffect)} " + + $"state_ahead=[{job.ResolveState}] state_now=[{_executor.DescribeProgramState()}]."); } return resolved; @@ -1086,6 +1137,11 @@ private void ResolveCore(Job job) job.Inputs = RenderExecutor.ProgramInputsOf(job.Banks, _host.FormatSupport, WorkerScratch.Enabled ? _fatal : _host.Fatal, job.Indexed, job.StartInstanceUserData); job.Programs = _executor.ResolveGraphicsPrograms(job.Banks, in job.Inputs); + if (LookaheadMode == DrawLookaheadMode.Verify) + { + job.ResolveState = _executor.DescribeProgramState(); + } + job.Assumptions = _concurrent.EndConcurrentResolve(); if (job.Programs is { Available: true } programs) { diff --git a/src/SharpEmu.Libs/Gpu/Rendering/RenderExecutor.Compute.cs b/src/SharpEmu.Libs/Gpu/Rendering/RenderExecutor.Compute.cs index 365137784..beab162bf 100644 --- a/src/SharpEmu.Libs/Gpu/Rendering/RenderExecutor.Compute.cs +++ b/src/SharpEmu.Libs/Gpu/Rendering/RenderExecutor.Compute.cs @@ -143,6 +143,7 @@ public void Dispatch(ulong submitId, RegisterBanks banks, uint groupsX, uint gro } } + Prefetch?.NoteDispatchProgram(computeProgram); if (computeProgram.Consumed || computeProgram.ImageCopy is not null || computeProgram.KnownWrite is not null) { // What this dispatch does may not show in the ownership answers of a dispatch resolved ahead of it. diff --git a/src/SharpEmu.Libs/Gpu/Rendering/RenderExecutor.Prefetch.cs b/src/SharpEmu.Libs/Gpu/Rendering/RenderExecutor.Prefetch.cs index 5c8f00874..ae1655e84 100644 --- a/src/SharpEmu.Libs/Gpu/Rendering/RenderExecutor.Prefetch.cs +++ b/src/SharpEmu.Libs/Gpu/Rendering/RenderExecutor.Prefetch.cs @@ -136,6 +136,11 @@ bool TryTakeCompute(RegisterBanks banks, uint dispatchInitiator, uint groupsX, u void NoteDispatchEffect() { } + + // The dispatch running now resolved this program (the look-ahead verify names the dispatches a draw looked over). + void NoteDispatchProgram(ComputeProgram program) + { + } } public sealed partial class RenderExecutor @@ -177,6 +182,8 @@ public static GraphicsProgramInputs ProgramInputsOf(RegisterBanks banks, IImageF return inputs; } + public string DescribeProgramState() => _pipelines.DescribeProgramState(); + // The programs of a draw with these banks and inputs, as ResolveShaderPrograms resolves them. public GraphicsPrograms ResolveGraphicsPrograms(RegisterBanks banks, in GraphicsProgramInputs inputs) { diff --git a/src/SharpEmu.ShaderCompiler/Resources/ResourceMaterializer.cs b/src/SharpEmu.ShaderCompiler/Resources/ResourceMaterializer.cs index 6fa9152d1..86686c306 100644 --- a/src/SharpEmu.ShaderCompiler/Resources/ResourceMaterializer.cs +++ b/src/SharpEmu.ShaderCompiler/Resources/ResourceMaterializer.cs @@ -856,21 +856,39 @@ private static void AttachProof(ShaderResourcePlan plan, ResourceSnapshot snapsh private static void VerifyProof(ShaderResourcePlan plan, ResourceSnapshot snapshot, MaterializationProgram.ReadProof proof, ResourceRuntimeInputs inputs, MaterializationProgram.Output output) { - if (EvaluateInto(plan, inputs, output) && SameAsOutput(plan, snapshot, output)) + var evaluated = EvaluateInto(plan, inputs, output); + if (evaluated && SameAsOutput(plan, snapshot, output)) { _proofVerified.Increment(); return; } + // Taken before the proof is compared again, which reads (and on a resolving thread records) the words anew. + var first = evaluated ? OutputDifference(plan, snapshot, output) : "refused"; if (!Holds(plan, proof, inputs, inputs.CompareGuestWords!)) { _proofVerifyRaced.Increment(); return; } + // A second evaluation tells a difference that keeps (the proof misses something the evaluation reads) from one that + // came and went (a refusal or a read the evaluation made of state that moved meanwhile). + string again; + try + { + again = !EvaluateInto(plan, inputs, output) ? "refused" : SameAsOutput(plan, snapshot, output) ? "current" : OutputDifference(plan, snapshot, output); + } + catch (Exception exception) + { + // An abandoned read on a resolving thread: reported with the mismatch, which is thrown below either way. + again = "threw " + exception.GetType().Name; + } + Interlocked.Increment(ref _proofVerifyFailed); + var thread = Thread.CurrentThread; var message = $"[SHADER][READ_PROOF] verify mismatch: proved current but evaluates otherwise plan=0x{plan.Hash:X16} stage={plan.Stage} " + - $"ranges={proof.Addresses.Length} bytes={proof.Bytes.Length} unreadable={proof.Unreadable.Length}."; + $"ranges={proof.Addresses.Length} bytes={proof.Bytes.Length} unreadable={proof.Unreadable.Length} " + + $"first={first} again={again} branches={plan.ResourceBranches.Count} thread={thread.Name ?? thread.ManagedThreadId.ToString(System.Globalization.CultureInfo.InvariantCulture)}."; Console.Error.WriteLine(message); throw new ReadProofMismatchException(message); } @@ -1045,6 +1063,70 @@ private static bool SameAsOutput(ShaderResourcePlan plan, ResourceSnapshot snaps return true; } + // The first place SameAsOutput finds the output differ from the snapshot, with both words, for the verify's message. + private static string OutputDifference(ShaderResourcePlan plan, ResourceSnapshot snapshot, MaterializationProgram.Output output) + { + static string Words(string what, int index, ReadOnlySpan known, ReadOnlySpan evaluated) + { + var length = Math.Min(known.Length, evaluated.Length); + for (var word = 0; word < length; word++) + { + if (known[word] != evaluated[word]) + { + return FormattableString.Invariant($"{what}[{index}].word{word} snapshot=0x{known[word]:X8} evaluated=0x{evaluated[word]:X8}"); + } + } + + return FormattableString.Invariant($"{what}[{index}] words snapshot={known.Length} evaluated={evaluated.Length}"); + } + + var info = plan.Info; + if (snapshot.Buffers.Length != info.Buffers.Count || snapshot.Images.Length != info.Images.Count || snapshot.Samplers.Length < info.Samplers.Count) + { + return "shape"; + } + + if (!snapshot.FlattenedResourceTable.AsSpan().SequenceEqual(output.TableWords)) + { + return Words("table", 0, snapshot.FlattenedResourceTable, output.TableWords); + } + + if (!snapshot.DeviceAddressRanges.AsSpan().SequenceEqual(output.RangeValues)) + { + return "ranges"; + } + + for (var index = 0; index < info.Buffers.Count; index++) + { + var words = output.Source(index); + var cleared = words.Length == 4 && (words[3] >> 30) != 0; + if (cleared ? snapshot.Buffers[index].AsSpan().ContainsAnyExcept(0u) : !snapshot.Buffers[index].AsSpan().SequenceEqual(words)) + { + return cleared ? FormattableString.Invariant($"buffer[{index}] cleared") : Words("buffer", index, snapshot.Buffers[index], words); + } + } + + for (var index = 0; index < info.Images.Count; index++) + { + var words = output.Source(info.Buffers.Count + index); + if (!snapshot.Images[index].AsSpan().SequenceEqual(words)) + { + return Words("image", index, snapshot.Images[index], words) + (snapshot.MipStatistics is null ? string.Empty : " (statistics)"); + } + } + + for (var index = 0; index < info.Samplers.Count; index++) + { + var words = output.Source(info.Buffers.Count + info.Images.Count + index); + if (!snapshot.Samplers[index].AsSpan().SequenceEqual(words)) + { + return Words("sampler", index, snapshot.Samplers[index], words); + } + } + + return "other"; + } + private static bool SameUnlessStatistics(ReadOnlySpan key, ReadOnlySpan current) { for (var word = 0; word < current.Length; word++) diff --git a/tests/SharpEmu.Libs.Tests/Gpu/Rendering/ParallelProgramPrefetchDrawLookaheadTests.cs b/tests/SharpEmu.Libs.Tests/Gpu/Rendering/ParallelProgramPrefetchDrawLookaheadTests.cs index 881d6a23d..9c1921005 100644 --- a/tests/SharpEmu.Libs.Tests/Gpu/Rendering/ParallelProgramPrefetchDrawLookaheadTests.cs +++ b/tests/SharpEmu.Libs.Tests/Gpu/Rendering/ParallelProgramPrefetchDrawLookaheadTests.cs @@ -179,11 +179,20 @@ public void VerifyResolvesAnAcceptedLookaheadAgainAndFailsOnADifference() Assert.Equal(1, Counters().Verified); // The host wrongly stands for a resolution the dispatch changed: the provider now resolves other programs. + _prefetch.NoteGateItem(2, ParallelProgramPrefetch.GateItemKind.Dispatch); job = Resolved(banks, gate: 1, fullGate: 2); _pipelines.Graphics = Programs(vertexBuffers: [new VertexInputBuffer(VertexBase, 16, 4)]); _prefetch.AdvanceGate(2); - Assert.Throws(() => Take(banks, job)); + var fatal = Assert.Throws(() => Take(banks, job)); Assert.Equal(1, Counters().Verified); + // The fatal names every differing group, both resolutions, whether the worker resolves the same again, and the + // items the resolution looked over, so a verify run's failure can be told apart without another run. + Assert.Contains("differences=[vertex.buffers,", fatal.Message); + Assert.Contains("ahead=[available=True", fatal.Message); + Assert.Contains("worker=[available=True", fatal.Message); + Assert.Contains("worker_again=same", fatal.Message); + Assert.Contains("looked_over=[2:dispatch=0x0000000000000000]", fatal.Message); + Assert.Contains("last_dispatch_effect=-1", fatal.Message); } // A gated item other than a dispatch (here an interrupt) still holds the resolution of the draw after it, while the diff --git a/tests/SharpEmu.ShaderCompiler.Tests/Resources/ReadProofTests.cs b/tests/SharpEmu.ShaderCompiler.Tests/Resources/ReadProofTests.cs index 9602a9607..f03672d3c 100644 --- a/tests/SharpEmu.ShaderCompiler.Tests/Resources/ReadProofTests.cs +++ b/tests/SharpEmu.ShaderCompiler.Tests/Resources/ReadProofTests.cs @@ -268,8 +268,16 @@ public void VerifyStopsOnAWrongProof() ResourceMaterializer.SetReadProofForTest(kept, ResourceMaterializer.ReadProofOf(other)); Assert.True(WithMode(ResourceMaterializer.ReadProofMode.On, () => ResourceMaterializer.RevalidateFast(kept))); - Assert.Throws(() => + var mismatch = Assert.Throws(() => WithMode(ResourceMaterializer.ReadProofMode.Verify, () => ResourceMaterializer.RevalidateFast(kept))); + // It names where the evaluation differs, and that a second evaluation differs the same way (a lasting difference, + // not a read that raced a write). + Assert.Contains("first=", mismatch.Message); + Assert.DoesNotContain("first=refused", mismatch.Message); + Assert.Contains("snapshot=0x", mismatch.Message); + Assert.DoesNotContain("again=current", mismatch.Message); + Assert.DoesNotContain("again=refused", mismatch.Message); + Assert.Contains("thread=", mismatch.Message); Assert.Throws(() => WithMode(ResourceMaterializer.ReadProofMode.Verify, () => ResourceMaterializer.RevalidateOrRebuildFast(kept, out _))); From c900d49e2b5746f3a782c2247e079d19f013fbfa Mon Sep 17 00:00:00 2001 From: kuba Date: Sun, 15 Nov 2026 18:23:10 +0000 Subject: [PATCH 087/178] [GPU] Tell a resolve-memo verify race from a mismatch and name the differing words of both verifies A memo hit's revalidation and its verify's full resolution read guest memory moments apart on a thread beside the guest and the worker, so a word stored between them showed as a mismatch (r26/r27 pixel.table/vertex.table at world load). On a difference verify now re-checks the hit (no rebuild): a miss now is a race (changed); a hit that still holds and a second full resolution equal to it is a race (came_and_went); only a difference that outlives both stops emulation. Counted as resolve_memo verify_raced=(changed,came_and_went); a verify failure on a speculative thread (memo or read proof) is counted as abandoned_verify on the prefetch line instead of a plain abandon. The memo verify mismatch and the look-ahead verify fatal (ahead_vs_worker=) now print, per stage, whether the programs are the same object, the specialization difference (the permutation key) and every differing descriptor word with where it is read from now, and each differing flattened-table word with its guest address. --- .../Gpu/Pipelines/GraphicsProgramsComparer.cs | 104 ++++++++++++++++++ .../Gpu/Pipelines/GraphicsResolveMemo.cs | 16 +++ .../Gpu/Pipelines/ShaderPipelineCache.cs | 85 +++++++++++--- .../Gpu/Pipelines/ShaderProgramCache.cs | 4 +- .../Gpu/Rendering/ParallelProgramPrefetch.cs | 1 + src/SharpEmu.Libs/Gpu/Scheduling/GpuFatal.cs | 18 +++ .../Resources/ResourceMaterializer.cs | 70 ++++++++++++ .../Resources/ResourceSpecialization.cs | 27 +++++ .../Resources/RuntimeValueEvaluator.cs | 43 +++++++- .../V2/MetalRenderHost.ConcurrentResolve.cs | 2 +- .../KeptStageInputsTests.ResolveMemo.cs | 79 +++++++++++++ .../Gpu/Pipelines/PipelineTestSupport.cs | 8 ++ 12 files changed, 431 insertions(+), 26 deletions(-) diff --git a/src/SharpEmu.Libs/Gpu/Pipelines/GraphicsProgramsComparer.cs b/src/SharpEmu.Libs/Gpu/Pipelines/GraphicsProgramsComparer.cs index 6006182c3..d132ae3ea 100644 --- a/src/SharpEmu.Libs/Gpu/Pipelines/GraphicsProgramsComparer.cs +++ b/src/SharpEmu.Libs/Gpu/Pipelines/GraphicsProgramsComparer.cs @@ -60,6 +60,110 @@ static string Stage(in ShaderStageResources stage) => stage.Program is not { } p $"pixel_inputs={programs.PixelInput.InputCount} custom=0x{programs.PixelInput.CustomInterpolationMask:X}"; } + // For a fatal or a race report: per stage, how the two resolutions' permutation keys (specializations) and snapshot + // words differ, whatever their programs are; each differing flattened-table word with both values and the guest + // address it is loaded from (evaluated now with the snapshot's own draw values). Tells inputs that differ (some + // writer) from equal inputs that picked another permutation. + public static string DescribeStages(GraphicsPrograms left, GraphicsPrograms right) => + $"vertex=[{DescribeStage(left.VertexInput.Stage, right.VertexInput.Stage)}] pixel=[{DescribeStage(left.PixelInput.Stage, right.PixelInput.Stage)}]"; + + private static string DescribeStage(in ShaderStageResources left, in ShaderStageResources right) + { + if (left.Program is null || right.Program is null) + { + return left.Program is null && right.Program is null ? "none" : "one_side_none"; + } + + var leftSpecialization = ResourceMaterializer.SpecializationOf(left.Resources); + var rightSpecialization = ResourceMaterializer.SpecializationOf(right.Resources); + var specialization = leftSpecialization is null || rightSpecialization is null ? "unknown" + : ReferenceEquals(leftSpecialization, rightSpecialization) ? "same_object" + : leftSpecialization.DifferenceFrom(rightSpecialization) ?? "equal"; + return $"same_program={ReferenceEquals(left.Program, right.Program)} specialization={specialization} " + + $"words={DescribeWords(left.Resources, right.Resources)}"; + } + + private static string DescribeWords(ResourceSnapshot left, ResourceSnapshot right) + { + if (ReferenceEquals(left, right)) return "same_snapshot"; + var differences = new List(); + List<(ulong Address, uint Word)>? reads = null; + var readsTaken = false; + // Where a differing word of the right side is read from now: the addresses an evaluation of right's program + // reads that value at (a descriptor's words come from memory, not from a table slot with a known address). + string ReadAt(uint[] a, uint[] b) + { + if (!readsTaken) + { + readsTaken = true; + reads = ResourceMaterializer.RecordWordReads(right); + } + + if (reads is null) return " read_at=unknown"; + var found = new List(); + for (var word = 0; word < b.Length && found.Count < 4; word++) + { + if (word < a.Length && a[word] == b[word]) continue; + foreach (var read in reads) + { + if (read.Word != b[word]) continue; + found.Add($"w{word}@0x{read.Address:X}"); + break; + } + } + + return found.Count == 0 ? " read_at=none" : " read_at=" + string.Join(",", found); + } + + void Jagged(string name, uint[][] a, uint[][] b) + { + if (a.Length != b.Length) + { + differences.Add($"{name}.count {a.Length} vs {b.Length}"); + return; + } + + for (var index = 0; index < a.Length; index++) + { + if (a[index].AsSpan().SequenceEqual(b[index])) continue; + differences.Add($"{name}[{index}] {Words(a[index])} vs {Words(b[index])}{ReadAt(a[index], b[index])}"); + } + } + + Jagged("buffers", left.Buffers, right.Buffers); + Jagged("images", left.Images, right.Images); + Jagged("samplers", left.Samplers, right.Samplers); + var (leftTable, rightTable) = (left.FlattenedResourceTable, right.FlattenedResourceTable); + if (leftTable.Length != rightTable.Length) + { + differences.Add($"table.count {leftTable.Length} vs {rightTable.Length}"); + } + else + { + var listed = 0; + for (var slot = 0; slot < leftTable.Length; slot++) + { + if (leftTable[slot] == rightTable[slot]) continue; + if (++listed > 12) + { + differences.Add("table.more"); + break; + } + + var address = ResourceMaterializer.TableWordAddress(left, slot) ?? ResourceMaterializer.TableWordAddress(right, slot); + differences.Add($"table[{slot}]@{(address is { } at ? $"0x{at:X}" : "none")} 0x{leftTable[slot]:X8} vs 0x{rightTable[slot]:X8}"); + } + } + + if (!left.UserData.AsSpan().SequenceEqual(right.UserData)) differences.Add("user_data"); + if (!left.DeviceAddressRanges.AsSpan().SequenceEqual(right.DeviceAddressRanges)) differences.Add("ranges"); + if (!SameArray(left.MipStatistics, right.MipStatistics)) differences.Add("mip_statistics"); + if (left.BindlessImages.Length != right.BindlessImages.Length) differences.Add("bindless.count"); + return differences.Count == 0 ? "equal" : string.Join(";", differences); + } + + private static string Words(uint[] words) => string.Join(",", words.Select(word => word.ToString("X8", System.Globalization.CultureInfo.InvariantCulture))); + private static string? VertexDifference(VertexInputInfo memo, VertexInputInfo full) { if (memo.Tessellation is not null || full.Tessellation is not null) return "vertex.tessellation"; diff --git a/src/SharpEmu.Libs/Gpu/Pipelines/GraphicsResolveMemo.cs b/src/SharpEmu.Libs/Gpu/Pipelines/GraphicsResolveMemo.cs index 538ed9c84..d124f74bd 100644 --- a/src/SharpEmu.Libs/Gpu/Pipelines/GraphicsResolveMemo.cs +++ b/src/SharpEmu.Libs/Gpu/Pipelines/GraphicsResolveMemo.cs @@ -397,6 +397,7 @@ public Entry Store() private static readonly ThreadCounter[] _keyMisses = NewCounters((int)ResolveMemoKeyMiss.Count); private static readonly ThreadCounter[] _uncacheable = NewCounters((int)ResolveMemoUncacheable.Count); private static long _verifyFailed; + private static readonly ThreadCounter[] _verifyRaced = NewCounters((int)ResolveMemoVerifyRace.Count); private static ThreadCounter[] NewCounters(int count) => Enumerable.Range(0, count).Select(_ => new ThreadCounter()).ToArray(); @@ -418,6 +419,11 @@ public Entry Store() public static void NoteVerifyFailed() => Interlocked.Increment(ref _verifyFailed); + // Tests that provoke a mismatch on purpose take it back out of the run-long count the other tests read. + internal static void ForgetVerifyFailureForTest() => Interlocked.Decrement(ref _verifyFailed); + + public static void NoteVerifyRaced(ResolveMemoVerifyRace how) => _verifyRaced[(int)how].Increment(); + private static string Take(ThreadCounter[] counters, params string[] names) => string.Join(",", names.Select((name, index) => FormattableString.Invariant($"{name}={counters[index].Take()}"))); @@ -430,9 +436,19 @@ public static string TakeReport() => FormattableString.Invariant( "key_miss=(" + Take(_keyMisses, "new", "user_data_only", "regs_only") + ")," + "uncacheable_by=(" + Take(_uncacheable, "frontend", "mesh", "tess", "calls", "unavailable", "tables", "trace", "origin", "key", "changed") + ")," + FormattableString.Invariant($"evictions={_evictions.Take()},entries={_entries.Total},verify_checked={_verifyChecked.Take()},") + + "verify_raced=(" + Take(_verifyRaced, "changed", "came_and_went") + ")," + FormattableString.Invariant($"verify_failed={Interlocked.Read(ref _verifyFailed)})"); } +// How a verify difference turned out to be a race (ShaderPipelineCache.VerifyResolveMemo): the hit's revalidation misses +// when made again (its words changed since), or it still holds and a second full resolution agrees with the hit. +internal enum ResolveMemoVerifyRace +{ + Changed, + CameAndWent, + Count, +} + internal enum ResolveMemoKeyMiss { New, diff --git a/src/SharpEmu.Libs/Gpu/Pipelines/ShaderPipelineCache.cs b/src/SharpEmu.Libs/Gpu/Pipelines/ShaderPipelineCache.cs index 8f71073b6..a263b3132 100644 --- a/src/SharpEmu.Libs/Gpu/Pipelines/ShaderPipelineCache.cs +++ b/src/SharpEmu.Libs/Gpu/Pipelines/ShaderPipelineCache.cs @@ -445,12 +445,9 @@ private GraphicsPrograms ResolveThroughMemo(GraphicsResolveMemo memo, RegisterBa GraphicsResolveMemo.NoteHit(); } - if (memo.Mode == ResolveMemoMode.Verify) - { - VerifyResolveMemo(entry, banks, targetExportMapping, flags); - } - - return entry.Programs!; + return memo.Mode == ResolveMemoMode.Verify + ? VerifyResolveMemo(memo, entry, banks, targetExportMapping, flags) + : entry.Programs!; } GraphicsResolveMemo.NoteMiss(miss); @@ -490,7 +487,9 @@ private GraphicsPrograms ResolveFull(RegisterBanks banks, ReadOnlySpan targetExportMapping, - in KeptGraphicsFlags flags) + // Verify: the hit's programs against a full resolution of the same draw, and against what they were when kept; the + // programs to hand out. A resolution beside the guest and the worker reads guest memory a little later than the hit's + // revalidation did, so a word written between the two shows as a difference no key or revalidation could have + // caught: the hit was current when it was made, and the take check judges its recorded reads as it judges a full + // resolution's. So a difference is first checked for that race: the hit's revalidation is made again (without a + // rebuild), and a miss now means its words changed since (raced, the full resolution handed out); while it still + // holds, the draw is resolved in full once more, and an answer equal to the hit means the difference came and went + // (raced). Only a hit that still revalidates while a second full resolution still differs from it is a mismatch, and + // a result written since it was kept always is; either stops emulation (on a speculative thread the work is + // abandoned and counted, GpuFatal.VerifyFailed). + private GraphicsPrograms VerifyResolveMemo(GraphicsResolveMemo memo, GraphicsResolveMemo.Entry entry, RegisterBanks banks, + ReadOnlySpan targetExportMapping, in KeptGraphicsFlags flags) { var memoPrograms = entry.Programs!; var full = ResolveFull(banks, targetExportMapping, flags); - var difference = GraphicsProgramsComparer.Difference(memoPrograms, full) ?? - (GraphicsProgramsComparer.Fingerprint(memoPrograms) != entry.Fingerprint ? "written_since_kept" : null); GraphicsResolveMemo.NoteVerified(); + var difference = GraphicsProgramsComparer.Difference(memoPrograms, full); if (difference is null) { - return; + if (GraphicsProgramsComparer.Fingerprint(memoPrograms) == entry.Fingerprint) + { + return memoPrograms; + } + + throw ResolveMemoVerifyFailed(entry, "written_since_kept", ""); + } + + // Named before anything is read again: the words that differ, their addresses, and both permutation keys. + var stages = GraphicsProgramsComparer.DescribeStages(memoPrograms, full); + if (TryTakeResolveMemo(memo, entry, flags.PixelActive, out _, allowRebuild: false) is { } miss) + { + GraphicsResolveMemo.NoteVerifyRaced(ResolveMemoVerifyRace.Changed); + ReportResolveMemoRace(entry, difference, $"recheck=miss:{miss.ToString().ToLowerInvariant()}", stages); + return full; } + var again = ResolveFull(banks, targetExportMapping, flags); + if (GraphicsProgramsComparer.Difference(memoPrograms, again) is not { } againDifference) + { + GraphicsResolveMemo.NoteVerifyRaced(ResolveMemoVerifyRace.CameAndWent); + ReportResolveMemoRace(entry, difference, "recheck=current again=same_as_hit", stages); + return memoPrograms; + } + + throw ResolveMemoVerifyFailed(entry, difference, + $" recheck=current again={againDifference} hit_vs_full=[{stages}] hit_vs_again=[{GraphicsProgramsComparer.DescribeStages(memoPrograms, again)}]"); + } + + private static Exception ResolveMemoVerifyFailed(GraphicsResolveMemo.Entry entry, string difference, string detail) + { GraphicsResolveMemo.NoteVerifyFailed(); var message = $"[GPU][RESOLVE_MEMO] verify mismatch field={difference} vs=0x{entry.VertexAddress:X16} ps=0x{entry.PixelAddress:X16} " + - $"key_hash=0x{entry.Hash:X16}."; + $"key_hash=0x{entry.Hash:X16}{detail}."; Console.Error.WriteLine(message); - throw GpuFatal.Fatal(message); + return GpuFatal.VerifyFailed(message); + } + + // The first races of a run, with what differed: the words and the guest addresses they were read from name the writer. + private static int _resolveMemoRaceReports; + private const int MaxResolveMemoRaceReports = 32; + + private static void ReportResolveMemoRace(GraphicsResolveMemo.Entry entry, string difference, string how, string stages) + { + if (Interlocked.Increment(ref _resolveMemoRaceReports) > MaxResolveMemoRaceReports) + { + return; + } + + var thread = Thread.CurrentThread; + Console.Error.WriteLine($"[GPU][RESOLVE_MEMO] verify raced field={difference} {how} speculative={GpuFatal.IsSpeculative} " + + $"thread={thread.Name ?? thread.ManagedThreadId.ToString(System.Globalization.CultureInfo.InvariantCulture)} " + + $"vs=0x{entry.VertexAddress:X16} ps=0x{entry.PixelAddress:X16} key_hash=0x{entry.Hash:X16} hit_vs_full=[{stages}]."); } // The interface's earlier forms, for callers holding only the four inputs. diff --git a/src/SharpEmu.Libs/Gpu/Pipelines/ShaderProgramCache.cs b/src/SharpEmu.Libs/Gpu/Pipelines/ShaderProgramCache.cs index 25672c888..329d9d805 100644 --- a/src/SharpEmu.Libs/Gpu/Pipelines/ShaderProgramCache.cs +++ b/src/SharpEmu.Libs/Gpu/Pipelines/ShaderProgramCache.cs @@ -368,7 +368,7 @@ public bool Revalidate(in ShaderStageResources stage) } catch (ResourceMaterializer.ReadProofMismatchException mismatch) { - throw GpuFatal.Fatal(mismatch.Message); + throw GpuFatal.VerifyFailed(mismatch.Message); } var current = fast ?? (Materializations is { } materializations && materializations.Revalidate(stage.Resources, _readResidentGuestBytes)); @@ -400,7 +400,7 @@ public ResourceMaterializer.FastRevalidation RevalidateOrRebuild(in ShaderStageR } catch (ResourceMaterializer.ReadProofMismatchException mismatch) { - throw GpuFatal.Fatal(mismatch.Message); + throw GpuFatal.VerifyFailed(mismatch.Message); } if (fast == ResourceMaterializer.FastRevalidation.NotFast) diff --git a/src/SharpEmu.Libs/Gpu/Rendering/ParallelProgramPrefetch.cs b/src/SharpEmu.Libs/Gpu/Rendering/ParallelProgramPrefetch.cs index 17043a16b..2dbcd2465 100644 --- a/src/SharpEmu.Libs/Gpu/Rendering/ParallelProgramPrefetch.cs +++ b/src/SharpEmu.Libs/Gpu/Rendering/ParallelProgramPrefetch.cs @@ -666,6 +666,7 @@ private GraphicsPrograms VerifyLookahead(Job job, RegisterBanks banks, in Graphi $"differences=[{SharpEmu.Libs.Gpu.Pipelines.GraphicsProgramsComparer.Differences(job.Programs!, resolved)}] " + $"ahead=[{SharpEmu.Libs.Gpu.Pipelines.GraphicsProgramsComparer.Describe(job.Programs!)}] " + $"worker=[{SharpEmu.Libs.Gpu.Pipelines.GraphicsProgramsComparer.Describe(resolved)}] worker_again={stable} " + + $"ahead_vs_worker=[{SharpEmu.Libs.Gpu.Pipelines.GraphicsProgramsComparer.DescribeStages(job.Programs!, resolved)}] " + $"looked_over=[{DescribeLookedOver(job.ExecutedAtStart, job.FullGate)}] " + $"last_dispatch_effect={Volatile.Read(ref _lastDispatchEffect)} last_collect_effect={Volatile.Read(ref _lastCollectEffect)} " + $"state_ahead=[{job.ResolveState}] state_now=[{_executor.DescribeProgramState()}]."); diff --git a/src/SharpEmu.Libs/Gpu/Scheduling/GpuFatal.cs b/src/SharpEmu.Libs/Gpu/Scheduling/GpuFatal.cs index b6627c238..48ab30362 100644 --- a/src/SharpEmu.Libs/Gpu/Scheduling/GpuFatal.cs +++ b/src/SharpEmu.Libs/Gpu/Scheduling/GpuFatal.cs @@ -64,6 +64,24 @@ public static T Speculatively(Func work) /// Backend contract. public static Exception Fatal(string message) => Fatal(message, null); + // Verify mismatches (a verify mode found a fast path handing out other results than a full resolution) raised on a + // speculative thread: that work is abandoned like any other, so each is counted here as well, for the prefetch PERF + // line (abandoned_verify=), instead of disappearing among the plain abandons. + private static long _speculativeVerifyFailures; + + public static long TakeSpeculativeVerifyFailures() => Interlocked.Exchange(ref _speculativeVerifyFailures, 0); + + // Fatal for a verify mismatch: on a speculative thread also counted (TakeSpeculativeVerifyFailures). + public static Exception VerifyFailed(string message) + { + if (ThrowOnFatal) + { + Interlocked.Increment(ref _speculativeVerifyFailures); + } + + return Fatal(message, null); + } + /// Reports a GPU failure without losing its original cause. public static Exception Fatal(string message, Exception? innerException) { diff --git a/src/SharpEmu.ShaderCompiler/Resources/ResourceMaterializer.cs b/src/SharpEmu.ShaderCompiler/Resources/ResourceMaterializer.cs index 86686c306..963209321 100644 --- a/src/SharpEmu.ShaderCompiler/Resources/ResourceMaterializer.cs +++ b/src/SharpEmu.ShaderCompiler/Resources/ResourceMaterializer.cs @@ -483,6 +483,76 @@ public static string TakeReadProofReport() => FormattableString.Invariant( // The proof a fast snapshot's origin holds (tests). internal static MaterializationProgram.ReadProof? ReadProofOf(ResourceSnapshot snapshot) => (snapshot.Origin as FastOrigin)?.Proof; + // Diagnostics: the specialization a fast snapshot was materialized with (the permutation's key), else null. + public static ResourceSpecialization? SpecializationOf(ResourceSnapshot snapshot) => (snapshot.Origin as FastOrigin)?.Specialization; + + // Diagnostics: every guest word a fast snapshot's program reads when evaluated now with the snapshot's own draw values + // (word reads only, no resident or clean shortcuts), in read order; null when the snapshot is not a fast one or the + // evaluation threw (an abandoned read on a resolving thread included). + public static List<(ulong Address, uint Word)>? RecordWordReads(ResourceSnapshot snapshot) + { + if (snapshot.Origin is not FastOrigin { Plan.MaterializationProgram: not null } origin) + { + return null; + } + + var reads = new List<(ulong Address, uint Word)>(); + var reader = origin.Inputs.ReadMemory; + bool Recording(ulong address, out uint word) + { + word = 0; + if (reader is null || !reader(address, out word)) + { + return false; + } + + reads.Add((address, word)); + return true; + } + + var inputs = new ResourceRuntimeInputs + { + ReadMemory = Recording, + ReadCleanMemory = origin.Inputs.ReadCleanMemory, + UserData = origin.UserData, + ShaderBase = origin.ShaderBase, + ComputeState = origin.ComputeState, + }; + try + { + EvaluateInto(origin.Plan, inputs, new MaterializationProgram.Output()); + return reads; + } + catch (Exception) + { + return null; + } + } + + // Diagnostics: the guest address flattened-table word flatOffset of a fast snapshot is loaded from, evaluated now with + // the snapshot's own draw values and readers; null when no table read fills that word, the snapshot is not a fast + // one, or the address cannot be evaluated (an abandoned read on a resolving thread included). + public static ulong? TableWordAddress(ResourceSnapshot snapshot, int flatOffset) + { + if (snapshot.Origin is not FastOrigin origin) + { + return null; + } + + var inputs = origin.Inputs.CopyReaders(); + inputs.UserData = origin.UserData; + inputs.ShaderBase = origin.ShaderBase; + inputs.ComputeState = origin.ComputeState; + try + { + return RuntimeValueEvaluator.TableWordAddress(origin.Plan, inputs, flatOffset); + } + catch (Exception) + { + return null; + } + } + // The test seam for verify: puts a proof on a fast snapshot's origin as if its evaluation had recorded it. internal static void SetReadProofForTest(ResourceSnapshot snapshot, MaterializationProgram.ReadProof? proof) => ((FastOrigin)snapshot.Origin!).Proof = proof; diff --git a/src/SharpEmu.ShaderCompiler/Resources/ResourceSpecialization.cs b/src/SharpEmu.ShaderCompiler/Resources/ResourceSpecialization.cs index 70d52ab03..a0fe5ad92 100644 --- a/src/SharpEmu.ShaderCompiler/Resources/ResourceSpecialization.cs +++ b/src/SharpEmu.ShaderCompiler/Resources/ResourceSpecialization.cs @@ -81,6 +81,33 @@ public bool Equals(ResourceSpecialization? other) => public override bool Equals(object? obj) => Equals(obj as ResourceSpecialization); + // Diagnostics: the first list entry that differs from other's, with both values, or null when Equals holds. + public string? DifferenceFrom(ResourceSpecialization other) + { + static string? First(string name, List left, List right) + { + for (var index = 0; index < Math.Max(left.Count, right.Count); index++) + { + if (index >= left.Count || index >= right.Count || !EqualityComparer.Default.Equals(left[index], right[index])) + { + var a = index < left.Count ? left[index]?.ToString() : "none"; + var b = index < right.Count ? right[index]?.ToString() : "none"; + return $"{name}[{index}] {a} vs {b}"; + } + } + + return null; + } + + if (Equals(other)) return null; + if (BaseBufferCount != other.BaseBufferCount) return $"base_buffers {BaseBufferCount} vs {other.BaseBufferCount}"; + return First("buffers", Buffers, other.Buffers) ?? First("images", Images, other.Images) ?? + First("candidate_tables", BufferCandidateTables, other.BufferCandidateTables) ?? + First("image_groups", ImageDescriptorGroups, other.ImageDescriptorGroups) ?? + First("sampler_groups", SamplerDescriptorGroups, other.SamplerDescriptorGroups) ?? + First("samplers", Samplers, other.Samplers) ?? "unequal"; + } + public override int GetHashCode() { var hash = new HashCode(); diff --git a/src/SharpEmu.ShaderCompiler/Resources/RuntimeValueEvaluator.cs b/src/SharpEmu.ShaderCompiler/Resources/RuntimeValueEvaluator.cs index 7d1124264..afa78838f 100644 --- a/src/SharpEmu.ShaderCompiler/Resources/RuntimeValueEvaluator.cs +++ b/src/SharpEmu.ShaderCompiler/Resources/RuntimeValueEvaluator.cs @@ -431,10 +431,21 @@ private bool EvaluateTableRead(int index, out uint result) // shader learns it as a device load. This read still waits, the next plan does not. private void LearnPendingDataSlot(int slot, int[] memoryIndices) { + if (TryTableReadAddress(slot, out var address) && _inputs.DataWritePending!(address)) + { + DeviceDataLoads.Learn(_plan.Hash, memoryIndices); + } + } + + // The guest address a table read (plan.TableReads[slot]) loads its dword from, evaluated with these inputs; false when + // the read is not a plain memory load or its pointer cannot be evaluated. + private bool TryTableReadAddress(int slot, out ulong address) + { + address = 0; var value = _plan.TableReads[slot].Value; if (value.MemoryIndex >= _plan.Memory.Count || value.Operands.Length < 2) { - return; + return false; } var handle = value.Operands[0]; @@ -443,16 +454,36 @@ private void LearnPendingDataSlot(int slot, int[] memoryIndices) !EvaluateWide(handle.Operands[1], out var high) || !Operand(value, 1, out var offset)) { - return; + return false; } var baseAddress = ((high << 32) | (uint)low) & AddressMask; - if (ResolveRawAddress(value.Kind, baseAddress, high, 0, (int)_plan.Memory[value.MemoryIndex].Offset, (uint)offset, - out var address) == RawAddress.Read && - _inputs.DataWritePending!(address)) + return ResolveRawAddress(value.Kind, baseAddress, high, 0, (int)_plan.Memory[value.MemoryIndex].Offset, (uint)offset, + out address) == RawAddress.Read; + } + + // Diagnostics: the guest address of the table read that fills flattened-table word flatOffset, or null when no table + // read fills it (a written range's or a mapping's word) or its address cannot be evaluated with these inputs. + internal static ulong? TableWordAddress(ShaderResourcePlan plan, ResourceRuntimeInputs inputs, int flatOffset) + { + var slot = -1; + for (var index = 0; index < plan.TableReads.Count; index++) { - DeviceDataLoads.Learn(_plan.Hash, memoryIndices); + if (plan.TableReads[index].FlatOffset == (uint)flatOffset) + { + slot = index; + break; + } } + + if (slot < 0) + { + return null; + } + + using var scratch = RuntimeEvaluationScratch.Rent(); + var evaluator = new RuntimeValueEvaluator(scratch, plan, inputs); + return evaluator.TryTableReadAddress(slot, out var address) ? address : null; } private static bool AddSignedAddress(ulong baseAddress, long offset, out ulong result) diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.ConcurrentResolve.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.ConcurrentResolve.cs index 303d3d2dc..31a11b948 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.ConcurrentResolve.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.ConcurrentResolve.cs @@ -170,7 +170,7 @@ private string FormatPrefetchCounters() $"ownership={computeRefused[(int)ParallelProgramPrefetch.ComputeRefusal.Ownership]},effects={computeRefused[(int)ParallelProgramPrefetch.ComputeRefusal.Effects]}) " + $"write_log_refusals={Interlocked.Exchange(ref _writeLogRefusals, 0)} dispatch_wait_ms={computeWaitMs.ToString("F1", culture)} " + $"dispatch_saved_ms={computeSavedMs.ToString("F1", culture)}"; - return $"resolved={resolved} abandoned={abandoned} abandoned_by=({TakeAbandonCauses()}) taken={taken} refused={refused} drains={drains} drained={drained} deferred_barriers={deferredBarriers} operand_reads_kept={operandReadsKept} " + + return $"resolved={resolved} abandoned={abandoned} abandoned_by=({TakeAbandonCauses()}) abandoned_verify={GpuFatal.TakeSpeculativeVerifyFailures()} taken={taken} refused={refused} drains={drains} drained={drained} deferred_barriers={deferredBarriers} operand_reads_kept={operandReadsKept} " + $"wait_ms={waitMs.ToString("F1", culture)} resolve_ms={prefetch.TakeResolveMilliseconds().ToString("F1", culture)} " + $"caller_jobs={callerResolves} caller_ms={callerMs.ToString("F1", culture)} claim_steals={prefetch.TakeClaimSteals()} {prefetch.TakeResolverReport()}{dispatches}{FormatPacketCounters()} {own} {TakeOwnerTestCounters()}{TakeDrainCallers()}"; } diff --git a/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/KeptStageInputsTests.ResolveMemo.cs b/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/KeptStageInputsTests.ResolveMemo.cs index 973b797d5..9859df7d0 100644 --- a/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/KeptStageInputsTests.ResolveMemo.cs +++ b/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/KeptStageInputsTests.ResolveMemo.cs @@ -5,6 +5,7 @@ using SharpEmu.Libs.Gpu.GpuCommands.Registers; using SharpEmu.Libs.Gpu.Pipelines; using SharpEmu.Libs.Gpu.Rendering; +using SharpEmu.Libs.Gpu.Scheduling; using SharpEmu.ShaderCompiler.Resources; using Xunit; @@ -238,6 +239,84 @@ public void ResolveMemo_OffResolvesAsTheKeptProgramsDid() Assert.NotSame(cached, Programs(cache, pixelActive: true)); } + // Verify on a thread beside the guest: a resolution reads the descriptor once (the hit's revalidation, the full + // resolution, the re-check and the second full resolution each read it in turn), and a guest store between two of + // those reads makes the full resolution differ from a hit that was current when it was made. The answers of the + // descriptor's first word, read after the two draws that store and first verify the entry (reads 1-3): the hit's + // revalidation (4), its full resolution (5), the difference's report reading where the words lie (6), the re-check + // (7), the second full resolution (8). + private (GraphicsPrograms Hit, GraphicsPrograms Third, string Report) VerifyWithDescriptorReads(Func moved) + { + var cache = MemoCache(); + UseLoadingPixelProgram(Descriptor); + var hit = Programs(cache, pixelActive: true); + Assert.Same(hit, Programs(cache, pixelActive: true)); + Report(); + var reads = 0; + _guest.Host.WordRead = (address, word) => address == Descriptor && moved(++reads + 3) ? word + 0x100 : word; + try + { + var third = Programs(cache, pixelActive: true); + return (hit, third, Report()); + } + finally + { + _guest.Host.WordRead = null; + } + } + + // The store lands after the hit read its words and stays: the re-check misses, so the difference is a race (counted), + // not a mismatch, and the draw takes the full resolution's programs, which read the store. + [Fact] + public void ResolveMemo_VerifyCountsAStoreBetweenTheHitAndTheFullResolutionAsARace() + { + var failed = VerifyFailedCount(); + var (hit, third, report) = VerifyWithDescriptorReads(read => read >= 5); + Assert.Contains("verify_raced=(changed=1,came_and_went=0)", report); + Assert.Equal(failed, VerifyFailedCount()); + Assert.NotSame(hit, third); + Assert.Contains(third.PixelInput.Stage.Resources.Buffers, words => words[0] == unchecked((uint)(StreamBase + 0x100))); + } + + // The store is seen by the full resolution only: the re-check holds and a second full resolution agrees with the hit. + [Fact] + public void ResolveMemo_VerifyCountsADifferenceThatCameAndWentAsARace() + { + var failed = VerifyFailedCount(); + var (hit, third, report) = VerifyWithDescriptorReads(read => read == 5); + Assert.Contains("verify_raced=(changed=0,came_and_went=1)", report); + Assert.Equal(failed, VerifyFailedCount()); + Assert.Same(hit, third); + } + + // A difference that outlives the re-check (the hit still revalidates, a second full resolution still differs) is a + // mismatch: stopped as before, and on a speculative thread counted apart from plain abandons. Here the store is seen by + // every read but the re-check's (7), as a writer that does not hold still would be. + [Fact] + public void ResolveMemo_VerifyStopsWhenTheHitStillRevalidatesAndTheDifferenceStays() + { + var failed = VerifyFailedCount(); + GpuFatal.TakeSpeculativeVerifyFailures(); + var thrown = Assert.Throws(() => + GpuFatal.Speculatively(() => VerifyWithDescriptorReads(read => read is >= 5 and not 7))); + Assert.Contains("verify mismatch field=pixel.buffers", thrown.Message); + Assert.Contains("recheck=current again=pixel.buffers", thrown.Message); + // The report names the permutation keys and where the differing words are read from. + Assert.Matches("pixel=\\[same_program=True specialization=(same_object|equal) words=buffers\\[0\\] ", thrown.Message); + Assert.Contains($"read_at=w0@0x{Descriptor:X}", thrown.Message); + var counted = VerifyFailedCount(); + GraphicsResolveMemo.ForgetVerifyFailureForTest(); + Assert.Equal(failed + 1, counted); + Assert.Equal(1, GpuFatal.TakeSpeculativeVerifyFailures()); + } + + private static long VerifyFailedCount() + { + var report = GraphicsResolveMemo.TakeReport(); + var at = report.IndexOf("verify_failed=", StringComparison.Ordinal) + "verify_failed=".Length; + return long.Parse(report[at..report.IndexOf(')', at)], System.Globalization.CultureInfo.InvariantCulture); + } + // The comparer behind verify names every field of what a resolution hands out: a field added later fails here // until the comparer (and the memo's key, if the resolution reads something new for it) covers it. [Fact] diff --git a/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/PipelineTestSupport.cs b/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/PipelineTestSupport.cs index 85b465e7b..ab8544b0a 100644 --- a/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/PipelineTestSupport.cs +++ b/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/PipelineTestSupport.cs @@ -102,9 +102,17 @@ public bool TryReadGuestWord(ulong address, out uint word) } word = BinaryPrimitives.ReadUInt32LittleEndian(bytes); + if (WordRead is { } transform) + { + word = transform(address, word); + } + return true; } + // The word a read answers in place of the one in memory, as a guest store landing between two reads would. + public Func? WordRead { get; set; } + // Addresses whose clean reads are refused, as for bytes a GPU image or buffer may still own. public Func? RefuseCleanRead { get; set; } From 9ad62cc4aff225a4d9c9b99113df0190b5ab8711 Mon Sep 17 00:00:00 2001 From: kuba Date: Sun, 15 Nov 2026 18:29:48 +0000 Subject: [PATCH 088/178] [GPU] Refuse a prefetched draw resolution made before the program cache moved A job resolved before a re-plan replaced a program entry (or a device load was learned, or the vertex tables changed) holds the entry a lookup made at the draw would no longer find. The look-ahead verify stopped on exactly that at world load in Demon's Souls (content_epoch 52 against 53, vertex program 0x210 against 0x211). The take now compares the stamp the resolution began under and refuses on a difference (draw_lookahead refused replanned=, replanned_all= for every job). --- .../Gpu/Pipelines/ShaderPipelineCache.cs | 2 ++ .../Gpu/Rendering/IShaderPipelineProvider.cs | 8 +++++++ .../Gpu/Rendering/ParallelProgramPrefetch.cs | 20 +++++++++++++++-- .../Gpu/Rendering/RenderExecutor.Prefetch.cs | 2 ++ ...rallelProgramPrefetchDrawLookaheadTests.cs | 22 +++++++++++++++++++ .../Rendering/RenderExecutorTestSupport.cs | 3 +++ 6 files changed, 55 insertions(+), 2 deletions(-) diff --git a/src/SharpEmu.Libs/Gpu/Pipelines/ShaderPipelineCache.cs b/src/SharpEmu.Libs/Gpu/Pipelines/ShaderPipelineCache.cs index a263b3132..1c121e48c 100644 --- a/src/SharpEmu.Libs/Gpu/Pipelines/ShaderPipelineCache.cs +++ b/src/SharpEmu.Libs/Gpu/Pipelines/ShaderPipelineCache.cs @@ -341,6 +341,8 @@ public GraphicsPrograms GetGraphicsPrograms( } } + public ProgramStateStamp ProgramState => new(_programs.ContentEpoch, DeviceDataLoads.Generation, _vertexTables.Generation); + public string DescribeProgramState() => $"content_epoch={_programs.ContentEpoch} device_data={DeviceDataLoads.Generation} " + $"registrations={ShaderHeaderRegistry.Registrations} tables={_vertexTables.Generation} linked={_programs.LinkedLookups}"; diff --git a/src/SharpEmu.Libs/Gpu/Rendering/IShaderPipelineProvider.cs b/src/SharpEmu.Libs/Gpu/Rendering/IShaderPipelineProvider.cs index 05140bf67..71f9ea45d 100644 --- a/src/SharpEmu.Libs/Gpu/Rendering/IShaderPipelineProvider.cs +++ b/src/SharpEmu.Libs/Gpu/Rendering/IShaderPipelineProvider.cs @@ -168,6 +168,11 @@ public interface IShaderPipelineProvider // learned device loads, header registrations...), for the look-ahead verify's fatal (ParallelProgramPrefetch). string DescribeProgramState() => string.Empty; + // The part of that state that decides which program entry a lookup finds: it moves when an entry is replaced + // (a re-plan) or refused, when a device data load is learned and when the vertex tables change. A resolution made + // under another stamp may hold the entry a lookup made now would not find (ParallelProgramPrefetch refuses it). + ProgramStateStamp ProgramState => default; + // Optional capture of rejected stage inputs; it never admits or executes the draw. void RecordUnsupportedGraphics(VertexStageRegisters vertex, ContextRegisters context) { } @@ -337,3 +342,6 @@ bool TryCreateComputePipeline(ComputeInputInfo input, ShaderProgram program, out return null; } } + +/// See . +public readonly record struct ProgramStateStamp(long ContentEpoch, long DeviceData, long Tables); diff --git a/src/SharpEmu.Libs/Gpu/Rendering/ParallelProgramPrefetch.cs b/src/SharpEmu.Libs/Gpu/Rendering/ParallelProgramPrefetch.cs index 2dbcd2465..9c97b658b 100644 --- a/src/SharpEmu.Libs/Gpu/Rendering/ParallelProgramPrefetch.cs +++ b/src/SharpEmu.Libs/Gpu/Rendering/ParallelProgramPrefetch.cs @@ -46,6 +46,9 @@ public sealed class Job(RegisterBanks banks, long gate, bool indexed = false, in internal long LastCollectGate; // =verify: the program cache state the resolution ended under (IShaderPipelineProvider.DescribeProgramState). internal string? ResolveState; + // The program cache stamp the resolution began under (IShaderPipelineProvider.ProgramState): a take under + // another one is refused, since a lookup made now may find a replaced entry (replanned). + internal ProgramStateStamp ProgramState; } /// @@ -107,11 +110,16 @@ public enum DrawLookaheadRefusal : byte Ownership, // A collector call it was resolved ahead of did something a resolution may have read (NoteCollect). CollectEffects, + // The program cache replaced an entry, learned a device load or changed the vertex tables since the + // resolution began (Job.ProgramState); counted for every job, looked ahead or not (replanned=). + Replanned, Count, } - private static readonly string[] DrawLookaheadRefusalNames = ["abandoned", "inputs", "effects", "ownership", "gc_effects"]; + private static readonly string[] DrawLookaheadRefusalNames = ["abandoned", "inputs", "effects", "ownership", "gc_effects", "replanned"]; private long _lookaheadJobs, _lookaheadTaken, _lookaheadVerified; + // Draw jobs of any kind refused because the program cache moved since they began (DrawLookaheadRefusal.Replanned). + private long _replannedRefusals; private readonly long[] _lookaheadRefusals = new long[(int)DrawLookaheadRefusal.Count]; // The subset of the look-aheads above that began before a collector call ran (over_gc), and the collector calls @@ -167,7 +175,8 @@ private string TakeDrawLookaheadReport() return builder.Append("),verified=").Append(verified) .Append(",gc=(jobs=").Append(collect.Jobs).Append(",taken=").Append(collect.Taken).Append(",refused=").Append(collect.Refused) - .Append(",calls=").Append(collect.Calls).Append(",effects=").Append(collect.Effects).Append("))").ToString(); + .Append(",calls=").Append(collect.Calls).Append(",effects=").Append(collect.Effects) + .Append("),replanned_all=").Append(Interlocked.Exchange(ref _replannedRefusals, 0)).Append(')').ToString(); } // The kind of a gated non-draw item, as the command thread queues it (NoteGateItem): what the draws after it wait for. @@ -604,6 +613,7 @@ public bool TryTakeGraphics(RegisterBanks banks, in GraphicsProgramInputs inputs } var refusal = !job.Inputs.Equals(inputs) ? DrawLookaheadRefusal.Inputs + : job.ProgramState != _executor.ProgramState ? DrawLookaheadRefusal.Replanned : !lookedAhead ? (_concurrent.IsStillCurrent(job.Assumptions!) ? DrawLookaheadRefusal.Count : DrawLookaheadRefusal.Ownership) // A collector call or a dispatch that ran after the resolution began (gate above ExecutedAtStart) noted an effect. : Volatile.Read(ref _lastCollectEffect) >= job.ExecutedAtStart ? DrawLookaheadRefusal.CollectEffects @@ -622,6 +632,11 @@ public bool TryTakeGraphics(RegisterBanks banks, in GraphicsProgramInputs inputs } } + if (refusal == DrawLookaheadRefusal.Replanned) + { + Interlocked.Increment(ref _replannedRefusals); + } + Interlocked.Increment(ref _refusedCount); return false; } @@ -1137,6 +1152,7 @@ private void ResolveCore(Job job) job.Inputs = RenderExecutor.ProgramInputsOf(job.Banks, _host.FormatSupport, WorkerScratch.Enabled ? _fatal : _host.Fatal, job.Indexed, job.StartInstanceUserData); + job.ProgramState = _executor.ProgramState; job.Programs = _executor.ResolveGraphicsPrograms(job.Banks, in job.Inputs); if (LookaheadMode == DrawLookaheadMode.Verify) { diff --git a/src/SharpEmu.Libs/Gpu/Rendering/RenderExecutor.Prefetch.cs b/src/SharpEmu.Libs/Gpu/Rendering/RenderExecutor.Prefetch.cs index ae1655e84..1d54ec2e0 100644 --- a/src/SharpEmu.Libs/Gpu/Rendering/RenderExecutor.Prefetch.cs +++ b/src/SharpEmu.Libs/Gpu/Rendering/RenderExecutor.Prefetch.cs @@ -184,6 +184,8 @@ public static GraphicsProgramInputs ProgramInputsOf(RegisterBanks banks, IImageF public string DescribeProgramState() => _pipelines.DescribeProgramState(); + public ProgramStateStamp ProgramState => _pipelines.ProgramState; + // The programs of a draw with these banks and inputs, as ResolveShaderPrograms resolves them. public GraphicsPrograms ResolveGraphicsPrograms(RegisterBanks banks, in GraphicsProgramInputs inputs) { diff --git a/tests/SharpEmu.Libs.Tests/Gpu/Rendering/ParallelProgramPrefetchDrawLookaheadTests.cs b/tests/SharpEmu.Libs.Tests/Gpu/Rendering/ParallelProgramPrefetchDrawLookaheadTests.cs index 9c1921005..8d0578921 100644 --- a/tests/SharpEmu.Libs.Tests/Gpu/Rendering/ParallelProgramPrefetchDrawLookaheadTests.cs +++ b/tests/SharpEmu.Libs.Tests/Gpu/Rendering/ParallelProgramPrefetchDrawLookaheadTests.cs @@ -121,6 +121,28 @@ public void ADrawWhoseAnswersChangedAcrossTheDispatchesIsRefused() Assert.Equal(1, _prefetch.TakeCounters().Refused); } + // The program cache replaced an entry after the resolution began: a lookup made now may find another program, so + // the job is refused whether it looked ahead or not, and one resolved under the new stamp is taken. + [Fact] + public void AJobResolvedBeforeTheProgramCacheMovedIsRefused() + { + var banks = Banks().Snapshot(); + var ahead = Resolved(banks, gate: 0, fullGate: 1); + _prefetch.AdvanceGate(1); + _pipelines.ProgramState = new ProgramStateStamp(ContentEpoch: 1, DeviceData: 0, Tables: 0); + Assert.False(Take(banks, ahead)); + Assert.Equal(1, Counters().Refused[(int)ParallelProgramPrefetch.DrawLookaheadRefusal.Replanned]); + Assert.Equal(0, _concurrent.CrossChecks); + + var inOrder = Resolved(banks, gate: 1, fullGate: 1); + _pipelines.ProgramState = new ProgramStateStamp(ContentEpoch: 1, DeviceData: 1, Tables: 0); + Assert.False(Take(banks, inOrder)); + Assert.Equal(2, _prefetch.TakeCounters().Refused); + + var current = Resolved(banks, gate: 1, fullGate: 1); + Assert.True(Take(banks, current)); + } + [Fact] public void ADispatchThatDidMoreThanEncodeRefusesTheDrawsResolvedAheadOfItOnly() { diff --git a/tests/SharpEmu.Libs.Tests/Gpu/Rendering/RenderExecutorTestSupport.cs b/tests/SharpEmu.Libs.Tests/Gpu/Rendering/RenderExecutorTestSupport.cs index 16ce4e9b8..65d8a22a1 100644 --- a/tests/SharpEmu.Libs.Tests/Gpu/Rendering/RenderExecutorTestSupport.cs +++ b/tests/SharpEmu.Libs.Tests/Gpu/Rendering/RenderExecutorTestSupport.cs @@ -586,6 +586,9 @@ internal sealed class FakePipelineProvider : IShaderPipelineProvider internal Action? BeforeGraphicsResolve { get; set; } public GraphicsPrograms Graphics { get; set; } = RenderExecutorFixtures.Programs(); + // What the program cache's stamp reads (IShaderPipelineProvider.ProgramState); a test moves it as a re-plan does. + public ProgramStateStamp ProgramState { get; set; } + // What a resolution with the pixel stage off returns, when it differs from Graphics. public GraphicsPrograms? GraphicsWithoutPixel { get; set; } From 6c363d03cba770b55889ae10bcac5aad54c8405d Mon Sep 17 00:00:00 2001 From: kuba Date: Sun, 15 Nov 2026 19:01:50 +0000 Subject: [PATCH 089/178] [GPU] Add a look-ahead census mode that names the reads and owners where a job and the worker differ SHARPEMU_PREFETCH_DRAW_LOOKAHEAD=census re-resolves every taken draw job on the worker, uses its own result and counts differences per group (gated, ahead). SHARPEMU_PREFETCH_CENSUS_PS= also records that pixel stage's materialization reads (clean reads included, refused ones marked) on both threads and prints them side by side, with the host's owner, overlay, image and pending-write state of the refused clean words. --- .../Gpu/Rendering/IRenderHost.cs | 4 + .../Gpu/Rendering/ParallelProgramPrefetch.cs | 165 +++++++++++++++++- .../Gpu/Rendering/RenderExecutor.Prefetch.cs | 2 + .../Resources/ResourceMaterializer.cs | 27 ++- .../SharpEmu.Gpu.Metal/V2/MetalImageCache.cs | 25 +++ .../V2/MetalRenderHost.ConcurrentResolve.cs | 8 + .../SharpEmu.Gpu.Metal/V2/MetalRenderHost.cs | 53 ++++++ 7 files changed, 277 insertions(+), 7 deletions(-) diff --git a/src/SharpEmu.Libs/Gpu/Rendering/IRenderHost.cs b/src/SharpEmu.Libs/Gpu/Rendering/IRenderHost.cs index 642902e2d..ade535e3e 100644 --- a/src/SharpEmu.Libs/Gpu/Rendering/IRenderHost.cs +++ b/src/SharpEmu.Libs/Gpu/Rendering/IRenderHost.cs @@ -97,6 +97,10 @@ public readonly record struct DrawScopeToken(long Scope, ulong Lookups, long Met public interface IRenderHost { bool TryCopyImage(in ImageRequest source, in ImageRequest destination) => false; + + // Diagnostics: who owns or last waited for these guest bytes on the host (ParallelProgramPrefetch census). + string DescribeGuestRangeForDiagnostics(ulong address, ulong size) => "unavailable"; + int BeginImageSnapshot(IPreparedBindings? pixelBindings) => 0; int BeginComputeImageSnapshot(IPreparedBindings bindings) => 0; diff --git a/src/SharpEmu.Libs/Gpu/Rendering/ParallelProgramPrefetch.cs b/src/SharpEmu.Libs/Gpu/Rendering/ParallelProgramPrefetch.cs index 9c97b658b..1f0a5c39f 100644 --- a/src/SharpEmu.Libs/Gpu/Rendering/ParallelProgramPrefetch.cs +++ b/src/SharpEmu.Libs/Gpu/Rendering/ParallelProgramPrefetch.cs @@ -41,6 +41,13 @@ public sealed class Job(RegisterBanks banks, long gate, bool indexed = false, in // all FullGate items ran looked ahead of the ones that had not, and its take checks it against them. internal long FullGate; internal long ExecutedAtStart; + // =verify, =census: when the resolution ended (Stopwatch ticks). + internal long ResolvedAt; + // =census with SHARPEMU_PREFETCH_CENSUS_PS: the pixel stage's materialization reads, in order, as the + // resolving thread read them right after its resolution. + internal List<(ulong Address, uint Word, bool Clean, bool Refused)>? CensusReads; + // What the host said of the refused clean reads among them, at the resolution. + internal string? CensusRefusals; // The gate number of the last collector call (GateItemKind.Collect) queued before the job: above ExecutedAtStart, // the resolution looked ahead of it (draw_lookahead over_gc). internal long LastCollectGate; @@ -70,6 +77,10 @@ public enum DrawLookaheadMode : byte Off, On, Verify, + // =census: a measurement, not a check. The worker resolves every taken draw job again, looked ahead or not, uses + // its own result, and counts the jobs whose earlier resolution differs, with the time each stood between its + // resolution and its take: whether look-aheads differ more often than jobs that waited for their gate. + Census, } public static readonly DrawLookaheadMode DrawLookahead = @@ -79,12 +90,15 @@ public enum DrawLookaheadMode : byte { "0" => DrawLookaheadMode.Off, "verify" => DrawLookaheadMode.Verify, + "census" => DrawLookaheadMode.Census, _ => Environment.GetEnvironmentVariable("SHARPEMU_PERF_VERIFY") == "1" ? DrawLookaheadMode.Verify : DrawLookaheadMode.On, }; // The mode this prefetch checks takes in (tests set Verify on one instance). internal DrawLookaheadMode LookaheadMode { get; set; } = DrawLookahead; + private bool RecordsForVerify => LookaheadMode is DrawLookaheadMode.Verify or DrawLookaheadMode.Census; + // The command thread queues a collector call (GateItemKind.Collect) without moving the dispatch gate: the draws and // dispatches after it gate on the items before it, and their takes check NoteCollect. Only where draws look ahead // (the mode, and a host whose cross-dispatch check covers it), so SHARPEMU_PREFETCH_DRAW_LOOKAHEAD=0 gates again; @@ -176,7 +190,17 @@ private string TakeDrawLookaheadReport() return builder.Append("),verified=").Append(verified) .Append(",gc=(jobs=").Append(collect.Jobs).Append(",taken=").Append(collect.Taken).Append(",refused=").Append(collect.Refused) .Append(",calls=").Append(collect.Calls).Append(",effects=").Append(collect.Effects) - .Append("),replanned_all=").Append(Interlocked.Exchange(ref _replannedRefusals, 0)).Append(')').ToString(); + .Append("),replanned_all=").Append(Interlocked.Exchange(ref _replannedRefusals, 0)) + .Append(LookaheadMode == DrawLookaheadMode.Census ? TakeCensusReport() : string.Empty).Append(')').ToString(); + } + + // census=(gated=resolved/differed/stood_ms,ahead=resolved/differed/stood_ms) + private string TakeCensusReport() + { + string Group(int group) => + $"{Interlocked.Exchange(ref _censusResolved[group], 0)}/{Interlocked.Exchange(ref _censusDiffered[group], 0)}/" + + $"{Interlocked.Exchange(ref _censusStoodTicks[group], 0) * 1000 / System.Diagnostics.Stopwatch.Frequency}"; + return $",census=(gated={Group(0)},ahead={Group(1)})"; } // The kind of a gated non-draw item, as the command thread queues it (NoteGateItem): what the draws after it wait for. @@ -344,7 +368,7 @@ public long[] TakeProviderRefusals() public void NoteDispatchProgram(ComputeProgram program) { - if (LookaheadMode == DrawLookaheadMode.Verify) + if (RecordsForVerify) { _gateDispatchHashes[(Volatile.Read(ref _executedGate) + 1) & (GateKindRing - 1)] = program.Input.Stage.Program?.Hash ?? 0; } @@ -657,9 +681,141 @@ public bool TryTakeGraphics(RegisterBanks banks, in GraphicsProgramInputs inputs } } + if (LookaheadMode == DrawLookaheadMode.Census) + { + programs = TakeCensus(job, banks, in inputs, lookedAhead); + } + return true; } + // =census counters, [0] jobs that waited for their gate, [1] look-aheads: taken jobs resolved again, those that + // differed, and the ticks they stood between resolution and take. + private readonly long[] _censusResolved = new long[2], _censusDiffered = new long[2], _censusStoodTicks = new long[2]; + private readonly int[] _censusReports = new int[2]; + private const int MaximumCensusReports = 8; + + // SHARPEMU_PREFETCH_CENSUS_PS=: the census records that pixel stage's reads on both threads. + private static readonly ulong CensusPixelHash = + ulong.TryParse(Environment.GetEnvironmentVariable("SHARPEMU_PREFETCH_CENSUS_PS")?.Replace("0x", "", StringComparison.OrdinalIgnoreCase), + System.Globalization.NumberStyles.HexNumber, System.Globalization.CultureInfo.InvariantCulture, out var hash) ? hash : 0; + + private List<(ulong Address, uint Word, bool Clean, bool Refused)>? CensusReadsOf(GraphicsPrograms? programs) => + LookaheadMode == DrawLookaheadMode.Census && CensusPixelHash != 0 && + programs is { Available: true } && programs.PixelInput.Stage.Program?.Hash == CensusPixelHash + ? SharpEmu.ShaderCompiler.Resources.ResourceMaterializer.RecordReads(programs.PixelInput.Stage.Resources, clean: true) + : null; + + private string? DescribeRefusedCleanReads(List<(ulong Address, uint Word, bool Clean, bool Refused)>? reads) + { + if (reads is null) + { + return null; + } + + var described = new List(); + foreach (var read in reads) + { + if (read.Refused && described.Count < 3) + { + described.Add($"0x{read.Address:X}:({_executor.DescribeGuestRange(read.Address, sizeof(uint))})"); + } + } + + return string.Join(" ", described); + } + + // The reads of the job (resolving thread) and the worker side by side where they differ, by position, and what the + // host knows of the first differing addresses. + private string DescribeCensusReads(Job job, List<(ulong Address, uint Word, bool Clean, bool Refused)>? worker, + List<(ulong Address, uint Word, bool Clean, bool Refused)>? again) + { + if (job.CensusReads is not { } ahead || worker is null) + { + return $"reads=unavailable(job={job.CensusReads?.Count.ToString() ?? "null"},worker={worker?.Count.ToString() ?? "null"})"; + } + + static string Read((ulong Address, uint Word, bool Clean, bool Refused) read) => + $"0x{read.Address:X}{(read.Clean ? "c" : "")}{(read.Refused ? "!" : "")}={read.Word:X8}"; + + var builder = new System.Text.StringBuilder(); + builder.Append($"reads=(job={ahead.Count},worker={worker.Count},again={again?.Count.ToString() ?? "null"}) "); + var listed = 0; + var described = new List(); + for (var index = 0; index < Math.Max(ahead.Count, worker.Count) && listed < 40; index++) + { + var a = index < ahead.Count ? ahead[index] : default; + var w = index < worker.Count ? worker[index] : default; + if (index < ahead.Count && index < worker.Count && a == w) + { + continue; + } + + listed++; + var g = again is not null && index < again.Count ? Read(again[index]) : "-"; + builder.Append($"[{index}] job={(index < ahead.Count ? Read(a) : "-")} worker={(index < worker.Count ? Read(w) : "-")} again={g}; "); + foreach (var address in new[] { a.Address, w.Address }) + { + var line = address & ~0xFFUL; + if (address != 0 && described.Count < 3 && !described.Contains(line)) + { + described.Add(line); + } + } + } + + foreach (var line in described) + { + builder.Append($"host[0x{line:X}+0x100]=({_executor.DescribeGuestRange(line, 0x100)}) "); + } + + builder.Append($"refused_at_resolution=[{job.CensusRefusals}] same_words_now=["); + foreach (var read in ahead) + { + if (read.Refused) + { + builder.Append($"0x{read.Address:X}:({_executor.DescribeGuestRange(read.Address, sizeof(uint))}) "); + } + } + + builder.Append(']'); + + return builder.ToString(); + } + + private GraphicsPrograms TakeCensus(Job job, RegisterBanks banks, in GraphicsProgramInputs inputs, bool lookedAhead) + { + var stood = System.Diagnostics.Stopwatch.GetTimestamp() - job.ResolvedAt; + var resolved = _executor.ResolveGraphicsPrograms(banks, in inputs); + var workerReads = job.CensusReads is null ? null : CensusReadsOfAny(resolved); + var group = lookedAhead ? 1 : 0; + Interlocked.Increment(ref _censusResolved[group]); + Interlocked.Add(ref _censusStoodTicks[group], stood); + if (SharpEmu.Libs.Gpu.Pipelines.GraphicsProgramsComparer.Difference(job.Programs!, resolved) is { } difference) + { + Interlocked.Increment(ref _censusDiffered[group]); + if (_censusReports[group] < MaximumCensusReports) + { + _censusReports[group]++; + Console.Error.WriteLine($"[GPU][PREFETCH] census differs group={(lookedAhead ? "ahead" : "gated")} {difference} " + + $"stood_us={stood * 1_000_000 / System.Diagnostics.Stopwatch.Frequency} (job {job.Index}, gate {job.Gate}, full gate {job.FullGate}, " + + $"executed at start {job.ExecutedAtStart}) " + + $"job_vs_worker=[{SharpEmu.Libs.Gpu.Pipelines.GraphicsProgramsComparer.DescribeStages(job.Programs!, resolved)}] " + + $"looked_over=[{DescribeLookedOver(job.ExecutedAtStart, job.FullGate)}] " + + $"state_job=[{job.ResolveState}] state_now=[{_executor.DescribeProgramState()}] " + + DescribeCensusReads(job, workerReads, job.CensusReads is null ? null : CensusReadsOfAny(resolved))); + } + } + + return resolved; + } + + // The worker's side of the census reads: its pixel stage's reads whatever program it picked. + private static List<(ulong Address, uint Word, bool Clean, bool Refused)>? CensusReadsOfAny(GraphicsPrograms? programs) => + programs is { Available: true } && programs.PixelInput.Stage.Program is not null + ? SharpEmu.ShaderCompiler.Resources.ResourceMaterializer.RecordReads(programs.PixelInput.Stage.Resources, clean: true) + : null; + // SHARPEMU_PREFETCH_DRAW_LOOKAHEAD=verify: the worker resolves the draw as it would have without the job, and the two // must hand the executor the same programs, inputs and resources (GraphicsProgramsComparer). private GraphicsPrograms VerifyLookahead(Job job, RegisterBanks banks, in GraphicsProgramInputs inputs) @@ -1154,9 +1310,12 @@ private void ResolveCore(Job job) job.StartInstanceUserData); job.ProgramState = _executor.ProgramState; job.Programs = _executor.ResolveGraphicsPrograms(job.Banks, in job.Inputs); - if (LookaheadMode == DrawLookaheadMode.Verify) + if (RecordsForVerify) { job.ResolveState = _executor.DescribeProgramState(); + job.ResolvedAt = System.Diagnostics.Stopwatch.GetTimestamp(); + job.CensusReads = CensusReadsOf(job.Programs); + job.CensusRefusals = DescribeRefusedCleanReads(job.CensusReads); } job.Assumptions = _concurrent.EndConcurrentResolve(); diff --git a/src/SharpEmu.Libs/Gpu/Rendering/RenderExecutor.Prefetch.cs b/src/SharpEmu.Libs/Gpu/Rendering/RenderExecutor.Prefetch.cs index 1d54ec2e0..8624abb32 100644 --- a/src/SharpEmu.Libs/Gpu/Rendering/RenderExecutor.Prefetch.cs +++ b/src/SharpEmu.Libs/Gpu/Rendering/RenderExecutor.Prefetch.cs @@ -184,6 +184,8 @@ public static GraphicsProgramInputs ProgramInputsOf(RegisterBanks banks, IImageF public string DescribeProgramState() => _pipelines.DescribeProgramState(); + public string DescribeGuestRange(ulong address, ulong size) => _host.DescribeGuestRangeForDiagnostics(address, size); + public ProgramStateStamp ProgramState => _pipelines.ProgramState; // The programs of a draw with these banks and inputs, as ResolveShaderPrograms resolves them. diff --git a/src/SharpEmu.ShaderCompiler/Resources/ResourceMaterializer.cs b/src/SharpEmu.ShaderCompiler/Resources/ResourceMaterializer.cs index 963209321..4bad71d70 100644 --- a/src/SharpEmu.ShaderCompiler/Resources/ResourceMaterializer.cs +++ b/src/SharpEmu.ShaderCompiler/Resources/ResourceMaterializer.cs @@ -489,14 +489,19 @@ public static string TakeReadProofReport() => FormattableString.Invariant( // Diagnostics: every guest word a fast snapshot's program reads when evaluated now with the snapshot's own draw values // (word reads only, no resident or clean shortcuts), in read order; null when the snapshot is not a fast one or the // evaluation threw (an abandoned read on a resolving thread included). - public static List<(ulong Address, uint Word)>? RecordWordReads(ResourceSnapshot snapshot) + public static List<(ulong Address, uint Word)>? RecordWordReads(ResourceSnapshot snapshot) => + RecordReads(snapshot, clean: false)?.ConvertAll(read => (read.Address, read.Word)); + + // RecordWordReads, with the clean reader's reads recorded too when clean is set (Clean marks them; a refused clean + // read is recorded with word 0 and Refused set). + public static List<(ulong Address, uint Word, bool Clean, bool Refused)>? RecordReads(ResourceSnapshot snapshot, bool clean) { if (snapshot.Origin is not FastOrigin { Plan.MaterializationProgram: not null } origin) { return null; } - var reads = new List<(ulong Address, uint Word)>(); + var reads = new List<(ulong Address, uint Word, bool Clean, bool Refused)>(); var reader = origin.Inputs.ReadMemory; bool Recording(ulong address, out uint word) { @@ -506,14 +511,28 @@ bool Recording(ulong address, out uint word) return false; } - reads.Add((address, word)); + reads.Add((address, word, false, false)); return true; } + var cleanReader = origin.Inputs.ReadCleanMemory; + bool RecordingClean(ulong address, out uint word) + { + word = 0; + if (cleanReader is null) + { + return false; + } + + var read = cleanReader(address, out word); + reads.Add((address, word, true, !read)); + return read; + } + var inputs = new ResourceRuntimeInputs { ReadMemory = Recording, - ReadCleanMemory = origin.Inputs.ReadCleanMemory, + ReadCleanMemory = clean && cleanReader is not null ? RecordingClean : cleanReader, UserData = origin.UserData, ShaderBase = origin.ShaderBase, ComputeState = origin.ComputeState, diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.cs index 128838ef9..b5adb2c7a 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.cs @@ -2213,6 +2213,31 @@ public bool HasGpuModifiedImageBytes(ulong address, ulong size) return false; } + // Diagnostics (SHARPEMU_PREFETCH_DRAW_LOOKAHEAD=census): the live images over the range, with their extent and state. + internal string DescribeRangeOwners(ulong address, ulong size) + { + if (!IsValidRange(address, size) || !_pageOwners.MayHaveOwners(address, size)) + { + return "none"; + } + + using var held = _lock.Hold(); + var owners = new List(); + foreach (var imageIdentifier in FindImagesInRange(address, size, pageOverlap: false)) + { + if (_slots.TryGet(imageIdentifier) is { } image) + { + owners.Add(FormattableString.Invariant( + $"0x{image.Description.Data.Address:X}+0x{image.Description.Data.Size:X} {image.Description.GuestFormat} ") + + FormattableString.Invariant( + $"{image.Description.Extent.Width}x{image.Description.Extent.Height}x{image.Description.Extent.Depth} tile={image.Description.TileMode} ") + + $"gpu_modified={image.IsGpuModified} cpu_dirty={image.IsCpuDirty} gpu_overlaps={image.GpuOverlaps(address, size)}"); + } + } + + return owners.Count == 0 ? "none" : string.Join(" | ", owners); + } + // Two surfaces over exactly the same guest bytes hand their contents over on the // device, with guest memory left out of it entirely. The pair that costs the most is // a depth-stencil target and the single-channel float alias something samples it diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.ConcurrentResolve.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.ConcurrentResolve.cs index 31a11b948..a0cd65398 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.ConcurrentResolve.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.ConcurrentResolve.cs @@ -802,6 +802,14 @@ private AbandonCause ConcurrentOwner(ulong address, ulong size, ConcurrentOwnerS return AbandonCause.None; } + // Diagnostics (DescribeGuestRangeForDiagnostics): the first owner the resolving thread's test names, any thread. + private string ConcurrentOwnerForDiagnostics(ulong address, ulong size) => + ConcurrentOwner(address, size, scope: null) is var cause && cause == AbandonCause.None ? "none" : AbandonCauseNames[(int)cause]; + + private bool PendingCommandWriteHoldsForDiagnostics(ulong address, ulong size) => PendingCommandWriteHolds(address, size); + + private bool IsGpuWritePendingForDiagnostics(ulong address, ulong size) => IsGpuWritePendingConcurrent(address, size); + private bool PendingCommandWriteHolds(ulong address, ulong size) => _commandThread is { } thread && ParallelProgramPrefetch.ResolvingJob is var job and >= 0 && thread.PendingRangeHolds(job, address, size); diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.cs index 76619a4bf..fbf772771 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.cs @@ -2089,6 +2089,7 @@ private void WaitForGuestBytes(ulong address, ulong size) if (_imageCache.HasGpuModifiedImageBytes(address, size)) { AbandonSpeculativeWait(address, size); + NoteHostReadWait(address, size, image: true); // The writeback is recorded into the buffer being built, so this one has // to be committed before the bytes can be read. FlushGpuWrites(address, size, MetalWritebackCause.HostRead); @@ -2108,6 +2109,7 @@ private void WaitForGuestBytes(ulong address, ulong size) } NoteObservedRead(address, size); + NoteHostReadWait(address, size, image: false); if (TryWaitForWriteFence(address, size, pending)) { return; @@ -2124,6 +2126,57 @@ private void WaitForGuestBytes(ulong address, ulong size) } } + // Diagnostics (SHARPEMU_PREFETCH_DRAW_LOOKAHEAD=census): the last host reads that waited, an image's writeback + // (image) or a recorded write landing (range), with when; DescribeGuestRangeForDiagnostics names those over a range. + private readonly (ulong Address, ulong Size, bool Image, long At)[] _hostReadWaits = new (ulong, ulong, bool, long)[64]; + private int _hostReadWaitNext; + + private void NoteHostReadWait(ulong address, ulong size, bool image) + { + if (SharpEmu.Libs.Gpu.Rendering.ParallelProgramPrefetch.DrawLookahead != + SharpEmu.Libs.Gpu.Rendering.ParallelProgramPrefetch.DrawLookaheadMode.Census) + { + return; + } + + lock (_hostReadWaits) + { + _hostReadWaits[_hostReadWaitNext++ & (_hostReadWaits.Length - 1)] = + (address, size, image, System.Diagnostics.Stopwatch.GetTimestamp()); + } + } + + public string DescribeGuestRangeForDiagnostics(ulong address, ulong size) + { + Span backing = stackalloc byte[sizeof(uint)]; + var raw = _backing.TryReadBacking(address, backing) + ? System.Buffers.Binary.BinaryPrimitives.ReadUInt32LittleEndian(backing).ToString("X8", System.Globalization.CultureInfo.InvariantCulture) + : "unreadable"; + var waits = new List(); + var now = System.Diagnostics.Stopwatch.GetTimestamp(); + lock (_hostReadWaits) + { + foreach (var wait in _hostReadWaits) + { + if (wait.Size != 0 && wait.Address < address + size && address < wait.Address + wait.Size) + { + waits.Add(FormattableString.Invariant( + $"{(wait.Image ? "image" : "range")}@0x{wait.Address:X}+0x{wait.Size:X} {(now - wait.At) * 1_000_000 / System.Diagnostics.Stopwatch.Frequency}us_ago")); + } + } + } + + var owner = ConcurrentOwnerForDiagnostics(address, size); + Func serial = SignaledSerial; + return $"owner={owner} queued={PendingCommandWriteHoldsForDiagnostics(address, size)} " + + FormattableString.Invariant($"gpu_write_pending={IsGpuWritePendingForDiagnostics(address, size)} ") + + FormattableString.Invariant($"cp_cover={(_cpOverlay.Count == 0 ? "-" : _cpOverlay.Coverage(address, size, serial).ToString())} ") + + FormattableString.Invariant($"label_cover={(_labelOverlay.Count == 0 ? "-" : _labelOverlay.Coverage(address, size, serial).ToString())} ") + + FormattableString.Invariant($"backing_w0={raw} gpu_writes_may_cover={_gpuWrites.MayCover(address, size)} ") + + FormattableString.Invariant($"cp_overlay={_cpOverlay.Count} label_overlay={_labelOverlay.Count} ") + + $"images=[{_imageCache.DescribeRangeOwners(address, size)}] host_read_waits=[{string.Join(" | ", waits)}]"; + } + // A read this small that waits for the GPU is a command-processor operand (an indirect // draw's arguments, a count, a predicate) rather than data; each distinct reader is // named once, with its stack, so the stall can be traced to the packet that asked. From bd5c2009a69c9a94d2f40188c496bfe7c8efb0ce Mon Sep 17 00:00:00 2001 From: kuba Date: Sun, 15 Nov 2026 19:01:50 +0000 Subject: [PATCH 090/178] [GPU] Refuse a clean word read on the worker while a recorded GPU write covers it The worker's TryReadCleanGuestWord refused only GPU-modified image bytes and answered a word a pending recorded GPU store covers from the backing, i.e. the value from before the store. The resolving thread (ConcurrentOwner) and the worker's own resident reader refuse it. A resource branch predicate read that way kept one path on the worker (the other path's descriptors zero, another permutation) and both on the resolver: Demon's Souls pixel shader 0x5089A6D528E00B58 at world load, predicate words 0x70A1180464/0x70A1180C40 under a pending GPU write. --- .../SharpEmu.Gpu.Metal/V2/MetalRenderHost.Pipelines.cs | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Pipelines.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Pipelines.cs index 774ed1f1d..db35a24fb 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Pipelines.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Pipelines.cs @@ -1889,7 +1889,12 @@ public bool TryReadCleanGuestWord(ulong address, out uint word) return true; } - if (_imageCache.HasGpuModifiedImageBytes(address, sizeof(uint))) + // A recorded GPU write still landing in the word owns it as an image does: the backing still holds the bytes + // from before the write, which the GPU will not see. Refused, as the resident reader below and the resolving + // thread's test (ConcurrentOwner) refuse it, so a clean answer is the same on every thread; a resource branch's + // predicate read here otherwise kept one path on the worker and both on the resolver. + if (_imageCache.HasGpuModifiedImageBytes(address, sizeof(uint)) || + (_gpuWrites.MayCover(address, sizeof(uint)) && _gpuWrites.PendingSerial(address, sizeof(uint), CompletedSerial) != 0)) { return false; } From fa3b6a0c4f8e60eb66a90068fa27063333dbf0f5 Mon Sep 17 00:00:00 2001 From: kuba Date: Sun, 15 Nov 2026 19:33:41 +0000 Subject: [PATCH 091/178] [GPU] Re-test a resolution's owned answers at the take, since a completed GPU write moves no version A refused clean or resident read (a resource branch then keeps both paths) is recorded as an owned answer. Its owner, a recorded GPU write, stops owning the bytes when the GPU completes it, before the worker retires the record, so the ownership versions stay equal and IsConcurrentResolveStillCurrent took the resolution while the worker would now answer the read and prune a path. A resolution that recorded an owned answer now always re-tests its answers; owned_now_clean_refusals counts the takes refused that way. The look-ahead verify keeps the job's assumptions to its comparison and counts a difference whose answers changed after the take as verify_raced instead of a fatal. Demon's Souls full verify configuration: fatal at 108 s before, stop marker at 150 s now, 6339 such refusals. --- .../Gpu/Rendering/ParallelProgramPrefetch.cs | 34 ++++++++-- .../V2/MetalRenderHost.ConcurrentResolve.cs | 20 +++++- .../MetalClearFoldingTests.OwnedCleanReads.cs | 68 +++++++++++++++++++ 3 files changed, 115 insertions(+), 7 deletions(-) create mode 100644 tests/SharpEmu.Gpu.Metal.Tests/MetalClearFoldingTests.OwnedCleanReads.cs diff --git a/src/SharpEmu.Libs/Gpu/Rendering/ParallelProgramPrefetch.cs b/src/SharpEmu.Libs/Gpu/Rendering/ParallelProgramPrefetch.cs index 1f0a5c39f..4a3d45d44 100644 --- a/src/SharpEmu.Libs/Gpu/Rendering/ParallelProgramPrefetch.cs +++ b/src/SharpEmu.Libs/Gpu/Rendering/ParallelProgramPrefetch.cs @@ -131,7 +131,7 @@ public enum DrawLookaheadRefusal : byte } private static readonly string[] DrawLookaheadRefusalNames = ["abandoned", "inputs", "effects", "ownership", "gc_effects", "replanned"]; - private long _lookaheadJobs, _lookaheadTaken, _lookaheadVerified; + private long _lookaheadJobs, _lookaheadTaken, _lookaheadVerified, _lookaheadVerifyRaced; // Draw jobs of any kind refused because the program cache moved since they began (DrawLookaheadRefusal.Replanned). private long _replannedRefusals; private readonly long[] _lookaheadRefusals = new long[(int)DrawLookaheadRefusal.Count]; @@ -187,7 +187,7 @@ private string TakeDrawLookaheadReport() builder.Append(index == 0 ? string.Empty : ",").Append(DrawLookaheadRefusalNames[index]).Append('=').Append(refused[index]); } - return builder.Append("),verified=").Append(verified) + return builder.Append("),verified=").Append(verified).Append(",verify_raced=").Append(Interlocked.Exchange(ref _lookaheadVerifyRaced, 0)) .Append(",gc=(jobs=").Append(collect.Jobs).Append(",taken=").Append(collect.Taken).Append(",refused=").Append(collect.Refused) .Append(",calls=").Append(collect.Calls).Append(",effects=").Append(collect.Effects) .Append("),replanned_all=").Append(Interlocked.Exchange(ref _replannedRefusals, 0)) @@ -644,7 +644,14 @@ public bool TryTakeGraphics(RegisterBanks banks, in GraphicsProgramInputs inputs : Volatile.Read(ref _lastDispatchEffect) >= job.ExecutedAtStart ? DrawLookaheadRefusal.Effects : !_concurrent.IsStillCurrentAcrossDispatches(job.Assumptions!) ? DrawLookaheadRefusal.Ownership : DrawLookaheadRefusal.Count; - ReleaseAssumptions(job); + // =verify keeps a taken look-ahead's assumptions to its comparison (VerifyLookahead): a difference whose answers + // changed after the take is a race, not a hole. + var verifies = refusal == DrawLookaheadRefusal.Count && lookedAhead && LookaheadMode == DrawLookaheadMode.Verify; + if (!verifies) + { + ReleaseAssumptions(job); + } + if (refusal != DrawLookaheadRefusal.Count) { if (lookedAhead) @@ -675,9 +682,16 @@ public bool TryTakeGraphics(RegisterBanks banks, in GraphicsProgramInputs inputs Interlocked.Increment(ref _collectLookaheadTaken); } - if (LookaheadMode == DrawLookaheadMode.Verify) + if (verifies) { - programs = VerifyLookahead(job, banks, in inputs); + try + { + programs = VerifyLookahead(job, banks, in inputs); + } + finally + { + ReleaseAssumptions(job); + } } } @@ -824,6 +838,16 @@ private GraphicsPrograms VerifyLookahead(Job job, RegisterBanks banks, in Graphi Interlocked.Increment(ref _lookaheadVerified); if (SharpEmu.Libs.Gpu.Pipelines.GraphicsProgramsComparer.Difference(job.Programs!, resolved) is { } difference) { + // The take's answers no longer hold (an owned answer turned clean: a recorded GPU write completed between + // the take and this resolution, and a refused clean read is answered now): both resolutions are right for + // their moment, the worker's is the later one. Counted, not fatal; a difference under answers that still + // hold is a hole and stops below. + if (job.Assumptions is { } assumptions && !_concurrent.IsStillCurrentAcrossDispatches(assumptions)) + { + Interlocked.Increment(ref _lookaheadVerifyRaced); + return resolved; + } + // What the next verify run needs to tell a hole in the take check from a resolution that differs whatever ran // before it: every differing group, both resolutions' programs, whether the worker resolves the same again, // the items looked over (a dispatch's program hash) and the effects noted, and the program cache state the diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.ConcurrentResolve.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.ConcurrentResolve.cs index a0cd65398..7dd1e3ccf 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.ConcurrentResolve.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.ConcurrentResolve.cs @@ -64,6 +64,8 @@ internal sealed partial class MetalRenderHost : IConcurrentResolveHost bool IConcurrentResolveHost.IsStillCurrentAcrossDispatches(object assumptions) => IsConcurrentResolveStillCurrentAcrossDispatches(assumptions); private long _writeLogRefusals; + // Takes refused because an owned answer (a refused clean or resident read) is clean now. + private long _ownedNowCleanRefusals; // Small unclaimed queues can resolve on the drawing thread without a worker wakeup. // Component gains and ordering/device checks justify the default; the Silent Hill @@ -168,7 +170,7 @@ private string FormatPrefetchCounters() var dispatches = $" dispatch_jobs={computeSubmitted} dispatch_taken={computeTaken} dispatch_refused=(abandoned={computeRefused[(int)ParallelProgramPrefetch.ComputeRefusal.Abandoned]}," + $"provider={computeRefused[(int)ParallelProgramPrefetch.ComputeRefusal.Provider]}{FormatProviderRefusals(prefetch.TakeProviderRefusals())},inputs={computeRefused[(int)ParallelProgramPrefetch.ComputeRefusal.Inputs]}," + $"ownership={computeRefused[(int)ParallelProgramPrefetch.ComputeRefusal.Ownership]},effects={computeRefused[(int)ParallelProgramPrefetch.ComputeRefusal.Effects]}) " + - $"write_log_refusals={Interlocked.Exchange(ref _writeLogRefusals, 0)} dispatch_wait_ms={computeWaitMs.ToString("F1", culture)} " + + $"write_log_refusals={Interlocked.Exchange(ref _writeLogRefusals, 0)} owned_now_clean_refusals={Interlocked.Exchange(ref _ownedNowCleanRefusals, 0)} dispatch_wait_ms={computeWaitMs.ToString("F1", culture)} " + $"dispatch_saved_ms={computeSavedMs.ToString("F1", culture)}"; return $"resolved={resolved} abandoned={abandoned} abandoned_by=({TakeAbandonCauses()}) abandoned_verify={GpuFatal.TakeSpeculativeVerifyFailures()} taken={taken} refused={refused} drains={drains} drained={drained} deferred_barriers={deferredBarriers} operand_reads_kept={operandReadsKept} " + $"wait_ms={waitMs.ToString("F1", culture)} resolve_ms={prefetch.TakeResolveMilliseconds().ToString("F1", culture)} " + @@ -434,11 +436,18 @@ public void NoteCopiedThrough(ulong address, ulong size) // The ring slot whose mask answered IsOwnedRecorded's last test, or -1. public int LastMaskSlot = -1; + // An owned answer was recorded: a clean or resident read the resolution let refuse (a resource branch then keeps + // both paths). Its owner can go away with no version moving (the GPU completes a recorded write before the worker + // retires it), so IsConcurrentResolveStillCurrent re-tests every answer instead of trusting equal versions. Not + // cleared by Forget: a stale flag only costs the re-test. + public bool ReliesOnOwned; + // Taken again from the pool for a new resolution. public void Reset((long Overlay, long Labels, ulong GpuWrites, long Images, long GpuModified) versions) { Answers.Clear(); CopiedThrough.Clear(); + ReliesOnOwned = false; Versions = versions; Array.Fill(_cleanPages, ulong.MaxValue); _nextCleanPage = 0; @@ -545,6 +554,7 @@ public void Record(ConcurrentQuery query, ulong address, ulong size, bool owned) } } + ReliesOnOwned |= owned; Answers.Add((query, address, size, owned)); } } @@ -676,7 +686,7 @@ internal string TakeAbandonCauses() internal bool IsConcurrentResolveStillCurrent(object assumptionsObject) { var assumptions = (ConcurrentAssumptions)assumptionsObject; - if (assumptions.Versions == OwnershipVersions()) + if (!assumptions.ReliesOnOwned && assumptions.Versions == OwnershipVersions()) { return true; } @@ -699,6 +709,12 @@ internal bool IsConcurrentResolveStillCurrent(object assumptionsObject) scope.Count(OwnerTestCounter.Recheck); if ((ConcurrentOwner(address, size, scope) != AbandonCause.None) != owned) { + if (owned) + { + // A refused read would now be answered: the resolution kept what a read now prunes. + Interlocked.Increment(ref _ownedNowCleanRefusals); + } + return false; } } diff --git a/tests/SharpEmu.Gpu.Metal.Tests/MetalClearFoldingTests.OwnedCleanReads.cs b/tests/SharpEmu.Gpu.Metal.Tests/MetalClearFoldingTests.OwnedCleanReads.cs new file mode 100644 index 000000000..78409e66b --- /dev/null +++ b/tests/SharpEmu.Gpu.Metal.Tests/MetalClearFoldingTests.OwnedCleanReads.cs @@ -0,0 +1,68 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using SharpEmu.Gpu.Metal.V2; +using SharpEmu.Libs.Gpu.Rendering; +using Xunit; + +namespace SharpEmu.Gpu.Metal.Tests; + +/// +/// A clean read a recorded GPU write still owns is refused on every thread (a resource branch's predicate then keeps both +/// paths), and a resolution that relied on that refusal is not current once the write has completed: the worker would +/// answer the read now and prune a path, so the take refuses the resolution even while no ownership version moved. +/// +public sealed unsafe partial class MetalClearFoldingTests +{ + private const ulong PredicateWord = GuestBase + 0x3A000; + + [Fact] + public void ARefusedCleanReadIsNotCurrentOnceTheWriteThatOwnedItCompletes() + { + if (!RequireDevice()) return; + using var rig = new Rig(Device.Value); + var host = rig.Host; + rig.WriteBacking32(PredicateWord, 0); + host.NoteGuestMemoryWrite(PredicateWord, sizeof(uint), MetalGpuWriteOrigin.StorageBuffer); + + // The worker refuses it as the resolving thread does. + Assert.False(host.TryReadCleanGuestWord(PredicateWord, out _)); + + var concurrent = (IConcurrentResolveHost)host; + concurrent.BeginConcurrentResolve(); + object assumptions; + try + { + Assert.False(host.TryReadCleanGuestWord(PredicateWord, out _)); + } + finally + { + assumptions = concurrent.EndConcurrentResolve(); + } + + try + { + Assert.True(((MetalRenderHost.ConcurrentAssumptions)assumptions).ReliesOnOwned); + Assert.True(concurrent.IsStillCurrent(assumptions)); + Assert.True(concurrent.IsStillCurrentAcrossDispatches(assumptions)); + + // The GPU completes the write; nothing on the worker retires its record yet, so no ownership version moves. + var serial = host.FlushCommandBuffer(); + var deadline = Environment.TickCount64 + 10_000; + while (host.CompletedSerial < serial && Environment.TickCount64 < deadline) + { + Thread.Sleep(1); + } + + Assert.True(host.CompletedSerial >= serial); + Assert.False(concurrent.IsStillCurrent(assumptions)); + Assert.False(concurrent.IsStillCurrentAcrossDispatches(assumptions)); + Assert.True(host.TryReadCleanGuestWord(PredicateWord, out var word)); + Assert.Equal(0u, word); + } + finally + { + concurrent.ReleaseAssumptions(assumptions); + } + } +} From 9cae28044699f0650124b53778377d6852da7402 Mon Sep 17 00:00:00 2001 From: kuba Date: Sun, 15 Nov 2026 20:08:53 +0000 Subject: [PATCH 092/178] [GPU] Name the differing word's address and each reader's answer in a read-proof verify mismatch The mismatch now carries the guest address of the first differing table word and what the evaluation's word reader answers for it now; the host adds how the resolving thread reads it (word line and copy line caches, clean page, a freshly tested read, the pending copy's source, owner, overlays, backing). Demon's Souls r41-long: vertex plan 0x8B94AE10B80DDFCD table word 14 at 0x70A11800D0, owner=gpu_write pending, proof/hit = pending copy source 0x3F793652, evaluation = backing (varies per occurrence). --- .../Gpu/Pipelines/ShaderProgramCache.cs | 17 ++++++- .../Resources/ResourceMaterializer.cs | 37 ++++++++++++++-- .../V2/MetalRenderHost.ConcurrentResolve.cs | 44 +++++++++++++++++++ 3 files changed, 93 insertions(+), 5 deletions(-) diff --git a/src/SharpEmu.Libs/Gpu/Pipelines/ShaderProgramCache.cs b/src/SharpEmu.Libs/Gpu/Pipelines/ShaderProgramCache.cs index 329d9d805..0de5190e2 100644 --- a/src/SharpEmu.Libs/Gpu/Pipelines/ShaderProgramCache.cs +++ b/src/SharpEmu.Libs/Gpu/Pipelines/ShaderProgramCache.cs @@ -368,7 +368,7 @@ public bool Revalidate(in ShaderStageResources stage) } catch (ResourceMaterializer.ReadProofMismatchException mismatch) { - throw GpuFatal.VerifyFailed(mismatch.Message); + throw GpuFatal.VerifyFailed(DescribeMismatch(mismatch)); } var current = fast ?? (Materializations is { } materializations && materializations.Revalidate(stage.Resources, _readResidentGuestBytes)); @@ -379,6 +379,19 @@ public bool Revalidate(in ShaderStageResources stage) return current; } + // A read-proof verify mismatch with what the host says of the differing word's address, printed with it. + private string DescribeMismatch(ResourceMaterializer.ReadProofMismatchException mismatch) + { + if (mismatch.Address is not { } address) + { + return mismatch.Message; + } + + var host = $"[SHADER][READ_PROOF] mismatch word 0x{address:X}: {_host.DescribeCleanRead(address)}"; + Console.Error.WriteLine(host); + return mismatch.Message + " " + host; + } + // Revalidate; and with rebuild, a fast stage whose own draw values evaluate to other descriptor words gets the stage // a lookup of that draw makes now (ResourceMaterializer.RevalidateOrRebuildFast): the same program, since the // specialization that picks its permutation is unchanged, and the snapshot materialized from that one evaluation. @@ -400,7 +413,7 @@ public ResourceMaterializer.FastRevalidation RevalidateOrRebuild(in ShaderStageR } catch (ResourceMaterializer.ReadProofMismatchException mismatch) { - throw GpuFatal.VerifyFailed(mismatch.Message); + throw GpuFatal.VerifyFailed(DescribeMismatch(mismatch)); } if (fast == ResourceMaterializer.FastRevalidation.NotFast) diff --git a/src/SharpEmu.ShaderCompiler/Resources/ResourceMaterializer.cs b/src/SharpEmu.ShaderCompiler/Resources/ResourceMaterializer.cs index 4bad71d70..4dec75ffe 100644 --- a/src/SharpEmu.ShaderCompiler/Resources/ResourceMaterializer.cs +++ b/src/SharpEmu.ShaderCompiler/Resources/ResourceMaterializer.cs @@ -449,7 +449,11 @@ internal enum ReadProofMode internal const int BackoffRevalidations = 16; // A verify-mode proof whose replay differs from the full evaluation (the full one compared its words again first). - public sealed class ReadProofMismatchException(string message) : InvalidOperationException(message); + public sealed class ReadProofMismatchException(string message, ulong? address = null) : InvalidOperationException(message) + { + // The guest address of the first differing flattened-table word, when one differs and its address evaluates. + public ulong? Address { get; } = address; + } private static readonly ThreadCounter _proofHits = new(); private static readonly ThreadCounter _proofNone = new(); @@ -939,6 +943,7 @@ private static void AttachProof(ShaderResourcePlan plan, ResourceSnapshot snapsh [ThreadStatic] private static MaterializationProgram.Output? _verifyOutput; + // Verify: a proved snapshot against a full evaluation of the same inputs. Not current while the proof's words still // compare equal is a wrong proof (counted, then thrown for the host's fatal); after they changed, a race with a guest // write (verify_raced). @@ -954,6 +959,31 @@ private static void VerifyProof(ShaderResourcePlan plan, ResourceSnapshot snapsh // Taken before the proof is compared again, which reads (and on a resolving thread records) the words anew. var first = evaluated ? OutputDifference(plan, snapshot, output) : "refused"; + // Where the first differing table word lies, and what the evaluation's word reader answers for it now. + ulong? at = null; + var atRead = "none"; + if (evaluated && output.TableWords is { } tableWords) + { + var known = snapshot.FlattenedResourceTable; + for (var slot = 0; slot < Math.Min(known.Length, tableWords.Length); slot++) + { + if (known[slot] == tableWords[slot]) continue; + try + { + at = RuntimeValueEvaluator.TableWordAddress(plan, inputs, slot); + atRead = at is { } address && inputs.ReadMemory is { } reader + ? reader(address, out var word) ? FormattableString.Invariant($"0x{word:X8}") : "refused" + : "no_address"; + } + catch (Exception exception) + { + atRead = "threw " + exception.GetType().Name; + } + + break; + } + } + if (!Holds(plan, proof, inputs, inputs.CompareGuestWords!)) { _proofVerifyRaced.Increment(); @@ -977,9 +1007,10 @@ private static void VerifyProof(ShaderResourcePlan plan, ResourceSnapshot snapsh var thread = Thread.CurrentThread; var message = $"[SHADER][READ_PROOF] verify mismatch: proved current but evaluates otherwise plan=0x{plan.Hash:X16} stage={plan.Stage} " + $"ranges={proof.Addresses.Length} bytes={proof.Bytes.Length} unreadable={proof.Unreadable.Length} " + - $"first={first} again={again} branches={plan.ResourceBranches.Count} thread={thread.Name ?? thread.ManagedThreadId.ToString(System.Globalization.CultureInfo.InvariantCulture)}."; + $"first={first} again={again} branches={plan.ResourceBranches.Count} thread={thread.Name ?? thread.ManagedThreadId.ToString(System.Globalization.CultureInfo.InvariantCulture)} " + + $"at={(at is { } a ? FormattableString.Invariant($"0x{a:X}") : "unknown")} word_reader_now={atRead}."; Console.Error.WriteLine(message); - throw new ReadProofMismatchException(message); + throw new ReadProofMismatchException(message, at); } // Whether the plan evaluates to the snapshot's words again for these inputs (a draw's user data, shader base and diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.ConcurrentResolve.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.ConcurrentResolve.cs index 7dd1e3ccf..ece5850a8 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.ConcurrentResolve.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.ConcurrentResolve.cs @@ -818,6 +818,50 @@ private AbandonCause ConcurrentOwner(ulong address, ulong size, ConcurrentOwnerS return AbandonCause.None; } + // For an error report (a read-proof verify mismatch): how each reader of this thread answers the word now. Off the + // worker: the resolution's word line and copy line caches, its clean-page answer, the word read as a resolution + // reads it, the pending copy's source; then the owner, the backing and the host's range state. + public string DescribeCleanRead(ulong address) + { + var builder = new System.Text.StringBuilder(); + const ulong lineMask = ConcurrentWordLineBytes - 1; + var line = address & ~lineMask; + var offset = (int)(address & lineMask); + if (_concurrentAssumptions is { } assumptions && (address & 3) == 0) + { + builder.Append(FormattableString.Invariant($"word_line={(assumptions.WordLine == line ? $"0x{System.Buffers.Binary.BinaryPrimitives.ReadUInt32LittleEndian(assumptions.WordLineBytes.AsSpan(offset)):X8}" : "other")} ")); + var copyBit = ((assumptions.CopyLineWords >> (offset >> 2)) & 1) != 0; + builder.Append(FormattableString.Invariant($"copy_line={(assumptions.CopyLine == line ? copyBit ? $"0x{System.Buffers.Binary.BinaryPrimitives.ReadUInt32LittleEndian(assumptions.CopyLineBytes.AsSpan(offset)):X8}" : "line_no_bit" : "other")} ")); + builder.Append($"clean_page={assumptions.IsCleanPage(ConcurrentQuery.Word, address & ~(ConcurrentPageBytes - 1))} "); + try + { + var savedLine = assumptions.WordLine; + var savedCopy = assumptions.CopyLine; + assumptions.WordLine = ulong.MaxValue; + assumptions.CopyLine = ulong.MaxValue; + builder.Append(TryReadGuestWordConcurrentTested(address, out var tested, assumptions) + ? FormattableString.Invariant($"tested_read=0x{tested:X8} ") : "tested_read=refused "); + assumptions.WordLine = savedLine; + assumptions.CopyLine = savedCopy; + } + catch (GpuFatal.AbandonedWorkException) + { + builder.Append("tested_read=abandoned "); + } + + Span through = stackalloc byte[sizeof(uint)]; + builder.Append(TryReadThroughPendingCopyConcurrent(address, through, assumptions) + ? FormattableString.Invariant($"pending_copy=0x{System.Buffers.Binary.BinaryPrimitives.ReadUInt32LittleEndian(through):X8} ") : "pending_copy=none "); + } + else + { + builder.Append("thread=worker "); + } + + builder.Append(DescribeGuestRangeForDiagnostics(address, sizeof(uint))); + return builder.ToString(); + } + // Diagnostics (DescribeGuestRangeForDiagnostics): the first owner the resolving thread's test names, any thread. private string ConcurrentOwnerForDiagnostics(ulong address, ulong size) => ConcurrentOwner(address, size, scope: null) is var cause && cause == AbandonCause.None ? "none" : AbandonCauseNames[(int)cause]; From dc219d26e870feec0722391e687bc3263c34afc0 Mon Sep 17 00:00:00 2001 From: kuba Date: Sun, 15 Nov 2026 20:31:25 +0000 Subject: [PATCH 093/178] [GPU] Refuse every take whose reads a GPU write logged since the resolution began covers, and excuse verify differences only there A resolution ahead of the worker can answer a line clean, read it from memory, and then see the worker record a GPU write over it (an item ahead of the draw: the worker takes the draw only after it). Once that write completed, the answer was clean again and IsConcurrentResolveStillCurrent (the take of a draw that did not look ahead of dispatches) accepted the bytes from before the write; only the cross-dispatch take tested the write log. Every take now tests it (ACleanReadIsNotCurrentOnceAWriteRecordedAfterItCompletes fails without, passes with). Such a resolution's readers straddle the write: a line answered clean before it is read from memory (the resident run reader), a word compared or read afterwards is read through the write's copy. That is the read-proof and resolve-memo verify difference in Demon's Souls (plan 0x8B94AE10B80DDFCD, 0x70A11800D0, proof = copy source, evaluation = backing). The draw needs the value after the write. A verify on the resolving thread now asks the host (IShaderPipelineHost.ConcurrentReadsSuperseded) whether a write logged since the resolution began covers what it read, from a seqlocked snapshot of the log; if so the difference is counted (read_proof verify_superseded, resolve_memo verify_raced superseded, host superseded_verifies) and the answer is latched so the take refuses the resolution whatever it finds. Two device tests that asserted the old take now assert the refusal. --- .../Gpu/Pipelines/GraphicsResolveMemo.cs | 7 +- .../Gpu/Pipelines/IShaderPipelineHost.cs | 5 + .../Gpu/Pipelines/ShaderPipelineCache.cs | 10 ++ .../Gpu/Pipelines/ShaderProgramCache.cs | 3 + .../Resources/ResourceMaterializer.cs | 15 ++- .../Resources/ResourceRuntimeInputs.cs | 10 +- .../V2/MetalGpuWriteRanges.cs | 27 ++++ .../V2/MetalRenderHost.ConcurrentResolve.cs | 117 +++++++++++++++--- ...MetalClearFoldingTests.DispatchPrefetch.cs | 3 +- ...etalClearFoldingTests.GuestWordsCompare.cs | 13 +- .../MetalClearFoldingTests.OwnedCleanReads.cs | 69 +++++++++++ .../KeptStageInputsTests.ResolveMemo.cs | 4 +- .../Resources/ReadProofTests.cs | 27 ++++ 13 files changed, 280 insertions(+), 30 deletions(-) diff --git a/src/SharpEmu.Libs/Gpu/Pipelines/GraphicsResolveMemo.cs b/src/SharpEmu.Libs/Gpu/Pipelines/GraphicsResolveMemo.cs index d124f74bd..6313f78ad 100644 --- a/src/SharpEmu.Libs/Gpu/Pipelines/GraphicsResolveMemo.cs +++ b/src/SharpEmu.Libs/Gpu/Pipelines/GraphicsResolveMemo.cs @@ -436,16 +436,19 @@ public static string TakeReport() => FormattableString.Invariant( "key_miss=(" + Take(_keyMisses, "new", "user_data_only", "regs_only") + ")," + "uncacheable_by=(" + Take(_uncacheable, "frontend", "mesh", "tess", "calls", "unavailable", "tables", "trace", "origin", "key", "changed") + ")," + FormattableString.Invariant($"evictions={_evictions.Take()},entries={_entries.Total},verify_checked={_verifyChecked.Take()},") + - "verify_raced=(" + Take(_verifyRaced, "changed", "came_and_went") + ")," + + "verify_raced=(" + Take(_verifyRaced, "changed", "came_and_went", "superseded") + ")," + FormattableString.Invariant($"verify_failed={Interlocked.Read(ref _verifyFailed)})"); } // How a verify difference turned out to be a race (ShaderPipelineCache.VerifyResolveMemo): the hit's revalidation misses -// when made again (its words changed since), or it still holds and a second full resolution agrees with the hit. +// when made again (its words changed since), or it still holds and a second full resolution agrees with the hit, or the +// resolution's reads straddle a GPU write recorded since it began (superseded: the take refuses it). internal enum ResolveMemoVerifyRace { Changed, CameAndWent, + // Ahead of the worker, a GPU write recorded since the resolution began covers what it read: the take refuses it. + Superseded, Count, } diff --git a/src/SharpEmu.Libs/Gpu/Pipelines/IShaderPipelineHost.cs b/src/SharpEmu.Libs/Gpu/Pipelines/IShaderPipelineHost.cs index 66e7081b2..e05befaa6 100644 --- a/src/SharpEmu.Libs/Gpu/Pipelines/IShaderPipelineHost.cs +++ b/src/SharpEmu.Libs/Gpu/Pipelines/IShaderPipelineHost.cs @@ -170,6 +170,11 @@ void SynchronizeShaderCode(ulong address, ulong size) { } // For an error report: why a clean read of the dword can fail (mapping and GPU ownership). string DescribeCleanRead(ulong address) => ""; + // On a thread resolving ahead of the GPU worker: a GPU write recorded since this resolution began covers memory it + // read, and the worker's take will refuse the resolution (latched). For a verify to tell a resolution whose readers + // straddle that write from a wrong answer. False on the worker. + bool ConcurrentReadsSuperseded() => false; + // Copies guest bytes the CPU already holds, without synchronizing. False when the GPU // may own the range (or, for a clean read, when a clean word read would be refused); // the resource cache then re-materializes instead of trusting a stale copy. diff --git a/src/SharpEmu.Libs/Gpu/Pipelines/ShaderPipelineCache.cs b/src/SharpEmu.Libs/Gpu/Pipelines/ShaderPipelineCache.cs index 1c121e48c..9ddf4883e 100644 --- a/src/SharpEmu.Libs/Gpu/Pipelines/ShaderPipelineCache.cs +++ b/src/SharpEmu.Libs/Gpu/Pipelines/ShaderPipelineCache.cs @@ -776,6 +776,16 @@ private GraphicsPrograms VerifyResolveMemo(GraphicsResolveMemo memo, GraphicsRes // Named before anything is read again: the words that differ, their addresses, and both permutation keys. var stages = GraphicsProgramsComparer.DescribeStages(memoPrograms, full); + // Ahead of the worker, reads that straddle a GPU write recorded since the resolution began (the hit's proof + // compared through the write, the full resolution read a line answered clean before it): the take refuses this + // resolution (IShaderPipelineHost.ConcurrentReadsSuperseded latches it), whichever programs it hands out. + if (_host.ConcurrentReadsSuperseded()) + { + GraphicsResolveMemo.NoteVerifyRaced(ResolveMemoVerifyRace.Superseded); + ReportResolveMemoRace(entry, difference, "recheck=superseded", stages); + return full; + } + if (TryTakeResolveMemo(memo, entry, flags.PixelActive, out _, allowRebuild: false) is { } miss) { GraphicsResolveMemo.NoteVerifyRaced(ResolveMemoVerifyRace.Changed); diff --git a/src/SharpEmu.Libs/Gpu/Pipelines/ShaderProgramCache.cs b/src/SharpEmu.Libs/Gpu/Pipelines/ShaderProgramCache.cs index 0de5190e2..e34a0aa97 100644 --- a/src/SharpEmu.Libs/Gpu/Pipelines/ShaderProgramCache.cs +++ b/src/SharpEmu.Libs/Gpu/Pipelines/ShaderProgramCache.cs @@ -455,6 +455,7 @@ public ResourceMaterializer.FastRevalidation RevalidateOrRebuild(in ShaderStageR private readonly ResidentGuestBytesReader? _prefetchResidentGuestBytes; private readonly ResidentGuestBytesComparer? _compareResidentGuestBytes; private readonly GuestWordsComparer? _compareGuestWords; + private readonly Func? _readsSuperseded; // The functions the call tables name, decoded once while their code stays the same. private readonly ShaderFunctionCache _functions; @@ -480,6 +481,7 @@ public ShaderProgramCache(CpuContext context, IGuestGpuBackend compiler, IShader _prefetchResidentGuestBytes = PrefetchEnabled ? _readResidentGuestBytes : null; _compareResidentGuestBytes = ResourceMaterializationCache.InPlaceValidateEnabled ? CompareResidentGuestBytes : null; _compareGuestWords = host.ComparesGuestWords ? CompareGuestWords : null; + _readsSuperseded = host.ComparesGuestWords ? host.ConcurrentReadsSuperseded : null; _dataWritePending = host.DataWritePending; _functions = new ShaderFunctionCache(_readResidentGuestBytes); } @@ -878,6 +880,7 @@ private ShaderProgram CompleteProgram(ProgramSourceEntry entry, bool sourceWasCa ReadResidentMemory = _prefetchResidentGuestBytes, CompareResidentMemory = _compareResidentGuestBytes, CompareGuestWords = _compareGuestWords, + ReadsSuperseded = _readsSuperseded, DataWritePending = _dataWritePending, NullsOffClassLoopRecords = NullsOffClassLoopRecords, }; diff --git a/src/SharpEmu.ShaderCompiler/Resources/ResourceMaterializer.cs b/src/SharpEmu.ShaderCompiler/Resources/ResourceMaterializer.cs index 4dec75ffe..ff731d1ea 100644 --- a/src/SharpEmu.ShaderCompiler/Resources/ResourceMaterializer.cs +++ b/src/SharpEmu.ShaderCompiler/Resources/ResourceMaterializer.cs @@ -466,6 +466,7 @@ public sealed class ReadProofMismatchException(string message, ulong? address = private static readonly ThreadCounter _proofUnmatched = new(); private static readonly ThreadCounter _proofVerified = new(); private static readonly ThreadCounter _proofVerifyRaced = new(); + private static readonly ThreadCounter _proofVerifySuperseded = new(); private static readonly ThreadCounter _proofBackoffs = new(); private static readonly ThreadCounter _proofBackedOff = new(); private static long _proofVerifyFailed; @@ -475,13 +476,14 @@ public sealed class ReadProofMismatchException(string message, ulong? address = // through the host (normalized), or because the proof did not hold and the words then evaluated to the snapshot // (refused: owned or unreadable words, or changes the output does not show) or not (changed); proofs recorded, // refused (torn: one address read as two values) and not kept (unmatched: a snapshot that differs from the words - // its evaluation emitted); verify counts; origins that entered the back-off (backoffs) and revalidations that skipped + // its evaluation emitted); verify counts (verify_superseded: a difference in a resolution the take refuses, its reads + // straddling a GPU write recorded since it began); origins that entered the back-off (backoffs) and revalidations that skipped // their proof in it (backed_off). public static string TakeReadProofReport() => FormattableString.Invariant( $"read_proof=(mode={ReadProofs.ToString().ToLowerInvariant()},hits={_proofHits.Take()},none={_proofNone.Take()},") + FormattableString.Invariant($"no_comparer={_proofNoComparer.Take()},normalized={_proofNormalized.Take()},refused={_proofRefusedCurrent.Take()},changed={_proofChanged.Take()},") + FormattableString.Invariant($"recorded={_proofRecorded.Take()},torn={_proofTorn.Take()},unmatched={_proofUnmatched.Take()},verified={_proofVerified.Take()},") + - FormattableString.Invariant($"verify_raced={_proofVerifyRaced.Take()},verify_failed={Interlocked.Read(ref _proofVerifyFailed)},") + + FormattableString.Invariant($"verify_raced={_proofVerifyRaced.Take()},verify_superseded={_proofVerifySuperseded.Take()},verify_failed={Interlocked.Read(ref _proofVerifyFailed)},") + FormattableString.Invariant($"backoff={(ReadProofBackoff ? "on" : "off")},backoffs={_proofBackoffs.Take()},backed_off={_proofBackedOff.Take()})"); // The proof a fast snapshot's origin holds (tests). @@ -957,6 +959,15 @@ private static void VerifyProof(ShaderResourcePlan plan, ResourceSnapshot snapsh return; } + // A resolution ahead of the GPU worker whose reads straddle a GPU write recorded since it began (a line answered + // clean and read from memory before the write, compared through the write's copy after it): the take refuses it, + // and the draw sees the bytes after the write, which the proof's compare read (ResourceRuntimeInputs.ReadsSuperseded). + if (inputs.ReadsSuperseded is { } superseded && superseded()) + { + _proofVerifySuperseded.Increment(); + return; + } + // Taken before the proof is compared again, which reads (and on a resolving thread records) the words anew. var first = evaluated ? OutputDifference(plan, snapshot, output) : "refused"; // Where the first differing table word lies, and what the evaluation's word reader answers for it now. diff --git a/src/SharpEmu.ShaderCompiler/Resources/ResourceRuntimeInputs.cs b/src/SharpEmu.ShaderCompiler/Resources/ResourceRuntimeInputs.cs index 39bd13d67..d9153660d 100644 --- a/src/SharpEmu.ShaderCompiler/Resources/ResourceRuntimeInputs.cs +++ b/src/SharpEmu.ShaderCompiler/Resources/ResourceRuntimeInputs.cs @@ -39,6 +39,11 @@ public sealed class ResourceRuntimeInputs // Compares a program evaluation's recorded reads (GuestWordsComparer); null proves nothing, every evaluation reads. public GuestWordsComparer? CompareGuestWords { get; init; } + // On a thread resolving ahead of the GPU worker: whether a GPU write recorded since this resolution began covers memory + // it read, so the worker's take refuses it (the host latches the answer). A read-proof verify difference in such a + // resolution is between a reader that answered before that write and one after it, not a wrong proof. Null: never. + public Func? ReadsSuperseded { get; init; } + public bool ReadsClean { get; init; } // Whether recorded GPU work may still write the dword at this address, asked without @@ -61,6 +66,7 @@ public sealed class ResourceRuntimeInputs ReadResidentMemory = ReadResidentMemory, CompareResidentMemory = CompareResidentMemory, CompareGuestWords = CompareGuestWords, + ReadsSuperseded = ReadsSuperseded, ReadsClean = ReadsClean, DataWritePending = DataWritePending, NullsOffClassLoopRecords = NullsOffClassLoopRecords, @@ -71,7 +77,7 @@ public bool SameReaders(ResourceRuntimeInputs other) => ReferenceEquals(ReadMemory, other.ReadMemory) && ReferenceEquals(ReadCleanMemory, other.ReadCleanMemory) && ReferenceEquals(TraceImageCandidate, other.TraceImageCandidate) && ReferenceEquals(TablePhase, other.TablePhase) && ReferenceEquals(ReadResidentMemory, other.ReadResidentMemory) && ReferenceEquals(CompareResidentMemory, other.CompareResidentMemory) && - ReferenceEquals(CompareGuestWords, other.CompareGuestWords) && + ReferenceEquals(CompareGuestWords, other.CompareGuestWords) && ReferenceEquals(ReadsSuperseded, other.ReadsSuperseded) && ReadsClean == other.ReadsClean && ReferenceEquals(DataWritePending, other.DataWritePending) && NullsOffClassLoopRecords == other.NullsOffClassLoopRecords; @@ -87,6 +93,7 @@ public bool SameReaders(ResourceRuntimeInputs other) => ReadResidentMemory = ReadResidentMemory, CompareResidentMemory = CompareResidentMemory, CompareGuestWords = CompareGuestWords, + ReadsSuperseded = ReadsSuperseded, ReadsClean = ReadsClean || ReferenceEquals(reader, ReadCleanMemory), DataWritePending = DataWritePending, NullsOffClassLoopRecords = NullsOffClassLoopRecords, @@ -128,6 +135,7 @@ public ResourceRuntimeInputs WithCallArguments(uint userDataBase, IReadOnlyList< ReadResidentMemory = ReadResidentMemory, CompareResidentMemory = CompareResidentMemory, CompareGuestWords = CompareGuestWords, + ReadsSuperseded = ReadsSuperseded, ReadsClean = ReadsClean, DataWritePending = DataWritePending, NullsOffClassLoopRecords = NullsOffClassLoopRecords, diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalGpuWriteRanges.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalGpuWriteRanges.cs index 1b6cb3aea..464cc72f6 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalGpuWriteRanges.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalGpuWriteRanges.cs @@ -207,6 +207,33 @@ public bool LoggedWriteSince(ulong version, ulong address, ulong size) return false; } + /// + /// off the worker: the log read between two equal even + /// values (every log write happens inside a mutation); null when the worker changed it + /// meanwhile. + /// + public bool? TryLoggedWriteSinceSnapshot(ulong version, ulong address, ulong size) + { + var before = Volatile.Read(ref _mutation); + if ((before & 1) != 0) + { + return null; + } + + bool logged; + try + { + logged = LoggedWriteSince(version, address, size); + } + catch (IndexOutOfRangeException) + { + return null; + } + + Interlocked.MemoryBarrier(); + return Volatile.Read(ref _mutation) == before ? logged : null; + } + /// /// Recorded work in stores into this range. Returns the /// write's sequence (see ), or zero when nothing was recorded. diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.ConcurrentResolve.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.ConcurrentResolve.cs index ece5850a8..c12fc3da8 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.ConcurrentResolve.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.ConcurrentResolve.cs @@ -64,6 +64,8 @@ internal sealed partial class MetalRenderHost : IConcurrentResolveHost bool IConcurrentResolveHost.IsStillCurrentAcrossDispatches(object assumptions) => IsConcurrentResolveStillCurrentAcrossDispatches(assumptions); private long _writeLogRefusals; + // Verify differences excused because a GPU write logged since the resolution began covers what it read. + private long _supersededVerifies; // Takes refused because an owned answer (a refused clean or resident read) is clean now. private long _ownedNowCleanRefusals; @@ -170,7 +172,7 @@ private string FormatPrefetchCounters() var dispatches = $" dispatch_jobs={computeSubmitted} dispatch_taken={computeTaken} dispatch_refused=(abandoned={computeRefused[(int)ParallelProgramPrefetch.ComputeRefusal.Abandoned]}," + $"provider={computeRefused[(int)ParallelProgramPrefetch.ComputeRefusal.Provider]}{FormatProviderRefusals(prefetch.TakeProviderRefusals())},inputs={computeRefused[(int)ParallelProgramPrefetch.ComputeRefusal.Inputs]}," + $"ownership={computeRefused[(int)ParallelProgramPrefetch.ComputeRefusal.Ownership]},effects={computeRefused[(int)ParallelProgramPrefetch.ComputeRefusal.Effects]}) " + - $"write_log_refusals={Interlocked.Exchange(ref _writeLogRefusals, 0)} owned_now_clean_refusals={Interlocked.Exchange(ref _ownedNowCleanRefusals, 0)} dispatch_wait_ms={computeWaitMs.ToString("F1", culture)} " + + $"write_log_refusals={Interlocked.Exchange(ref _writeLogRefusals, 0)} superseded_verifies={Interlocked.Exchange(ref _supersededVerifies, 0)} owned_now_clean_refusals={Interlocked.Exchange(ref _ownedNowCleanRefusals, 0)} dispatch_wait_ms={computeWaitMs.ToString("F1", culture)} " + $"dispatch_saved_ms={computeSavedMs.ToString("F1", culture)}"; return $"resolved={resolved} abandoned={abandoned} abandoned_by=({TakeAbandonCauses()}) abandoned_verify={GpuFatal.TakeSpeculativeVerifyFailures()} taken={taken} refused={refused} drains={drains} drained={drained} deferred_barriers={deferredBarriers} operand_reads_kept={operandReadsKept} " + $"wait_ms={waitMs.ToString("F1", culture)} resolve_ms={prefetch.TakeResolveMilliseconds().ToString("F1", culture)} " + @@ -442,12 +444,17 @@ public void NoteCopiedThrough(ulong address, ulong size) // cleared by Forget: a stale flag only costs the re-test. public bool ReliesOnOwned; + // A verify on the resolving thread found a GPU write logged since the resolution began over what it read and + // excused a difference for it (ConcurrentReadsSuperseded): the take refuses the resolution whatever it finds. + public bool Superseded; + // Taken again from the pool for a new resolution. public void Reset((long Overlay, long Labels, ulong GpuWrites, long Images, long GpuModified) versions) { Answers.Clear(); CopiedThrough.Clear(); ReliesOnOwned = false; + Superseded = false; Versions = versions; Array.Fill(_cleanPages, ulong.MaxValue); _nextCleanPage = 0; @@ -682,10 +689,21 @@ internal string TakeAbandonCauses() return builder.ToString(); } - // On the worker: the answers a resolution relied on still hold. + // On the worker: the answers a resolution relied on still hold, and no GPU write logged since it began covers a + // range it read or a destination it read through a pending copy. Every write the worker records while a resolution + // is open belongs to an item ahead of the draw (the worker takes the draw only after them), so the draw sees it; + // once that write has completed its record is gone and a clean answer read before it is clean again (the bytes it + // read are not), which only the log still shows (ACleanReadIsNotCurrentOnceAWriteRecordedAfterItCompletes). internal bool IsConcurrentResolveStillCurrent(object assumptionsObject) { var assumptions = (ConcurrentAssumptions)assumptionsObject; + if (assumptions.Superseded || + (assumptions.WriteLogVersion != _gpuWrites.WriteLogVersion && LoggedWriteCoversRead(assumptions))) + { + Interlocked.Increment(ref _writeLogRefusals); + return false; + } + if (!assumptions.ReliesOnOwned && assumptions.Versions == OwnershipVersions()) { return true; @@ -739,31 +757,98 @@ internal bool IsConcurrentResolveStillCurrent(object assumptionsObject) // nor a destination it read through a pending copy. A write those dispatches recorded may have landed and retired by // now, which the ownership answers alone no longer show; and one over a copied destination, whose owned answer the // copy read dropped, makes it the destination's latest write instead of the copy. - internal bool IsConcurrentResolveStillCurrentAcrossDispatches(object assumptionsObject) + // The write log is tested by IsConcurrentResolveStillCurrent for every take. + internal bool IsConcurrentResolveStillCurrentAcrossDispatches(object assumptionsObject) => + IsConcurrentResolveStillCurrent(assumptionsObject); + + // On a resolving thread ahead of the worker, for a verify that found two readers of one resolution disagreeing: a + // GPU write logged since the resolution began covers what it read, so its reads straddle that write (an answer + // cached before it, a fresh test or a copy read after it) and the take refuses it (latched: Superseded). The worker + // records such a write only for an item ahead of the draw, so the value the draw needs is the one after the write. + // False on the worker, and when the log could not be read whole. + public bool ConcurrentReadsSuperseded() { - var assumptions = (ConcurrentAssumptions)assumptionsObject; - if (assumptions.WriteLogVersion != _gpuWrites.WriteLogVersion) + if (_concurrentAssumptions is not { } assumptions) + { + return false; + } + + if (assumptions.Superseded) + { + return true; + } + + for (var attempt = 0; attempt < 4; attempt++) { - foreach (var (_, address, size, _) in assumptions.Answers) + if (TryLoggedWriteCoversRead(assumptions) is { } covers) { - if (_gpuWrites.LoggedWriteSince(assumptions.WriteLogVersion, address, size)) + assumptions.Superseded = covers; + if (covers) { - Interlocked.Increment(ref _writeLogRefusals); - return false; + Interlocked.Increment(ref _supersededVerifies); } + + return covers; } - foreach (var (start, end) in assumptions.CopiedThrough) + Thread.SpinWait(8); + } + + return false; + } + + private bool? TryLoggedWriteCoversRead(ConcurrentAssumptions assumptions) + { + foreach (var (_, address, size, _) in assumptions.Answers) + { + if (_gpuWrites.TryLoggedWriteSinceSnapshot(assumptions.WriteLogVersion, address, size) is not { } logged) { - if (_gpuWrites.LoggedWriteSince(assumptions.WriteLogVersion, start, end - start)) - { - Interlocked.Increment(ref _writeLogRefusals); - return false; - } + return null; + } + + if (logged) + { + return true; } } - return IsConcurrentResolveStillCurrent(assumptionsObject); + foreach (var (start, end) in assumptions.CopiedThrough) + { + if (_gpuWrites.TryLoggedWriteSinceSnapshot(assumptions.WriteLogVersion, start, end - start) is not { } logged) + { + return null; + } + + if (logged) + { + return true; + } + } + + return false; + } + + // On the worker, which logs: whether a GPU write logged since the resolution began covers a range it answered or read + // through a copy. + private bool LoggedWriteCoversRead(ConcurrentAssumptions assumptions) + { + foreach (var (_, address, size, _) in assumptions.Answers) + { + if (_gpuWrites.LoggedWriteSince(assumptions.WriteLogVersion, address, size)) + { + return true; + } + } + + foreach (var (start, end) in assumptions.CopiedThrough) + { + if (_gpuWrites.LoggedWriteSince(assumptions.WriteLogVersion, start, end - start)) + { + return true; + } + } + + return false; } // A write the command thread queued ahead of the draw being resolved, still waiting for the worker, diff --git a/tests/SharpEmu.Gpu.Metal.Tests/MetalClearFoldingTests.DispatchPrefetch.cs b/tests/SharpEmu.Gpu.Metal.Tests/MetalClearFoldingTests.DispatchPrefetch.cs index 3a47f638c..65d15e251 100644 --- a/tests/SharpEmu.Gpu.Metal.Tests/MetalClearFoldingTests.DispatchPrefetch.cs +++ b/tests/SharpEmu.Gpu.Metal.Tests/MetalClearFoldingTests.DispatchPrefetch.cs @@ -52,7 +52,8 @@ public void ADispatchResolutionIsRefusedWhenAWriteLoggedAfterItCoversWhatItReadE host.NoteGuestMemoryWrite(KernelSource + 0x10, sizeof(uint), MetalGpuWriteOrigin.StorageBuffer); // The store landed and its record retired: the page is unowned again. ((MetalGpuWriteRanges)GpuWritesOfHost.GetValue(host)!).Clear(ulong.MaxValue); - Assert.True(concurrent.IsStillCurrent(assumptions)); + // Every take tests the log: a write the worker recorded after the resolution began is ahead of its draw too. + Assert.False(concurrent.IsStillCurrent(assumptions)); Assert.False(concurrent.IsStillCurrentAcrossDispatches(assumptions)); concurrent.ReleaseAssumptions(assumptions); } diff --git a/tests/SharpEmu.Gpu.Metal.Tests/MetalClearFoldingTests.GuestWordsCompare.cs b/tests/SharpEmu.Gpu.Metal.Tests/MetalClearFoldingTests.GuestWordsCompare.cs index cde2b75b3..80bb523f1 100644 --- a/tests/SharpEmu.Gpu.Metal.Tests/MetalClearFoldingTests.GuestWordsCompare.cs +++ b/tests/SharpEmu.Gpu.Metal.Tests/MetalClearFoldingTests.GuestWordsCompare.cs @@ -173,10 +173,11 @@ public void ARangeAPendingCopyWritesComparesThroughTheCopyAndTheTakeChecksItsSou Assert.False(changed.Equal); concurrent.ReleaseAssumptions(changed.Assumptions); - // A write recorded after the copy over a compared word comes from stream items after the draw, so the take - // accepts a compare made before it exactly as it accepts a word read through the copy made then - // (TryReadThroughPendingCopyConcurrent); a compare made after it refuses, the copy no longer the range's latest - // write, with no owned answer left behind. + // A write over a compared word recorded after the resolution began is one the worker recorded for an item ahead + // of the draw (it takes the draw only after them), the word's latest write, not the copy: the take refuses a + // compare made before it exactly as it refuses a word read through the copy made then (the write log over the + // copied-through range); a compare made after it refuses, the copy no longer the range's latest write, with no + // owned answer left behind. copied[4] ^= 1; recorded = [.. copied, .. recorded.AsSpan(32)]; var before = CompareConcurrent(rig, ranges, recorded); @@ -194,8 +195,8 @@ public void ARangeAPendingCopyWritesComparesThroughTheCopyAndTheTakeChecksItsSou } rig.Host.NoteGuestMemoryWrite(CopyDestination + 0x18, sizeof(uint), MetalGpuWriteOrigin.StorageBuffer); - Assert.True(concurrent.IsStillCurrent(read)); - Assert.True(concurrent.IsStillCurrent(before.Assumptions)); + Assert.False(concurrent.IsStillCurrent(read)); + Assert.False(concurrent.IsStillCurrent(before.Assumptions)); concurrent.ReleaseAssumptions(read); concurrent.ReleaseAssumptions(before.Assumptions); var after = CompareConcurrent(rig, ranges, recorded); diff --git a/tests/SharpEmu.Gpu.Metal.Tests/MetalClearFoldingTests.OwnedCleanReads.cs b/tests/SharpEmu.Gpu.Metal.Tests/MetalClearFoldingTests.OwnedCleanReads.cs index 78409e66b..9fdfdaf4b 100644 --- a/tests/SharpEmu.Gpu.Metal.Tests/MetalClearFoldingTests.OwnedCleanReads.cs +++ b/tests/SharpEmu.Gpu.Metal.Tests/MetalClearFoldingTests.OwnedCleanReads.cs @@ -65,4 +65,73 @@ public void ARefusedCleanReadIsNotCurrentOnceTheWriteThatOwnedItCompletes() concurrent.ReleaseAssumptions(assumptions); } } + + // A clean read, then a GPU write over it recorded by the worker while the resolution is still open (an item ahead of + // the draw), then the write completes: the answer is clean again at the take, but the bytes the resolution read are + // the ones from before the write. The take refuses it while the write is pending and after it completed. + [Theory] + [InlineData(false, false)] + [InlineData(true, false)] + [InlineData(false, true)] + public void ACleanReadIsNotCurrentOnceAWriteRecordedAfterItCompletes(bool resident, bool verifies) + { + if (!RequireDevice()) return; + using var rig = new Rig(Device.Value); + var host = rig.Host; + rig.WriteBacking32(PredicateWord, 0x1111_1111); + + var concurrent = (IConcurrentResolveHost)host; + concurrent.BeginConcurrentResolve(); + object assumptions; + try + { + uint word; + if (resident) + { + Span bytes = stackalloc byte[sizeof(uint)]; + Assert.True(host.TryReadResidentGuestBytes(PredicateWord, bytes, clean: true)); + word = BitConverter.ToUInt32(bytes); + } + else + { + Assert.True(host.TryReadCleanGuestWord(PredicateWord, out word)); + } + + Assert.Equal(0x1111_1111u, word); + Assert.False(host.ConcurrentReadsSuperseded()); + host.NoteGuestMemoryWrite(PredicateWord, sizeof(uint), MetalGpuWriteOrigin.StorageBuffer); + if (verifies) + { + // A verify in this resolution finds its reads straddling the write, and latches the take's refusal. + Assert.True(host.ConcurrentReadsSuperseded()); + } + } + finally + { + assumptions = concurrent.EndConcurrentResolve(); + } + + try + { + Assert.False(((MetalRenderHost.ConcurrentAssumptions)assumptions).ReliesOnOwned, "relies on owned"); + Assert.Equal(verifies, ((MetalRenderHost.ConcurrentAssumptions)assumptions).Superseded); + Assert.False(concurrent.IsStillCurrent(assumptions), "current while the write is pending"); + Assert.False(concurrent.IsStillCurrentAcrossDispatches(assumptions), "current across dispatches while the write is pending"); + + var serial = host.FlushCommandBuffer(); + var deadline = Environment.TickCount64 + 10_000; + while (host.CompletedSerial < serial && Environment.TickCount64 < deadline) + { + Thread.Sleep(1); + } + + Assert.True(host.CompletedSerial >= serial); + Assert.False(concurrent.IsStillCurrentAcrossDispatches(assumptions), "current across dispatches after the write completed"); + Assert.False(concurrent.IsStillCurrent(assumptions), "current after the write completed"); + } + finally + { + concurrent.ReleaseAssumptions(assumptions); + } + } } diff --git a/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/KeptStageInputsTests.ResolveMemo.cs b/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/KeptStageInputsTests.ResolveMemo.cs index 9859df7d0..dce7bcec6 100644 --- a/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/KeptStageInputsTests.ResolveMemo.cs +++ b/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/KeptStageInputsTests.ResolveMemo.cs @@ -272,7 +272,7 @@ public void ResolveMemo_VerifyCountsAStoreBetweenTheHitAndTheFullResolutionAsARa { var failed = VerifyFailedCount(); var (hit, third, report) = VerifyWithDescriptorReads(read => read >= 5); - Assert.Contains("verify_raced=(changed=1,came_and_went=0)", report); + Assert.Contains("verify_raced=(changed=1,came_and_went=0,superseded=0)", report); Assert.Equal(failed, VerifyFailedCount()); Assert.NotSame(hit, third); Assert.Contains(third.PixelInput.Stage.Resources.Buffers, words => words[0] == unchecked((uint)(StreamBase + 0x100))); @@ -284,7 +284,7 @@ public void ResolveMemo_VerifyCountsADifferenceThatCameAndWentAsARace() { var failed = VerifyFailedCount(); var (hit, third, report) = VerifyWithDescriptorReads(read => read == 5); - Assert.Contains("verify_raced=(changed=0,came_and_went=1)", report); + Assert.Contains("verify_raced=(changed=0,came_and_went=1,superseded=0)", report); Assert.Equal(failed, VerifyFailedCount()); Assert.Same(hit, third); } diff --git a/tests/SharpEmu.ShaderCompiler.Tests/Resources/ReadProofTests.cs b/tests/SharpEmu.ShaderCompiler.Tests/Resources/ReadProofTests.cs index f03672d3c..7e7c870fe 100644 --- a/tests/SharpEmu.ShaderCompiler.Tests/Resources/ReadProofTests.cs +++ b/tests/SharpEmu.ShaderCompiler.Tests/Resources/ReadProofTests.cs @@ -287,6 +287,33 @@ public void VerifyStopsOnAWrongProof() Assert.Equal(1, Counter(ResourceMaterializer.TakeReadProofReport(), "verified")); } + // A resolution whose reads straddle a GPU write recorded since it began (the host's ReadsSuperseded, which also makes + // the take refuse it): a verify difference there is counted as superseded, not a wrong proof; otherwise it still stops. + [Fact] + public void VerifyCountsADifferenceInASupersededResolutionWithoutStopping() + { + var (plan, memory, comparer, _) = Setup(); + var superseded = false; + var inputs = new ResourceRuntimeInputs { ReadMemory = memory.Read, CompareGuestWords = comparer.Compare, ReadsSuperseded = () => superseded }; + inputs.UserData = new uint[] { 0x1000, 0, 0, 0 }; + var kept = WithMode(ResourceMaterializer.ReadProofMode.On, () => Materialize(plan, inputs)); + inputs.UserData = new uint[] { 0x1020, 0, 0, 0 }; + var other = WithMode(ResourceMaterializer.ReadProofMode.On, () => Materialize(plan, inputs)); + memory.Words[0] = 0x9000; + ResourceMaterializer.SetReadProofForTest(kept, ResourceMaterializer.ReadProofOf(other)); + + _ = ResourceMaterializer.TakeReadProofReport(); + Assert.Throws(() => + WithMode(ResourceMaterializer.ReadProofMode.Verify, () => ResourceMaterializer.RevalidateFast(kept))); + var failed = Counter(ResourceMaterializer.TakeReadProofReport(), "verify_failed"); + + superseded = true; + Assert.True(WithMode(ResourceMaterializer.ReadProofMode.Verify, () => ResourceMaterializer.RevalidateFast(kept))); + var report = ResourceMaterializer.TakeReadProofReport(); + Assert.Equal(1, Counter(report, "verify_superseded")); + Assert.Equal(failed, Counter(report, "verify_failed")); + } + // The proof's words: sorted, repeats folded, runs of consecutive words split where they leave a 256-byte line; one // address read as two values refuses the proof. [Fact] From 3c3df55a633adb7730e62e969aa692c00ee901e2 Mon Sep 17 00:00:00 2001 From: kuba Date: Sun, 15 Nov 2026 20:42:14 +0000 Subject: [PATCH 094/178] [Shader] Turn the materializer's read proofs on by default (SHARPEMU_RESOURCE_READ_PROOF=0 turns them off) The verify mismatches that turned them off were resolutions whose reads straddled a GPU write recorded meanwhile, which the take now refuses (dc219d26e). Demon's Souls long in-world run with every verify on (r42-long, 419 s): verify_failed=0, 862 superseded, no fatal; proofs are worth ~5 ms a frame there (median 86.5 -> 81.0 ms). --- .../Resources/ResourceMaterializer.cs | 18 +++++++++++------- 1 file changed, 11 insertions(+), 7 deletions(-) diff --git a/src/SharpEmu.ShaderCompiler/Resources/ResourceMaterializer.cs b/src/SharpEmu.ShaderCompiler/Resources/ResourceMaterializer.cs index ff731d1ea..0a6a04769 100644 --- a/src/SharpEmu.ShaderCompiler/Resources/ResourceMaterializer.cs +++ b/src/SharpEmu.ShaderCompiler/Resources/ResourceMaterializer.cs @@ -403,13 +403,17 @@ public void CarryBackoffTo(FastOrigin rebuilt) } } - // SHARPEMU_RESOURCE_READ_PROOF: off (default: every revalidation evaluates the program word by word), 1 or on, + // SHARPEMU_RESOURCE_READ_PROOF: on (default), 0 or off (every revalidation evaluates the program word by word), // verify (a proved revalidation also evaluates in full and stops when the snapshot is not current). // - // Off by default since 2026-11-15: a Demon's Souls verify run found one proof that held before and after a full - // evaluation that did not give the snapshot ("[SHADER][READ_PROOF] verify mismatch", plan 0x4DFFC096614D79ED, vertex - // stage, 8 ranges, 156 bytes; about one in 200,000 proved revalidations), not yet explained, and in that game the - // proofs bought no resolver time (as many origins change or are recorded again as are proved). + // On by default again since 2026-11-15. The verify mismatches that had turned it off (plans 0x4DFFC096614D79ED, + // 0xB3AB9F05FA5AFAA8, 0x8B94AE10B80DDFCD in Demon's Souls) were resolutions ahead of the GPU worker whose reads + // straddled a GPU write the worker recorded meanwhile: the full evaluation read a line answered clean before the + // write, the proof compared it through the write's copy after it. The draw needs the value after the write; the take + // now refuses every such resolution (the GPU write log, MetalRenderHost.IsConcurrentResolveStillCurrent) and verify + // counts it as verify_superseded. Evidence: long in-world verify run (LOOKAHEAD, READ_PROOF and RESOLVE_MEMO all + // =verify, 419 s) with verify_failed=0, 862 superseded, 15.5M verified, no fatal; proofs worth ~5 ms a frame there + // (median 86.5 ms off vs 81.0 ms on). // // A fast snapshot's revalidation evaluates its program again with the snapshot's own user data, shader base and // readers and compares the words it emits with the snapshot. The evaluation that made the snapshot (or last found it @@ -428,9 +432,9 @@ internal enum ReadProofMode internal static ReadProofMode ParseReadProofMode(string? value) => value?.Trim().ToLowerInvariant() switch { - "1" or "on" => ReadProofMode.On, + "0" or "off" => ReadProofMode.Off, "verify" => ReadProofMode.Verify, - _ => ReadProofMode.Off, + _ => ReadProofMode.On, }; internal static ReadProofMode ReadProofs { get; set; } = ParseReadProofMode(Environment.GetEnvironmentVariable("SHARPEMU_RESOURCE_READ_PROOF")); From a7418b54953fc7c48c58ef4c975204937b3536ef Mon Sep 17 00:00:00 2001 From: kuba Date: Sun, 15 Nov 2026 21:01:50 +0000 Subject: [PATCH 095/178] [GPU] Answer a clean word read under a pending GPU write with the value after that write, and name an invalid DCC texture bd5c2009a made the worker refuse a clean word a pending recorded GPU write covers, as the resolving thread did. For a resource branch's predicate a refusal keeps both paths, and the path the shader does not take has its descriptor read from whatever that memory holds; a descriptor that does not decode then stops the process in the image cache (ImageDescription.Validate: "The DCC metadata is invalid", Demon's Souls r44 at world load, metadata 0x3F8000002000). The write is ahead of the draw, so the value the draw sees is the one after it: the worker now reads it through the write's copy or waits for it (TryReadGuestCore), and a resolving thread reads it through the copy (its owned answer dropped, the source's answers and the copied-through range kept for the take) or abandons the resolution, so both threads keep the same single path. Other owners (images, overlays) refuse as before. Counted on the prefetch line: clean_under_write=(landed, copied, abandoned). SHARPEMU_CLEAN_READ_LANDED=0 refuses again. A texture request whose DCC metadata address is out of range now prints the shader hash, image slot and T# words before the image cache stops on it. --- .../Images/ImageRequestBuilders.Texture.cs | 10 +++ .../V2/MetalRenderHost.ConcurrentResolve.cs | 50 +++++++++++++- .../V2/MetalRenderHost.Pipelines.cs | 37 +++++----- .../MetalClearFoldingTests.OwnedCleanReads.cs | 67 +++++++++++-------- 4 files changed, 120 insertions(+), 44 deletions(-) diff --git a/src/SharpEmu.Libs/Gpu/Images/ImageRequestBuilders.Texture.cs b/src/SharpEmu.Libs/Gpu/Images/ImageRequestBuilders.Texture.cs index 6cfe2c8b8..de66951be 100644 --- a/src/SharpEmu.Libs/Gpu/Images/ImageRequestBuilders.Texture.cs +++ b/src/SharpEmu.Libs/Gpu/Images/ImageRequestBuilders.Texture.cs @@ -250,6 +250,16 @@ public static TextureRequestResolution Texture(ReadOnlySpan words, in Shad } var resolution = BuildTexture(key, shape, shaderHash, imageIndex); + // The image cache stops on such a request (ImageDescription.Validate); name the shader, the slot and the words + // here, where they are known (Demon's Souls r44: DCC metadata at 0x3F8000002000, float bits read as a T#). + if (resolution.Request.Description.Metadata is { Kind: MetadataKind.Dcc } metadata && + (metadata.Range.Address == 0 || metadata.Range.Address >= TrackerLayout.SpaceBytes)) + { + Console.Error.WriteLine( + $"[GPU][IMAGE] texture with invalid DCC metadata: shaderHash=0x{shaderHash:X16} image={imageIndex} " + + $"metadata=0x{metadata.Range.Address:X16} words={string.Join(",", key.ToArray().Select(word => word.ToString("X8")))}."); + } + if (cache.Count >= TextureCacheLimit) { cache.Clear(); diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.ConcurrentResolve.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.ConcurrentResolve.cs index c12fc3da8..0d9aece7a 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.ConcurrentResolve.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.ConcurrentResolve.cs @@ -64,6 +64,13 @@ internal sealed partial class MetalRenderHost : IConcurrentResolveHost bool IConcurrentResolveHost.IsStillCurrentAcrossDispatches(object assumptions) => IsConcurrentResolveStillCurrentAcrossDispatches(assumptions); private long _writeLogRefusals; + // Clean word reads under a pending recorded GPU write: on the worker answered with the landed value (through the copy + // or after a wait); on a resolving thread answered through the copy, or the resolution abandoned. + private long _cleanReadsLanded; + // SHARPEMU_CLEAN_READ_LANDED=0: such a clean read is refused on both threads again (bd5c2009a). + internal static bool CleanReadsLanded { get; set; } = Environment.GetEnvironmentVariable("SHARPEMU_CLEAN_READ_LANDED") != "0"; + private long _cleanReadsCopied; + private long _cleanReadsAbandoned; // Verify differences excused because a GPU write logged since the resolution began covers what it read. private long _supersededVerifies; // Takes refused because an owned answer (a refused clean or resident read) is clean now. @@ -172,7 +179,7 @@ private string FormatPrefetchCounters() var dispatches = $" dispatch_jobs={computeSubmitted} dispatch_taken={computeTaken} dispatch_refused=(abandoned={computeRefused[(int)ParallelProgramPrefetch.ComputeRefusal.Abandoned]}," + $"provider={computeRefused[(int)ParallelProgramPrefetch.ComputeRefusal.Provider]}{FormatProviderRefusals(prefetch.TakeProviderRefusals())},inputs={computeRefused[(int)ParallelProgramPrefetch.ComputeRefusal.Inputs]}," + $"ownership={computeRefused[(int)ParallelProgramPrefetch.ComputeRefusal.Ownership]},effects={computeRefused[(int)ParallelProgramPrefetch.ComputeRefusal.Effects]}) " + - $"write_log_refusals={Interlocked.Exchange(ref _writeLogRefusals, 0)} superseded_verifies={Interlocked.Exchange(ref _supersededVerifies, 0)} owned_now_clean_refusals={Interlocked.Exchange(ref _ownedNowCleanRefusals, 0)} dispatch_wait_ms={computeWaitMs.ToString("F1", culture)} " + + $"write_log_refusals={Interlocked.Exchange(ref _writeLogRefusals, 0)} superseded_verifies={Interlocked.Exchange(ref _supersededVerifies, 0)} owned_now_clean_refusals={Interlocked.Exchange(ref _ownedNowCleanRefusals, 0)} clean_under_write=(landed={Interlocked.Exchange(ref _cleanReadsLanded, 0)},copied={Interlocked.Exchange(ref _cleanReadsCopied, 0)},abandoned={Interlocked.Exchange(ref _cleanReadsAbandoned, 0)}) dispatch_wait_ms={computeWaitMs.ToString("F1", culture)} " + $"dispatch_saved_ms={computeSavedMs.ToString("F1", culture)}"; return $"resolved={resolved} abandoned={abandoned} abandoned_by=({TakeAbandonCauses()}) abandoned_verify={GpuFatal.TakeSpeculativeVerifyFailures()} taken={taken} refused={refused} drains={drains} drained={drained} deferred_barriers={deferredBarriers} operand_reads_kept={operandReadsKept} " + $"wait_ms={waitMs.ToString("F1", culture)} resolve_ms={prefetch.TakeResolveMilliseconds().ToString("F1", culture)} " + @@ -1378,6 +1385,47 @@ private void SynchronizeShaderCodeConcurrent(ulong address, ulong size, Concurre } } + // TryReadCleanGuestWord off the worker. A word a pending recorded GPU write owns is the worker's to read after that + // write (it reads through the copy or waits): read through the copy here too (its source's answers recorded, the + // word's owned answer dropped, as TryReadGuestWordConcurrentTested does), else the resolution is abandoned, so a + // resource branch's predicate never keeps both paths here where the worker keeps one. Any other owner (an image, + // an overlay) refuses the read as before. + private bool TryReadCleanGuestWordConcurrent(ulong address, out uint word, ConcurrentAssumptions assumptions) + { + word = 0; + Span bytes = stackalloc byte[sizeof(uint)]; + if (!IsOwnedRecorded(ConcurrentQuery.Resident, address, sizeof(uint), assumptions)) + { + if (!_backing.TryReadBacking(address, bytes)) + { + return false; + } + + word = System.Buffers.Binary.BinaryPrimitives.ReadUInt32LittleEndian(bytes); + return true; + } + + var owner = _lastConcurrentOwner; + if (owner != AbandonCause.GpuWrite || !CleanReadsLanded) + { + return false; + } + + var answers = assumptions.Answers.Count; + if (TryReadThroughPendingCopyConcurrent(address, bytes, assumptions)) + { + assumptions.Forget(ConcurrentQuery.Resident, address, sizeof(uint), answers); + Interlocked.Increment(ref _cleanReadsCopied); + word = System.Buffers.Binary.BinaryPrimitives.ReadUInt32LittleEndian(bytes); + return true; + } + + _lastConcurrentOwner = owner; + Interlocked.Increment(ref _cleanReadsAbandoned); + NoteAbandonCause(address, sizeof(uint)); + throw new GpuFatal.AbandonedWorkException($"The resolution reads a clean word a pending GPU write owns: address=0x{address:X16}."); + } + // The clean and resident readers refuse owned bytes on the worker too, so off it they refuse // them the same way, and record the answer. private bool TryReadResidentGuestBytesConcurrent(ulong address, Span destination, ConcurrentAssumptions assumptions) => diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Pipelines.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Pipelines.cs index db35a24fb..4c0069824 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Pipelines.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Pipelines.cs @@ -1879,28 +1879,35 @@ public bool TryReadCleanGuestWord(ulong address, out uint word) word = 0; if (_concurrentAssumptions is { } assumptions) { - Span concurrent = stackalloc byte[sizeof(uint)]; - if (!TryReadResidentGuestBytesConcurrent(address, concurrent, assumptions)) - { - return false; - } - - word = System.Buffers.Binary.BinaryPrimitives.ReadUInt32LittleEndian(concurrent); - return true; + return TryReadCleanGuestWordConcurrent(address, out word, assumptions); } - // A recorded GPU write still landing in the word owns it as an image does: the backing still holds the bytes - // from before the write, which the GPU will not see. Refused, as the resident reader below and the resolving - // thread's test (ConcurrentOwner) refuse it, so a clean answer is the same on every thread; a resource branch's - // predicate read here otherwise kept one path on the worker and both on the resolver. - if (_imageCache.HasGpuModifiedImageBytes(address, sizeof(uint)) || - (_gpuWrites.MayCover(address, sizeof(uint)) && _gpuWrites.PendingSerial(address, sizeof(uint), CompletedSerial) != 0)) + if (_imageCache.HasGpuModifiedImageBytes(address, sizeof(uint))) { return false; } + // A recorded GPU write still landing in the word is ahead of the draw being resolved, which on the GPU reads the + // word after it: read through the write's copy, or after waiting for it (TryReadGuestCore), the value the draw + // sees. Neither the stale backing (one resource branch kept on the worker, both on the resolver: bd5c2009a) nor a + // refusal (both paths kept: the path the shader does not take had its descriptor read from whatever that memory + // held, floats in Demon's Souls, which fataled as an invalid image) is that value. The resolving thread reads it + // through the copy as well, or abandons (TryReadCleanGuestWordConcurrent). Span bytes = stackalloc byte[sizeof(uint)]; - if (!_backing.TryReadBacking(address, bytes)) + if (_gpuWrites.MayCover(address, sizeof(uint)) && _gpuWrites.PendingSerial(address, sizeof(uint), CompletedSerial) != 0) + { + if (!CleanReadsLanded) + { + return false; + } + + Interlocked.Increment(ref _cleanReadsLanded); + if (!TryReadGuestCore(address, bytes)) + { + return false; + } + } + else if (!_backing.TryReadBacking(address, bytes)) { return false; } diff --git a/tests/SharpEmu.Gpu.Metal.Tests/MetalClearFoldingTests.OwnedCleanReads.cs b/tests/SharpEmu.Gpu.Metal.Tests/MetalClearFoldingTests.OwnedCleanReads.cs index 9fdfdaf4b..9b9f24938 100644 --- a/tests/SharpEmu.Gpu.Metal.Tests/MetalClearFoldingTests.OwnedCleanReads.cs +++ b/tests/SharpEmu.Gpu.Metal.Tests/MetalClearFoldingTests.OwnedCleanReads.cs @@ -3,21 +3,23 @@ using SharpEmu.Gpu.Metal.V2; using SharpEmu.Libs.Gpu.Rendering; +using SharpEmu.Libs.Gpu.Scheduling; using Xunit; namespace SharpEmu.Gpu.Metal.Tests; /// -/// A clean read a recorded GPU write still owns is refused on every thread (a resource branch's predicate then keeps both -/// paths), and a resolution that relied on that refusal is not current once the write has completed: the worker would -/// answer the read now and prune a path, so the take refuses the resolution even while no ownership version moved. +/// A clean read of a word a recorded GPU write still owns answers the value the draw sees, after that write: the worker +/// reads it through the write's copy or waits for it, a resolving thread reads it through the copy or abandons. Neither +/// refuses (a resource branch's predicate then kept both paths, and the untaken path's descriptor, read from memory holding +/// floats, fataled as an invalid image in Demon's Souls) nor answers the bytes from before the write. /// public sealed unsafe partial class MetalClearFoldingTests { private const ulong PredicateWord = GuestBase + 0x3A000; [Fact] - public void ARefusedCleanReadIsNotCurrentOnceTheWriteThatOwnedItCompletes() + public void ACleanReadUnderAPendingWriteAbandonsTheResolutionAndTheWorkerReadsTheLandedValue() { if (!RequireDevice()) return; using var rig = new Rig(Device.Value); @@ -25,45 +27,54 @@ public void ARefusedCleanReadIsNotCurrentOnceTheWriteThatOwnedItCompletes() rig.WriteBacking32(PredicateWord, 0); host.NoteGuestMemoryWrite(PredicateWord, sizeof(uint), MetalGpuWriteOrigin.StorageBuffer); - // The worker refuses it as the resolving thread does. - Assert.False(host.TryReadCleanGuestWord(PredicateWord, out _)); - var concurrent = (IConcurrentResolveHost)host; concurrent.BeginConcurrentResolve(); - object assumptions; try { - Assert.False(host.TryReadCleanGuestWord(PredicateWord, out _)); + Assert.Throws(() => host.TryReadCleanGuestWord(PredicateWord, out _)); } finally { - assumptions = concurrent.EndConcurrentResolve(); + concurrent.ReleaseAssumptions(concurrent.EndConcurrentResolve()); } + // The worker waits for the write and reads what it left (the backing, here: the write is only recorded). + var serial = host.SubmissionSerial; + rig.WriteBacking32(PredicateWord, 0x1234); + Assert.True(host.TryReadCleanGuestWord(PredicateWord, out var word)); + Assert.Equal(0x1234u, word); + Assert.True(host.CompletedSerial >= serial); + } + + [Fact] + public void ACleanReadOfAPendingCopyDestinationIsAnsweredFromItsSourceOnBothThreads() + { + if (!RequireDevice()) return; + using var rig = new Rig(Device.Value); + var host = rig.Host; + var serial = RecordPendingCopy(rig); + var concurrent = (IConcurrentResolveHost)host; + concurrent.BeginConcurrentResolve(); + object assumptions; try { - Assert.True(((MetalRenderHost.ConcurrentAssumptions)assumptions).ReliesOnOwned); - Assert.True(concurrent.IsStillCurrent(assumptions)); - Assert.True(concurrent.IsStillCurrentAcrossDispatches(assumptions)); - - // The GPU completes the write; nothing on the worker retires its record yet, so no ownership version moves. - var serial = host.FlushCommandBuffer(); - var deadline = Environment.TickCount64 + 10_000; - while (host.CompletedSerial < serial && Environment.TickCount64 < deadline) - { - Thread.Sleep(1); - } - - Assert.True(host.CompletedSerial >= serial); - Assert.False(concurrent.IsStillCurrent(assumptions)); - Assert.False(concurrent.IsStillCurrentAcrossDispatches(assumptions)); - Assert.True(host.TryReadCleanGuestWord(PredicateWord, out var word)); - Assert.Equal(0u, word); + Assert.True(host.TryReadCleanGuestWord(CopyDestination + 6 * sizeof(uint), out var copied)); + Assert.Equal(0xA002u, copied); } finally { - concurrent.ReleaseAssumptions(assumptions); + assumptions = concurrent.EndConcurrentResolve(); } + + // The destination's owned answer is dropped (the copy writes it either way); the source's answers stand. + Assert.DoesNotContain(((MetalRenderHost.ConcurrentAssumptions)assumptions).Answers, answer => answer.Owned); + Assert.True(concurrent.IsStillCurrent(assumptions)); + concurrent.ReleaseAssumptions(assumptions); + + Assert.True(host.TryReadCleanGuestWord(CopyDestination + 6 * sizeof(uint), out var word)); + Assert.Equal(0xA002u, word); + // Answered from the source without a wait. + Assert.True(host.CompletedSerial < serial); } // A clean read, then a GPU write over it recorded by the worker while the resolution is still open (an item ahead of From 7defb18acca12244fef4c39ddc5d54624a988103 Mon Sep 17 00:00:00 2001 From: kuba Date: Sun, 15 Nov 2026 21:47:37 +0000 Subject: [PATCH 096/178] [GPU] Refuse a dispatch job resolved under another program cache stamp, and verify taken dispatch jobs A dispatch's prefetch job now records the program cache stamp before it resolves (Job.ProgramState, as draw jobs do since 9ad62cc4a); a take under another stamp is refused and counted (dispatch_refused replanned=). With SHARPEMU_PREFETCH_DRAW_LOOKAHEAD=verify (or SHARPEMU_PERF_VERIFY=1) the worker resolves every taken dispatch job again through the side-effect-free ahead path and compares program, launch inputs and stage resources (GraphicsProgramsComparer.ComputeDifference). A difference under answers that moved (IsStillCurrentAcrossDispatches, which covers a GPU write logged since the resolution began) is a race: refused, counted, the dispatch resolves itself. Any other is fatal and names the job, gate, executed-at-start, looked-over items, effects and stamps. The job's assumptions stay alive until the comparison. Counters: dispatch_verify=(verified,raced,failed) on the prefetch line. --- .../Gpu/Pipelines/GraphicsProgramsComparer.cs | 34 ++++++++ .../Gpu/Rendering/ParallelProgramPrefetch.cs | 87 ++++++++++++++++++- .../V2/MetalRenderHost.ConcurrentResolve.cs | 2 +- .../ParallelProgramPrefetchComputeTests.cs | 55 ++++++++++++ 4 files changed, 175 insertions(+), 3 deletions(-) diff --git a/src/SharpEmu.Libs/Gpu/Pipelines/GraphicsProgramsComparer.cs b/src/SharpEmu.Libs/Gpu/Pipelines/GraphicsProgramsComparer.cs index d132ae3ea..6bbfcd0c1 100644 --- a/src/SharpEmu.Libs/Gpu/Pipelines/GraphicsProgramsComparer.cs +++ b/src/SharpEmu.Libs/Gpu/Pipelines/GraphicsProgramsComparer.cs @@ -206,6 +206,40 @@ private static bool SameClipSpace(in ClipSpaceTransform memo, in ClipSpaceTransf return StageDifference("pixel", memo.Stage, full.Stage); } + // A dispatch's two resolutions (ParallelProgramPrefetch's compute verify): what the executor branches on, the + // program, every launch input and the stage as Difference compares a draw's. Null when they hand it the same. + public static string? ComputeDifference(ComputeProgram ahead, ComputeProgram worker) + { + if (ahead.Available != worker.Available) return "available"; + if (ahead.Consumed != worker.Consumed) return "consumed"; + if ((ahead.ImageCopy is null) != (worker.ImageCopy is null)) return "image_copy"; + if ((ahead.KnownWrite is null) != (worker.KnownWrite is null)) return "known_write"; + if (ahead.Program != worker.Program) return "compute_program"; + var (a, w) = (ahead.Input, worker.Input); + if (ReferenceEquals(a, w)) return null; + if (a.ThreadsX != w.ThreadsX || a.ThreadsY != w.ThreadsY || a.ThreadsZ != w.ThreadsZ) return "compute.threads"; + if (a.DispatchThreadDimensions != w.DispatchThreadDimensions || a.DispatchThreadsX != w.DispatchThreadsX || + a.DispatchThreadsY != w.DispatchThreadsY || a.DispatchThreadsZ != w.DispatchThreadsZ) return "compute.dispatch_threads"; + if (a.GroupIdX != w.GroupIdX || a.GroupIdY != w.GroupIdY || a.GroupIdZ != w.GroupIdZ || a.ThreadIdCount != w.ThreadIdCount || + a.ThreadGroupSizeEnabled != w.ThreadGroupSizeEnabled || a.WorkgroupRegister != w.WorkgroupRegister) return "compute.ids"; + if (a.WaveSize != w.WaveSize || a.LocalDataShareDwords != w.LocalDataShareDwords || a.ScratchDwords != w.ScratchDwords || + a.NeedsLocalDataShareBarriers != w.NeedsLocalDataShareBarriers) return "compute.launch"; + if (a.IeeeMode != w.IeeeMode || a.FloatMode != w.FloatMode || a.Dx10Clamp != w.Dx10Clamp) return "compute.float_mode"; + return StageDifference("compute", a.Stage, w.Stage); + } + + // For the compute verify's fatal: each side's program and stage, and how their stages differ (DescribeStages). + public static string DescribeCompute(ComputeProgram ahead, ComputeProgram worker) + { + static string Side(ComputeProgram program) => program.Input.Stage.Program is not { } stage + ? $"available={program.Available} cs=0x{program.Program.Id:X}/0x{program.Program.Module:X} stage=none" + : $"available={program.Available} cs=0x{program.Program.Id:X}/0x{program.Program.Module:X} hash=0x{stage.Hash:X16} " + + $"base=0x{program.Input.Stage.ShaderBase:X} buffers={program.Input.Stage.Resources.Buffers.Length} " + + $"images={program.Input.Stage.Resources.Images.Length} table={program.Input.Stage.Resources.FlattenedResourceTable.Length}"; + + return $"ahead=[{Side(ahead)}] worker=[{Side(worker)}] stages=[{DescribeStage(ahead.Input.Stage, worker.Input.Stage)}]"; + } + private static string? StageDifference(string stage, in ShaderStageResources memo, in ShaderStageResources full) { if (!ReferenceEquals(memo.Program, full.Program)) return stage + ".program"; diff --git a/src/SharpEmu.Libs/Gpu/Rendering/ParallelProgramPrefetch.cs b/src/SharpEmu.Libs/Gpu/Rendering/ParallelProgramPrefetch.cs index 4a3d45d44..0845800c9 100644 --- a/src/SharpEmu.Libs/Gpu/Rendering/ParallelProgramPrefetch.cs +++ b/src/SharpEmu.Libs/Gpu/Rendering/ParallelProgramPrefetch.cs @@ -318,9 +318,15 @@ public enum ComputeRefusal // A dispatch it was resolved ahead of did more than encode GPU work (NoteDispatchEffect), or a collector call it // was resolved ahead of noted an effect (NoteCollect). Effects, + // The program cache stamp moved since the resolution began (Job.ProgramState), as DrawLookaheadRefusal.Replanned. + Replanned, Count, } + // =verify: taken dispatch jobs the worker resolved again and compared (VerifyCompute), those whose difference the + // moved answers excuse (refused, the dispatch resolves itself), and those that differed under answers that held. + private long _computeVerified, _computeVerifyRaced, _computeVerifyFailed; + private long _computeSubmitted; private long _computeTaken; private long _computeWaitTicks; @@ -907,10 +913,17 @@ public bool TryTakeCompute(RegisterBanks banks, uint dispatchInitiator, uint gro var refusal = job.State != 1 ? ComputeRefusal.Abandoned : job.ComputeResult is null ? ComputeRefusal.Provider : !arguments.Matches(dispatchInitiator, groupsX, groupsY, groupsZ, indirect) ? ComputeRefusal.Inputs + : job.ProgramState != _executor.ProgramState ? ComputeRefusal.Replanned : Volatile.Read(ref _lastDispatchEffect) >= job.Gate || Volatile.Read(ref _lastCollectEffect) >= job.Gate ? ComputeRefusal.Effects : !_concurrent.IsStillCurrentAcrossDispatches(job.Assumptions!) ? ComputeRefusal.Ownership : ComputeRefusal.Count; - ReleaseAssumptions(job); + // =verify keeps a taken job's assumptions to its comparison (VerifyCompute), as for a draw's look-ahead. + var verifies = refusal == ComputeRefusal.Count && LookaheadMode == DrawLookaheadMode.Verify; + if (!verifies) + { + ReleaseAssumptions(job); + } + if (refusal != ComputeRefusal.Count) { NoteComputeRefusal(refusal); @@ -922,12 +935,75 @@ public bool TryTakeCompute(RegisterBanks banks, uint dispatchInitiator, uint gro return false; } + program = job.ComputeResult!; + if (verifies) + { + try + { + if (VerifyCompute(job, banks, arguments) is not { } verified) + { + return false; + } + + program = verified; + } + finally + { + ReleaseAssumptions(job); + } + } + Interlocked.Increment(ref _computeTaken); Interlocked.Add(ref _computeSavedTicks, job.ResolveTicks); - program = job.ComputeResult!; return true; } + // SHARPEMU_PREFETCH_DRAW_LOOKAHEAD=verify: the worker resolves the taken dispatch again through the same side-effect-free + // path (nothing consumed, predicted or submitted) and both must hand the executor the same program, inputs and + // resources (GraphicsProgramsComparer.ComputeDifference). The worker's result stands; a difference under answers + // that moved since the resolution (IsStillCurrentAcrossDispatches, which refuses a GPU write logged since it began + // over what it read) is a race, refused and counted, and the dispatch resolves itself; any other is fatal. + private ComputeProgram? VerifyCompute(Job job, RegisterBanks banks, ComputeArguments arguments) + { + var resolved = _executor.ResolveComputeProgramAhead(banks, arguments.DispatchInitiator, arguments.GroupsX, arguments.GroupsY, + arguments.GroupsZ, arguments.Indirect, out var workerRefusal); + Interlocked.Increment(ref _computeVerified); + var difference = resolved is null + ? $"worker_refused={workerRefusal}" + : SharpEmu.Libs.Gpu.Pipelines.GraphicsProgramsComparer.ComputeDifference(job.ComputeResult!, resolved); + if (difference is null) + { + return resolved; + } + + if (job.Assumptions is { } assumptions && !_concurrent.IsStillCurrentAcrossDispatches(assumptions)) + { + Interlocked.Increment(ref _computeVerifyRaced); + return null; + } + + Interlocked.Increment(ref _computeVerifyFailed); + var executed = Volatile.Read(ref _executedGate); + throw _fatal($"A dispatch's program resolved ahead of it differs from the worker's: {difference} " + + $"(job {job.Index}, gate {job.Gate}, executed at start {job.ExecutedAtStart}, executed now {executed}). " + + (resolved is null ? string.Empty : $"{SharpEmu.Libs.Gpu.Pipelines.GraphicsProgramsComparer.DescribeCompute(job.ComputeResult!, resolved)} ") + + $"looked_over=[{DescribeLookedOver(job.ExecutedAtStart, executed)}] " + + $"last_dispatch_effect={Volatile.Read(ref _lastDispatchEffect)} last_collect_effect={Volatile.Read(ref _lastCollectEffect)} " + + $"stamp_ahead={job.ProgramState} stamp_now={_executor.ProgramState} " + + $"state_ahead=[{job.ResolveState}] state_now=[{_executor.DescribeProgramState()}]."); + } + + public (long Verified, long Raced, long Failed) TakeComputeVerifyCounters() => + (Interlocked.Exchange(ref _computeVerified, 0), Interlocked.Exchange(ref _computeVerifyRaced, 0), + Interlocked.Exchange(ref _computeVerifyFailed, 0)); + + // The dispatch counters beyond TakeComputeCounters, for the host's prefetch line: the compute verify's. + public string TakeComputeReport() + { + var verify = TakeComputeVerifyCounters(); + return $"dispatch_verify=(verified={verify.Verified},raced={verify.Raced},failed={verify.Failed})"; + } + // Why a draw's job was not resolved when its draw took it: still gated on the work before it, the resolving // thread busy with another job, or queued behind others with its gate open (takes_unresolved). private long _unresolvedGated, _unresolvedBusy, _unresolvedQueued; @@ -1315,8 +1391,15 @@ private void ResolveCore(Job job) { // Only a dispatch's job keeps its resolving time (dispatch_saved_ms); a draw's read the clock for nothing. var started = System.Diagnostics.Stopwatch.GetTimestamp(); + // Before the lookup, as for a draw: a take under another stamp is refused (ComputeRefusal.Replanned). + job.ProgramState = _executor.ProgramState; job.ComputeResult = _executor.ResolveComputeProgramAhead(job.Banks, compute.DispatchInitiator, compute.GroupsX, compute.GroupsY, compute.GroupsZ, compute.Indirect, out job.ComputeRefusal); + if (RecordsForVerify) + { + job.ResolveState = _executor.DescribeProgramState(); + } + job.Assumptions = _concurrent.EndConcurrentResolve(); // The dispatch's binding decode joins its resolution (IConcurrentResolveHost.PrepareBindingsAhead). if (job.ComputeResult is { Available: true, Consumed: false, ImageCopy: null } resolved) diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.ConcurrentResolve.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.ConcurrentResolve.cs index 0d9aece7a..5b0f35bc4 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.ConcurrentResolve.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.ConcurrentResolve.cs @@ -178,7 +178,7 @@ private string FormatPrefetchCounters() var (computeSubmitted, computeTaken, computeRefused, computeWaitMs, computeSavedMs) = prefetch.TakeComputeCounters(); var dispatches = $" dispatch_jobs={computeSubmitted} dispatch_taken={computeTaken} dispatch_refused=(abandoned={computeRefused[(int)ParallelProgramPrefetch.ComputeRefusal.Abandoned]}," + $"provider={computeRefused[(int)ParallelProgramPrefetch.ComputeRefusal.Provider]}{FormatProviderRefusals(prefetch.TakeProviderRefusals())},inputs={computeRefused[(int)ParallelProgramPrefetch.ComputeRefusal.Inputs]}," + - $"ownership={computeRefused[(int)ParallelProgramPrefetch.ComputeRefusal.Ownership]},effects={computeRefused[(int)ParallelProgramPrefetch.ComputeRefusal.Effects]}) " + + $"ownership={computeRefused[(int)ParallelProgramPrefetch.ComputeRefusal.Ownership]},effects={computeRefused[(int)ParallelProgramPrefetch.ComputeRefusal.Effects]},replanned={computeRefused[(int)ParallelProgramPrefetch.ComputeRefusal.Replanned]}) {prefetch.TakeComputeReport()} " + $"write_log_refusals={Interlocked.Exchange(ref _writeLogRefusals, 0)} superseded_verifies={Interlocked.Exchange(ref _supersededVerifies, 0)} owned_now_clean_refusals={Interlocked.Exchange(ref _ownedNowCleanRefusals, 0)} clean_under_write=(landed={Interlocked.Exchange(ref _cleanReadsLanded, 0)},copied={Interlocked.Exchange(ref _cleanReadsCopied, 0)},abandoned={Interlocked.Exchange(ref _cleanReadsAbandoned, 0)}) dispatch_wait_ms={computeWaitMs.ToString("F1", culture)} " + $"dispatch_saved_ms={computeSavedMs.ToString("F1", culture)}"; return $"resolved={resolved} abandoned={abandoned} abandoned_by=({TakeAbandonCauses()}) abandoned_verify={GpuFatal.TakeSpeculativeVerifyFailures()} taken={taken} refused={refused} drains={drains} drained={drained} deferred_barriers={deferredBarriers} operand_reads_kept={operandReadsKept} " + diff --git a/tests/SharpEmu.Libs.Tests/Gpu/Rendering/ParallelProgramPrefetchComputeTests.cs b/tests/SharpEmu.Libs.Tests/Gpu/Rendering/ParallelProgramPrefetchComputeTests.cs index d3b12de3b..56f3fa4b8 100644 --- a/tests/SharpEmu.Libs.Tests/Gpu/Rendering/ParallelProgramPrefetchComputeTests.cs +++ b/tests/SharpEmu.Libs.Tests/Gpu/Rendering/ParallelProgramPrefetchComputeTests.cs @@ -42,6 +42,9 @@ private sealed class ConcurrentHost : IConcurrentResolveHost { internal bool Current = true; internal bool CurrentAcrossDispatches = true; + // The answers move after the take's check: the verify's check (the second for the job) sees them moved. + internal bool Raced; + private int _crossChecksSinceRace; internal int Checks, CrossChecks; public void BeginConcurrentResolve() { } public object EndConcurrentResolve() => this; @@ -54,6 +57,11 @@ public bool IsStillCurrent(object assumptions) public bool IsStillCurrentAcrossDispatches(object assumptions) { Interlocked.Increment(ref CrossChecks); + if (Raced && ++_crossChecksSinceRace % 2 == 0) + { + return false; + } + return CurrentAcrossDispatches && IsStillCurrent(assumptions); } } @@ -209,6 +217,53 @@ public void TheExecutorResolvesADispatchItselfOnlyWhenItsJobIsRefused(bool curre Assert.Null(_prefetch.Current); } + // A job resolved before the program cache replaced an entry (its stamp moved) may hold an entry a lookup made now + // would not find: refused as replanned, as a draw's. + [Fact] + public void AJobResolvedBeforeTheProgramCacheMovedIsRefused() + { + var banks = Banks().Snapshot(); + var job = Resolved(banks); + _pipelines.ProgramState = new ProgramStateStamp(1, 0, 0); + Assert.False(Take(banks, job)); + Assert.Equal(1, Refused(ParallelProgramPrefetch.ComputeRefusal.Replanned)); + Assert.True(Take(banks, Resolved(banks))); + } + + // =verify: the worker resolves every taken dispatch job again and compares; a difference under answers that held + // is fatal, one under answers that moved is a race the dispatch resolves itself. + [Fact] + public void VerifyResolvesATakenJobAgainAndCountsOrFailsOnADifference() + { + _prefetch.LookaheadMode = ParallelProgramPrefetch.DrawLookaheadMode.Verify; + var banks = Banks().Snapshot(); + var job = Resolved(banks); + var resolutions = _pipelines.ComputeAheadResolutions; + Assert.True(Take(banks, job)); + Assert.Equal(resolutions + 1, _pipelines.ComputeAheadResolutions); + Assert.Equal("dispatch_verify=(verified=1,raced=0,failed=0)", _prefetch.TakeComputeReport()); + + // The worker now resolves another program while the job's answers moved: a race, refused and counted. + job = Resolved(banks); + var original = _pipelines.Compute; + _pipelines.Compute = new ComputeProgram { Program = new ShaderProgram(0x44), Input = original.Input }; + _concurrent.Raced = true; + Assert.False(Take(banks, job)); + Assert.Equal("dispatch_verify=(verified=1,raced=1,failed=0)", _prefetch.TakeComputeReport()); + + // The same difference under answers that still hold is a hole: fatal, naming the job and the difference. + _pipelines.Compute = original; + job = Resolved(banks); + _concurrent.Raced = false; + _pipelines.Compute = new ComputeProgram { Program = new ShaderProgram(0x44), Input = original.Input }; + var fatal = Assert.Throws(() => Take(banks, job)); + Assert.Contains("compute_program", fatal.Message); + Assert.Contains($"job {job.Index}", fatal.Message); + Assert.Contains("looked_over=[", fatal.Message); + Assert.Contains("stamp_ahead=", fatal.Message); + Assert.Equal("dispatch_verify=(verified=1,raced=0,failed=1)", _prefetch.TakeComputeReport()); + } + // A program that consumed its dispatch counts as an effect for the jobs resolved ahead of it. [Fact] public void AConsumedDispatchNotesAnEffect() From b99217c5bb3bbc5c661e8724397c556c38227bb5 Mon Sep 17 00:00:00 2001 From: kuba Date: Sun, 15 Nov 2026 21:49:04 +0000 Subject: [PATCH 097/178] [GPU] Measure a dispatch job's effects from the start of its resolution, as a draw's Since 425656f95 collector calls no longer raise DispatchGate, so a dispatch job's Gate reaches back over hundreds of items, and the take refused any dispatch or collector effect at or after Gate (dispatch_taken fell from ~16k to ~1k per 2 s). The take now tests both _lastDispatchEffect and _lastCollectEffect against ExecutedAtStart, as TryTakeGraphics does. Invariant (stated in HasComputeEffects): the worker runs item g with _executedGate = g-1, so an effect at item g records g-1, and DeferredCommandThread publishes AdvanceGate(g) in its finally after item g ran; ExecutedAtStart is read before anything the resolution reads, so g-1 >= ExecutedAtStart exactly when item g had not finished before the resolution began. SHARPEMU_PREFETCH_COMPUTE_WINDOW=0 restores the Gate-based test. Counters on the prefetch line: effects_window=(mode,gate=, started=,taken_over=). --- .../Gpu/Rendering/ParallelProgramPrefetch.cs | 45 +++++++++++++- .../ParallelProgramPrefetchComputeTests.cs | 60 ++++++++++++++++++- 2 files changed, 100 insertions(+), 5 deletions(-) diff --git a/src/SharpEmu.Libs/Gpu/Rendering/ParallelProgramPrefetch.cs b/src/SharpEmu.Libs/Gpu/Rendering/ParallelProgramPrefetch.cs index 0845800c9..c43c5bc9b 100644 --- a/src/SharpEmu.Libs/Gpu/Rendering/ParallelProgramPrefetch.cs +++ b/src/SharpEmu.Libs/Gpu/Rendering/ParallelProgramPrefetch.cs @@ -914,9 +914,13 @@ public bool TryTakeCompute(RegisterBanks banks, uint dispatchInitiator, uint gro : job.ComputeResult is null ? ComputeRefusal.Provider : !arguments.Matches(dispatchInitiator, groupsX, groupsY, groupsZ, indirect) ? ComputeRefusal.Inputs : job.ProgramState != _executor.ProgramState ? ComputeRefusal.Replanned - : Volatile.Read(ref _lastDispatchEffect) >= job.Gate || Volatile.Read(ref _lastCollectEffect) >= job.Gate ? ComputeRefusal.Effects + : HasComputeEffects(job) ? ComputeRefusal.Effects : !_concurrent.IsStillCurrentAcrossDispatches(job.Assumptions!) ? ComputeRefusal.Ownership : ComputeRefusal.Count; + if (refusal == ComputeRefusal.Count && job.ExecutedAtStart < Volatile.Read(ref _executedGate)) + { + Interlocked.Increment(ref _computeTakenOver); + } // =verify keeps a taken job's assumptions to its comparison (VerifyCompute), as for a draw's look-ahead. var verifies = refusal == ComputeRefusal.Count && LookaheadMode == DrawLookaheadMode.Verify; if (!verifies) @@ -993,6 +997,41 @@ public bool TryTakeCompute(RegisterBanks banks, uint dispatchInitiator, uint gro $"state_ahead=[{job.ResolveState}] state_now=[{_executor.DescribeProgramState()}]."); } + // Whether a dispatch or collector call that ran after the job's resolution began noted an effect, measured from + // ExecutedAtStart as the draw take does. The worker runs item g with _executedGate = g-1, so an effect at item g + // records g-1 (NoteDispatchEffect, NoteCollect), and AdvanceGate(g) publishes the count only after item g ran. A + // resolution read ExecutedAtStart before anything else, so item g had finished before it read anything exactly when + // g <= ExecutedAtStart; g-1 >= ExecutedAtStart is an item that had not, whose effect it may have missed. Effects + // between Gate and ExecutedAtStart ran before the resolution began and are in what it read. + // SHARPEMU_PREFETCH_COMPUTE_WINDOW=0 measures from Gate again (every item since the earliest allowed start). + private bool HasComputeEffects(Job job) + { + var effect = Math.Max(Volatile.Read(ref _lastDispatchEffect), Volatile.Read(ref _lastCollectEffect)); + var byGate = effect >= job.Gate; + var byStart = effect >= job.ExecutedAtStart; + if (byGate) + { + Interlocked.Increment(ref _computeEffectsByGate); + } + + if (byStart) + { + Interlocked.Increment(ref _computeEffectsByStart); + } + + return ComputeEffectsFromStart ? byStart : byGate; + } + + private static readonly bool ComputeWindowDefault = + Environment.GetEnvironmentVariable("SHARPEMU_PREFETCH_COMPUTE_WINDOW") != "0"; + + // Tests set it on one instance. + internal bool ComputeEffectsFromStart { get; set; } = ComputeWindowDefault; + + // effects_window: jobs that reached the effects test and the old (gate) rule and the new (started) rule each refuse, + // and the taken jobs whose resolution began before at least one item ahead of the dispatch ran. + private long _computeEffectsByGate, _computeEffectsByStart, _computeTakenOver; + public (long Verified, long Raced, long Failed) TakeComputeVerifyCounters() => (Interlocked.Exchange(ref _computeVerified, 0), Interlocked.Exchange(ref _computeVerifyRaced, 0), Interlocked.Exchange(ref _computeVerifyFailed, 0)); @@ -1001,7 +1040,9 @@ public bool TryTakeCompute(RegisterBanks banks, uint dispatchInitiator, uint gro public string TakeComputeReport() { var verify = TakeComputeVerifyCounters(); - return $"dispatch_verify=(verified={verify.Verified},raced={verify.Raced},failed={verify.Failed})"; + return $"effects_window=(mode={(ComputeEffectsFromStart ? "started" : "gate")},gate={Interlocked.Exchange(ref _computeEffectsByGate, 0)}," + + $"started={Interlocked.Exchange(ref _computeEffectsByStart, 0)},taken_over={Interlocked.Exchange(ref _computeTakenOver, 0)}) " + + $"dispatch_verify=(verified={verify.Verified},raced={verify.Raced},failed={verify.Failed})"; } // Why a draw's job was not resolved when its draw took it: still gated on the work before it, the resolving diff --git a/tests/SharpEmu.Libs.Tests/Gpu/Rendering/ParallelProgramPrefetchComputeTests.cs b/tests/SharpEmu.Libs.Tests/Gpu/Rendering/ParallelProgramPrefetchComputeTests.cs index 56f3fa4b8..185bc6983 100644 --- a/tests/SharpEmu.Libs.Tests/Gpu/Rendering/ParallelProgramPrefetchComputeTests.cs +++ b/tests/SharpEmu.Libs.Tests/Gpu/Rendering/ParallelProgramPrefetchComputeTests.cs @@ -217,6 +217,60 @@ public void TheExecutorResolvesADispatchItselfOnlyWhenItsJobIsRefused(bool curre Assert.Null(_prefetch.Current); } + // Effects count from the moment the resolution began (ExecutedAtStart), as for a draw: an effect at an item that ran + // after the job's gate opened but before its resolution read anything is in what it read, and the job is taken; one + // at an item that ran after the resolution began is refused. SHARPEMU_PREFETCH_COMPUTE_WINDOW=0 (the property) + // measures from the gate again and refuses both. + [Theory] + [InlineData(true)] + [InlineData(false)] + public void EffectsCountFromTheStartOfTheResolutionUnlessTheWindowIsOff(bool fromStart) + { + _prefetch.ComputeEffectsFromStart = fromStart; + var banks = Banks().Snapshot(); + // Item 1 ran; item 2 (the worker runs it with the count at 1) noted an effect and ran; then the job, gated on + // item 1, begins its resolution with two items run. + _prefetch.AdvanceGate(1); + _prefetch.NoteDispatchEffect(); + _prefetch.AdvanceGate(2); + var before = _prefetch.SubmitCompute(banks, 1, Initiator, 4, 2, 1, false); + _prefetch.WaitIdle(); + Assert.Equal(2, before.ExecutedAtStart); + Assert.Equal(fromStart, Take(banks, before)); + Assert.Equal(fromStart ? 0 : 1, Refused(ParallelProgramPrefetch.ComputeRefusal.Effects)); + Assert.Contains($"effects_window=(mode={(fromStart ? "started" : "gate")},gate=1,started=0,taken_over=0)", + _prefetch.TakeComputeReport()); + + // A job resolved with two items run, then item 3 notes an effect: refused under either rule. + var after = _prefetch.SubmitCompute(banks, 2, Initiator, 4, 2, 1, false); + _prefetch.WaitIdle(); + _prefetch.NoteDispatchEffect(); + _prefetch.AdvanceGate(3); + Assert.False(Take(banks, after)); + Assert.Equal(1, Refused(ParallelProgramPrefetch.ComputeRefusal.Effects)); + Assert.Contains("gate=1,started=1,", _prefetch.TakeComputeReport()); + + // A collector call's effect follows the same rule. + var collected = _prefetch.SubmitCompute(banks, 2, Initiator, 4, 2, 1, false); + _prefetch.WaitIdle(); + Assert.Equal(3, collected.ExecutedAtStart); + _prefetch.NoteCollect(effect: true); + _prefetch.AdvanceGate(4); + Assert.False(Take(banks, collected)); + Assert.Equal(1, Refused(ParallelProgramPrefetch.ComputeRefusal.Effects)); + } + + // A taken job whose resolution began before an item ahead of the dispatch ran counts as looked over (taken_over). + [Fact] + public void ATakenJobThatLookedOverAnItemIsCounted() + { + var banks = Banks().Snapshot(); + var job = Resolved(banks, gate: 1); + _prefetch.AdvanceGate(2); + Assert.True(Take(banks, job)); + Assert.Contains("taken_over=1)", _prefetch.TakeComputeReport()); + } + // A job resolved before the program cache replaced an entry (its stamp moved) may hold an entry a lookup made now // would not find: refused as replanned, as a draw's. [Fact] @@ -241,7 +295,7 @@ public void VerifyResolvesATakenJobAgainAndCountsOrFailsOnADifference() var resolutions = _pipelines.ComputeAheadResolutions; Assert.True(Take(banks, job)); Assert.Equal(resolutions + 1, _pipelines.ComputeAheadResolutions); - Assert.Equal("dispatch_verify=(verified=1,raced=0,failed=0)", _prefetch.TakeComputeReport()); + Assert.EndsWith("dispatch_verify=(verified=1,raced=0,failed=0)", _prefetch.TakeComputeReport()); // The worker now resolves another program while the job's answers moved: a race, refused and counted. job = Resolved(banks); @@ -249,7 +303,7 @@ public void VerifyResolvesATakenJobAgainAndCountsOrFailsOnADifference() _pipelines.Compute = new ComputeProgram { Program = new ShaderProgram(0x44), Input = original.Input }; _concurrent.Raced = true; Assert.False(Take(banks, job)); - Assert.Equal("dispatch_verify=(verified=1,raced=1,failed=0)", _prefetch.TakeComputeReport()); + Assert.EndsWith("dispatch_verify=(verified=1,raced=1,failed=0)", _prefetch.TakeComputeReport()); // The same difference under answers that still hold is a hole: fatal, naming the job and the difference. _pipelines.Compute = original; @@ -261,7 +315,7 @@ public void VerifyResolvesATakenJobAgainAndCountsOrFailsOnADifference() Assert.Contains($"job {job.Index}", fatal.Message); Assert.Contains("looked_over=[", fatal.Message); Assert.Contains("stamp_ahead=", fatal.Message); - Assert.Equal("dispatch_verify=(verified=1,raced=0,failed=1)", _prefetch.TakeComputeReport()); + Assert.EndsWith("dispatch_verify=(verified=1,raced=0,failed=1)", _prefetch.TakeComputeReport()); } // A program that consumed its dispatch counts as an effect for the jobs resolved ahead of it. From aed59bb38bdc6dadbb0712ba6818a42cdc7029e7 Mon Sep 17 00:00:00 2001 From: kuba Date: Sun, 15 Nov 2026 21:51:12 +0000 Subject: [PATCH 098/178] [GPU] Predict no CPU kernel writes on a host that consumes none ShaderPipelineCache evaluated every evaluable dispatch on the CPU (WithPrediction), and the resolver refused such dispatches' prefetch jobs (ComputePrefetchRefusal. Prediction, ~6k per 2 s in Demon's Souls). On Metal no consumer of a prediction does anything that reaches rendering or a later resolution: - evaluation reads: PeekMemory -> IShaderPipelineHost.TryPeekResidentGuestBytes, default false (IShaderPipelineHost.cs:207, ShaderPipelineCache.KernelEvaluation.cs:315); Metal does not override it. - consumption: TryConsume -> TryPostKernelWrite, default Unsupported (IShaderPipelineHost.cs:212, KernelEvaluation.cs:161), so Consumed is never set. - ComputeProgram.KnownWrite (same Program and Input as the unpredicted program): RenderRecorder.Compute.cs:310-312 -> IRenderHost.NoteKnownGpuContents, a no-op (IRenderHost.cs:451) Metal does not override; AgcExports.CommandStream.cs:428-430 -> sink NoteKnownWrite, the no-op default (:69), implemented only by the Vulkan command thread; RenderExecutor.Compute.cs:147 -> NoteDispatchEffect (prefetch refusals only); RenderExecutor.Compute.cs:274 -> DispatchRunTally (diagnostic); RenderRecorder.Compute.cs:376 -> Release (buffer pool). - KernelDemand.NoteRead is called only from VulkanVideoPresenter.CommandThread.cs:427. Only the Vulkan presenter implements peek, post and known contents. IShaderPipelineHost.ConsumesKernelPredictions (default false, true on the Vulkan presenter and the test pipeline host) now gates WouldPredict, so WithPrediction and the resolver's Ahead() check both skip evaluation where nothing consumes it. SHARPEMU_METAL_KERNEL_PREDICTIONS=1 predicts as before. --- .../Gpu/Pipelines/IShaderPipelineHost.cs | 5 ++++ .../ShaderPipelineCache.KernelEvaluation.cs | 12 ++++++-- .../Gpu/Pipelines/ShaderPipelineCache.cs | 2 +- .../VulkanVideoPresenter.Pipelines.cs | 3 ++ .../Gpu/Pipelines/CopyKernelTests.cs | 28 +++++++++++++++++++ .../Gpu/Pipelines/PipelineTestSupport.cs | 3 ++ 6 files changed, 50 insertions(+), 3 deletions(-) diff --git a/src/SharpEmu.Libs/Gpu/Pipelines/IShaderPipelineHost.cs b/src/SharpEmu.Libs/Gpu/Pipelines/IShaderPipelineHost.cs index e05befaa6..f4789e668 100644 --- a/src/SharpEmu.Libs/Gpu/Pipelines/IShaderPipelineHost.cs +++ b/src/SharpEmu.Libs/Gpu/Pipelines/IShaderPipelineHost.cs @@ -203,6 +203,11 @@ bool TryCompareResidentGuestBytes(ReadOnlySpan addresses, ReadOnlySpan words, ShaderStage stage, ulong shaderHash, string source) => frontend.NormalizeImageForResolution(words, stage, shaderHash, source, true); + // Whether a CPU kernel prediction (ShaderPipelineCache.KernelEvaluation) can reach anything: the host answers + // TryPeekResidentGuestBytes, TryPostKernelWrite or IRenderHost.NoteKnownGpuContents (and its command stream's + // NoteKnownWrite). Without it no dispatch is evaluated on the CPU. + bool ConsumesKernelPredictions => false; + // A resident read that refuses instead of waiting for pending command-thread work. bool TryPeekResidentGuestBytes(ulong address, Span destination) => false; diff --git a/src/SharpEmu.Libs/Gpu/Pipelines/ShaderPipelineCache.KernelEvaluation.cs b/src/SharpEmu.Libs/Gpu/Pipelines/ShaderPipelineCache.KernelEvaluation.cs index 447c65e99..c32d1e481 100644 --- a/src/SharpEmu.Libs/Gpu/Pipelines/ShaderPipelineCache.KernelEvaluation.cs +++ b/src/SharpEmu.Libs/Gpu/Pipelines/ShaderPipelineCache.KernelEvaluation.cs @@ -112,9 +112,17 @@ private static string TakeKernelRefusals() return _kernelDemands.GetValue(program, _ => new KernelDemand(evaluable)); } + // SHARPEMU_METAL_KERNEL_PREDICTIONS=1: predict on a host that consumes no prediction (Metal) as before, for comparison. + private static readonly bool PredictWithoutConsumer = Environment.GetEnvironmentVariable("SHARPEMU_METAL_KERNEL_PREDICTIONS") == "1"; + + // Whether this cache's dispatches are evaluated on the CPU at all: only on a host that does something with a + // prediction (IShaderPipelineHost.ConsumesKernelPredictions); elsewhere one only costs time and refuses the + // dispatch's prefetch job (ComputePrefetchRefusal.Prediction). + private bool PredictsKernels => _host.ConsumesKernelPredictions || PredictWithoutConsumer; + // Whether WithPrediction evaluates the kernel rather than returning the program as it is. - private static bool WouldPredict(ComputeProgram program, KernelDemand? kernel, ShaderSource? source) => - kernel is not null && source is not null && program.Available && !program.Consumed && + private bool WouldPredict(ComputeProgram program, KernelDemand? kernel, ShaderSource? source) => + PredictsKernels && kernel is not null && source is not null && program.Available && !program.Consumed && source.Registered.Frontend?.NormalizeBufferDescriptor is null; private ComputeProgram WithPrediction( diff --git a/src/SharpEmu.Libs/Gpu/Pipelines/ShaderPipelineCache.cs b/src/SharpEmu.Libs/Gpu/Pipelines/ShaderPipelineCache.cs index 9ddf4883e..affb25bf1 100644 --- a/src/SharpEmu.Libs/Gpu/Pipelines/ShaderPipelineCache.cs +++ b/src/SharpEmu.Libs/Gpu/Pipelines/ShaderPipelineCache.cs @@ -2000,7 +2000,7 @@ public ComputeProgram GetComputeProgram(RegisterBanks banks, uint dispatchInitia // A program resolved ahead stands for the dispatch's own only where the dispatch would take it unchanged: // WithPrediction returns it as it is, and no frontend or consumption had a say. - private static ComputeProgram? Ahead(ComputeProgram program, KernelDemand? kernel, ShaderSource? source, out ComputePrefetchRefusal refusal) + private ComputeProgram? Ahead(ComputeProgram program, KernelDemand? kernel, ShaderSource? source, out ComputePrefetchRefusal refusal) { refusal = !program.Available || program.Consumed || program.ImageCopy is not null ? ComputePrefetchRefusal.Unavailable : source?.Registered.Frontend is not null ? ComputePrefetchRefusal.Frontend diff --git a/src/graphics/SharpEmu.Gpu.Vulkan/Presentation/VulkanVideoPresenter.Pipelines.cs b/src/graphics/SharpEmu.Gpu.Vulkan/Presentation/VulkanVideoPresenter.Pipelines.cs index d85fb6ba6..ca16583a1 100644 --- a/src/graphics/SharpEmu.Gpu.Vulkan/Presentation/VulkanVideoPresenter.Pipelines.cs +++ b/src/graphics/SharpEmu.Gpu.Vulkan/Presentation/VulkanVideoPresenter.Pipelines.cs @@ -499,6 +499,9 @@ private bool ReadResidentBytesOnCommandThread(ulong address, Span destinat return true; } + // It answers peeks, posts kernel writes and shadows known GPU contents. + public bool ConsumesKernelPredictions => true; + public bool TryPeekResidentGuestBytes(ulong address, Span destination) { if (HasPendingMemoryPublication(address, (ulong)destination.Length)) diff --git a/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/CopyKernelTests.cs b/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/CopyKernelTests.cs index 6c575e964..711458462 100644 --- a/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/CopyKernelTests.cs +++ b/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/CopyKernelTests.cs @@ -305,6 +305,34 @@ public void AFullyEvaluatedDispatch_IsConsumedAndItsWordsLandAsAStoreBehindEarli Assert.Equal(Untouched, Destination(guest, ConsumedWords.Length + 1)[^1]); } + // A host that consumes no prediction (Metal: no peek, no posted store, no known contents) gets the program as it is: + // nothing evaluated, consumed or known, and the dispatch's job resolved ahead stands for it. + [Theory] + [InlineData(true)] + [InlineData(false)] + public void AHostThatConsumesNoPrediction_EvaluatesNothingAndTheResolutionAheadStands(bool consumes) + { + var guest = Guest(elementCount: 10, parameter: 4, [1, 2, 3, 4]); + var stream = new FakeKernelWriteStream(guest.Memory); + guest.Host.KernelWriteStream = stream; + guest.Host.ConsumesKernelPredictions = consumes; + var banks = new RegisterBanks(message => new InvalidOperationException(message)); + banks.Shader.Compute = Registers(4, 64); + var ahead = new ShaderPipelineCache(guest.Context, guest.Host, guest.Compiler, guest.Registry) + .ResolveComputeProgramAhead(banks, 0x8001, 1, 1, 1, indirect: false, out var refusal); + var result = new ShaderPipelineCache(guest.Context, guest.Host, guest.Compiler, guest.Registry) + .GetComputeProgram(banks, 0x8001, 1, 1, 1, indirect: false); + + Assert.Equal(consumes ? ComputePrefetchRefusal.Prediction : ComputePrefetchRefusal.None, refusal); + Assert.Equal(consumes, ahead is null); + Assert.True(result.Available); + Assert.Equal(consumes, result.Consumed); + Assert.Null(result.KnownWrite); + stream.RunAll(); + Assert.Equal(consumes ? new[] { "store" } : [], stream.Ran); + Assert.Equal(consumes ? 1u : Untouched, Destination(guest, 1)[0]); + } + [Theory] [InlineData(DestinationAddress + 16, false)] [InlineData(DestinationAddress - 4, true)] diff --git a/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/PipelineTestSupport.cs b/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/PipelineTestSupport.cs index ab8544b0a..dd4407e66 100644 --- a/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/PipelineTestSupport.cs +++ b/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/PipelineTestSupport.cs @@ -140,6 +140,9 @@ public bool TryReadResidentGuestBytes(ulong address, Span destination, boo // A pending known write the test names here; a read it covers whole is served from it. public (ulong Address, uint[] Words) Shadow { get; set; } + // It answers peeks and posts kernel writes, so dispatches are evaluated; a test sets false for a host that cannot. + public bool ConsumesKernelPredictions { get; set; } = true; + public bool TryPeekResidentGuestBytes(ulong address, Span destination) { var (shadowAddress, words) = Shadow; From 36aa407576b1c06f03b5fbbe0a9f73aa31528396 Mon Sep 17 00:00:00 2001 From: kuba Date: Sun, 15 Nov 2026 22:32:29 +0000 Subject: [PATCH 099/178] [GPU] Put shader header registrations in the program cache stamp a prefetched resolution is taken under A header registered at a code address changes what a lookup there finds and moves no content epoch, so a job resolved before it could be taken afterwards. Found in review of the take checks. --- src/SharpEmu.Libs/Gpu/Pipelines/ShaderPipelineCache.cs | 5 ++++- src/SharpEmu.Libs/Gpu/Rendering/IShaderPipelineProvider.cs | 2 +- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/src/SharpEmu.Libs/Gpu/Pipelines/ShaderPipelineCache.cs b/src/SharpEmu.Libs/Gpu/Pipelines/ShaderPipelineCache.cs index affb25bf1..d6c1d1e2f 100644 --- a/src/SharpEmu.Libs/Gpu/Pipelines/ShaderPipelineCache.cs +++ b/src/SharpEmu.Libs/Gpu/Pipelines/ShaderPipelineCache.cs @@ -341,7 +341,10 @@ public GraphicsPrograms GetGraphicsPrograms( } } - public ProgramStateStamp ProgramState => new(_programs.ContentEpoch, DeviceDataLoads.Generation, _vertexTables.Generation); + // Shader header registrations are in the stamp too: a header registered at a code address changes what a lookup there + // finds, and it moves no content epoch. + public ProgramStateStamp ProgramState => + new(_programs.ContentEpoch, DeviceDataLoads.Generation, _vertexTables.Generation, ShaderHeaderRegistry.Registrations); public string DescribeProgramState() => $"content_epoch={_programs.ContentEpoch} device_data={DeviceDataLoads.Generation} " + diff --git a/src/SharpEmu.Libs/Gpu/Rendering/IShaderPipelineProvider.cs b/src/SharpEmu.Libs/Gpu/Rendering/IShaderPipelineProvider.cs index 71f9ea45d..4670c791f 100644 --- a/src/SharpEmu.Libs/Gpu/Rendering/IShaderPipelineProvider.cs +++ b/src/SharpEmu.Libs/Gpu/Rendering/IShaderPipelineProvider.cs @@ -344,4 +344,4 @@ bool TryCreateComputePipeline(ComputeInputInfo input, ShaderProgram program, out } /// See . -public readonly record struct ProgramStateStamp(long ContentEpoch, long DeviceData, long Tables); +public readonly record struct ProgramStateStamp(long ContentEpoch, long DeviceData, long Tables, long Registrations = 0); From a7aefce9ec13b0f02166f221d97834335e1c722c Mon Sep 17 00:00:00 2001 From: kuba Date: Sun, 15 Nov 2026 22:59:04 +0000 Subject: [PATCH 100/178] [Diag] SHARPEMU_GC_PAUSES=2: per-GC [GC-DETAIL] line with reason, suspend, mark roots, heap stats, memory load Fields: reason/type (GCStart), suspend_ms/suspend_reason, gc_ms (GCStart..GCEnd), mark_ms and post_mark_ms, mark_*_kb promoted bytes per root kind, gen0/1/2/loh/poh_mb and promoted0-2_kb, pinned, handles, heaps, condemned, gen0_reduction, global_reason, mechanisms, pause_mode, memory_load, desired_kb. =1 output unchanged. --- src/SharpEmu.Logging/GcPauseLog.cs | 362 ++++++++++++++++++++++++++++- 1 file changed, 360 insertions(+), 2 deletions(-) diff --git a/src/SharpEmu.Logging/GcPauseLog.cs b/src/SharpEmu.Logging/GcPauseLog.cs index 9c8427151..43145da18 100644 --- a/src/SharpEmu.Logging/GcPauseLog.cs +++ b/src/SharpEmu.Logging/GcPauseLog.cs @@ -2,6 +2,7 @@ // SPDX-License-Identifier: GPL-2.0-or-later using System.Diagnostics; +using System.Diagnostics.Tracing; using System.Globalization; namespace SharpEmu.Logging; @@ -11,20 +12,28 @@ namespace SharpEmu.Logging; /// is logged as [GC-PAUSE] pid=.. unix_us=.. gen=.. pause_ms=.., on the wall clock the frame-time /// log (SHARPEMU_FRAME_TIMES) names its origin in, so a long frame can be matched with the pause in it. /// The last collection is polled every 50 ms; one that two polls do not separate is missed. +/// SHARPEMU_GC_PAUSES=2 does the same and additionally prints one [GC-DETAIL] line per collection +/// (see ); the =1 output and cost are unchanged. /// public static class GcPauseLog { private const double ThresholdMilliseconds = 10; private static int _started; + private static GcDetailListener? _detail; public static void StartFromEnvironment() { - if (Environment.GetEnvironmentVariable("SHARPEMU_GC_PAUSES") != "1" || - Interlocked.Exchange(ref _started, 1) != 0) + var mode = Environment.GetEnvironmentVariable("SHARPEMU_GC_PAUSES"); + if ((mode != "1" && mode != "2") || Interlocked.Exchange(ref _started, 1) != 0) { return; } + if (mode == "2") + { + _detail = new GcDetailListener(); + } + var thread = new Thread(Poll) { IsBackground = true, Name = "SharpEmu GC pause log" }; thread.Start(); } @@ -59,3 +68,352 @@ private static void Poll() } } } + +/// +/// One [GC-DETAIL] pid=.. index=.. line per collection (only when suspend + GC time reaches the same +/// 10 ms threshold as [GC-PAUSE]; printed at GCRestartEEBegin because GCHeapStats follows GCEnd), from the runtime's GC events at Informational level (keyword 0x1; no +/// GCAllocationTick, so no Verbose cost). Payload fields are read by name. Fields (absent when no event gave them): +/// reason, type (GCStart_V2); suspend_ms, suspend_reason (GCSuspendEEBegin/End); gc_ms (GCStart to GCEnd); +/// mark_ms (first to last GCMarkWithType) and mark_{stack,fq,handles,older,sizedref,overflow,dependent}_kb +/// (promoted bytes summed over heaps); post_mark_ms (last mark event to GCEnd, i.e. plan/relocate/compact/sweep, +/// the runtime has no per-phase events); gen0/1/2/loh/poh_mb and promoted0/1/2_kb, pinned, handles (GCHeapStats_V2); +/// heaps, condemned, gen0_reduction, global_reason, mechanisms (hex bitmask), pause_mode, memory_load (percent), +/// desired_kb (FinalYoungestDesired, the gen0 budget) (GCGlobalHeapHistory_V*). +/// Events carry no shared index except GCStart/GCEnd/GCGlobalHeapHistory (Count), so one in-flight record +/// is assumed: a background GC with foreground GCs nested inside it is reported partially (partial=1). +/// +internal sealed class GcDetailListener : EventListener +{ + private const double ThresholdMilliseconds = 10; + private static readonly string[] Reasons = + { + "AllocSmall", "Induced", "LowMemory", "Empty", "AllocLarge", "OutOfSpaceSOH", "OutOfSpaceLOH", + "InducedNotForced", "Internal", "InducedLowMemory", "InducedCompacting", "LowMemoryHost", "PMFullGC", + "LowMemoryHostBlocking", + }; + private static readonly string[] Types = { "NonConcurrent", "Background", "Foreground" }; + private static readonly string[] SuspendReasons = + { + "Other", "GC", "AppDomainShutdown", "CodePitching", "Shutdown", "Debugger", "GCPrep", "DebuggerSweep", + }; + private static readonly string[] PauseModes = { "Batch", "Interactive", "LowLatency", "SustainedLowLatency", "NoGC" }; + private static readonly string[] MarkNames = + { + "stack", "fq", "handles", "older", "sizedref", "overflow", "dependent", + }; + + private readonly object _lock = new(); + private readonly int _pid = Environment.ProcessId; + private readonly long[] _markBytes = new long[MarkNames.Length]; + private int _errors; + private int _errorsPrinted; + + // In-flight record. Long.MinValue / MinValue mean "not seen". + private DateTime _end, _suspendBegin, _suspendEnd, _gcStart, _firstMark, _lastMark; + private long _suspendReason = long.MinValue, _count = long.MinValue, _reason = long.MinValue, _type = long.MinValue; + private int _markEvents; + private bool _open, _partial; + private readonly long[] _heap = new long[16]; + private bool _haveHeap; + private readonly long[] _global = new long[8]; + private bool _haveGlobal; + + protected override void OnEventSourceCreated(EventSource eventSource) + { + if (eventSource.Name == "Microsoft-Windows-DotNETRuntime") + { + EnableEvents(eventSource, EventLevel.Informational, (EventKeywords)0x1); + } + } + + protected override void OnEventWritten(EventWrittenEventArgs data) + { + var name = data.EventName; + if (name is null || !name.StartsWith("GC", StringComparison.Ordinal)) + { + return; + } + + try + { + lock (_lock) + { + Handle(name, data); + } + } + catch + { + Interlocked.Increment(ref _errors); + } + } + + private void Handle(string name, EventWrittenEventArgs e) + { + if (name.StartsWith("GCSuspendEEBegin", StringComparison.Ordinal)) + { + FlushEnded(); + if (_open && _gcStart != default) + { + // Suspension inside an in-flight (background) GC: keep that record. + return; + } + + Reset(); + _open = true; + _suspendBegin = e.TimeStamp; + _suspendReason = Get(e, "Reason"); + } + else if (name.StartsWith("GCSuspendEEEnd", StringComparison.Ordinal)) + { + _suspendEnd = e.TimeStamp; + } + else if (name.StartsWith("GCStart", StringComparison.Ordinal)) + { + FlushEnded(); + if (_open && _gcStart != default) + { + _partial = true; + Emit(default); + Reset(); + _open = true; + } + + _open = true; + _gcStart = e.TimeStamp; + _count = Get(e, "Count"); + _reason = Get(e, "Reason"); + _type = Get(e, "Type"); + } + else if (name == "GCMarkWithType") + { + if (!_open) + { + return; + } + + var type = Get(e, "Type"); + var bytes = Get(e, "Bytes"); + if (type >= 0 && type < _markBytes.Length && bytes > 0) + { + _markBytes[type] += bytes; + } + + if (_markEvents++ == 0) + { + _firstMark = e.TimeStamp; + } + + _lastMark = e.TimeStamp; + } + else if (name.StartsWith("GCHeapStats", StringComparison.Ordinal)) + { + if (!_open) + { + return; + } + + string[] fields = + { + "GenerationSize0", "TotalPromotedSize0", "GenerationSize1", "TotalPromotedSize1", "GenerationSize2", + "TotalPromotedSize2", "GenerationSize3", "TotalPromotedSize3", "GenerationSize4", "PinnedObjectCount", + "GCHandleCount", "FinalizationPromotedCount", + }; + for (var i = 0; i < fields.Length; i++) + { + _heap[i] = Get(e, fields[i]); + } + + _haveHeap = true; + } + else if (name.StartsWith("GCGlobalHeapHistory", StringComparison.Ordinal)) + { + if (!_open) + { + return; + } + + _global[0] = Get(e, "NumHeaps"); + _global[1] = Get(e, "CondemnedGeneration"); + _global[2] = Get(e, "Gen0ReductionCount"); + _global[3] = Get(e, "Reason"); + _global[4] = Get(e, "GlobalMechanisms"); + _global[5] = Get(e, "PauseMode"); + _global[6] = Get(e, "MemoryPressure"); + _global[7] = Get(e, "FinalYoungestDesired"); + _haveGlobal = true; + } + else if (name.StartsWith("GCEnd", StringComparison.Ordinal)) + { + // GCHeapStats follows GCEnd; the record is printed at GCRestartEEBegin (or by the next GC). + if (_open && _gcStart != default) + { + _end = e.TimeStamp; + } + } + else if (name.StartsWith("GCRestartEEBegin", StringComparison.Ordinal)) + { + FlushEnded(); + } + } + + private void FlushEnded() + { + if (_open && _end != default) + { + Emit(_end); + Reset(); + } + } + + private void Reset() + { + _end = default; + _open = false; + _partial = false; + _suspendBegin = _suspendEnd = _gcStart = _firstMark = _lastMark = default; + _suspendReason = _count = _reason = _type = long.MinValue; + _markEvents = 0; + Array.Clear(_markBytes); + _haveHeap = _haveGlobal = false; + } + + private void Emit(DateTime end) + { + double suspendMs = _suspendBegin != default && _suspendEnd >= _suspendBegin + ? (_suspendEnd - _suspendBegin).TotalMilliseconds : -1; + double gcMs = end != default ? (end - _gcStart).TotalMilliseconds : -1; + if (Math.Max(suspendMs, 0) + Math.Max(gcMs, 0) < ThresholdMilliseconds) + { + return; + } + + var sb = new System.Text.StringBuilder(384); + var ic = CultureInfo.InvariantCulture; + if (_errors != _errorsPrinted) + { + _errorsPrinted = _errors; + sb.Append("[GC-DETAIL] errors=").Append(_errorsPrinted.ToString(ic)).Append('\n'); + } + + sb.Append("[GC-DETAIL] pid=").Append(_pid).Append(" index=").Append(_count.ToString(ic)); + Name(sb, "reason", _reason, Reasons); + Name(sb, "type", _type, Types); + if (suspendMs >= 0) + { + sb.Append(ic, $" suspend_ms={suspendMs:F1}"); + } + + Name(sb, "suspend_reason", _suspendReason, SuspendReasons); + if (gcMs >= 0) + { + sb.Append(ic, $" gc_ms={gcMs:F1}"); + } + + if (_markEvents > 0) + { + sb.Append(ic, $" mark_ms={(_lastMark - _firstMark).TotalMilliseconds:F1}"); + if (end != default) + { + sb.Append(ic, $" post_mark_ms={(end - _lastMark).TotalMilliseconds:F1}"); + } + + for (var i = 0; i < MarkNames.Length; i++) + { + sb.Append(ic, $" mark_{MarkNames[i]}_kb={_markBytes[i] / 1024}"); + } + } + + if (_haveHeap) + { + Kv(sb, "gen0_mb", _heap[0], 20); + Kv(sb, "gen1_mb", _heap[2], 20); + Kv(sb, "gen2_mb", _heap[4], 20); + Kv(sb, "loh_mb", _heap[6], 20); + Kv(sb, "poh_mb", _heap[8], 20); + Kv(sb, "promoted0_kb", _heap[1], 10); + Kv(sb, "promoted1_kb", _heap[3], 10); + Kv(sb, "promoted2_kb", _heap[5], 10); + Kv(sb, "pinned", _heap[9], 0); + Kv(sb, "handles", _heap[10], 0); + } + + if (_haveGlobal) + { + Kv(sb, "heaps", _global[0], 0); + Kv(sb, "condemned", _global[1], 0); + Kv(sb, "gen0_reduction", _global[2], 0); + Name(sb, "global_reason", _global[3], Reasons); + if (_global[4] != long.MinValue) + { + sb.Append(" mechanisms=0x").Append(_global[4].ToString("x", ic)); + } + + Name(sb, "pause_mode", _global[5], PauseModes); + Kv(sb, "memory_load", _global[6], 0); + Kv(sb, "desired_kb", _global[7], 10); + } + + if (_partial) + { + sb.Append(" partial=1"); + } + + Console.Error.WriteLine(sb.ToString()); + } + + private static void Kv(System.Text.StringBuilder sb, string key, long value, int shift) + { + if (value != long.MinValue) + { + sb.Append(' ').Append(key).Append('=').Append((value >> shift).ToString(CultureInfo.InvariantCulture)); + } + } + + private static void Name(System.Text.StringBuilder sb, string key, long value, string[] names) + { + if (value == long.MinValue) + { + return; + } + + sb.Append(' ').Append(key).Append('='); + if (value >= 0 && value < names.Length) + { + sb.Append(names[value]); + } + else + { + sb.Append(value); + } + } + + /// Reads an integer payload field by name; long.MinValue when the field is absent. + private static long Get(EventWrittenEventArgs e, string field) + { + var names = e.PayloadNames; + var payload = e.Payload; + if (names is null || payload is null) + { + return long.MinValue; + } + + for (var i = 0; i < names.Count && i < payload.Count; i++) + { + if (names[i] == field) + { + return payload[i] switch + { + ulong u => (long)u, + long l => l, + uint u => u, + int n => n, + ushort u => u, + byte b => b, + _ => long.MinValue, + }; + } + } + + return long.MinValue; + } +} From 7f7789944565056b871855c168f823b88681f9ba Mon Sep 17 00:00:00 2001 From: kuba Date: Sun, 15 Nov 2026 23:01:13 +0000 Subject: [PATCH 101/178] [Agc] Make no submit-time copy of a command buffer for a host that reads the stream itself sceAgcDriverSubmitDcb rented a buffer, copied the whole command buffer into it, walked it for indirect register tables (one byte[] per table plus a dictionary) and handed the result to the backend. The split backend sends the address and the length only and its GPU process reads guest memory, so in the two-process build every copy was dropped unread, and the rented array was never returned to the pool. In Demon's Souls that was ~19 MB/s of byte[] in the guest process, part of it on the large object heap, on the guest's submitting threads and under both submission gates. IGuestGpuBackend.ConsumesSubmittedCommandBytes (default true) says whether the host reads the copy; RemoteGpuBackend says no. Without a copy the submit still answers MEMORY_FAULT for a buffer that is not mapped (ICpuMemory.CanRead). --- src/SharpEmu.GpuSplit/RemoteGpuBackend.cs | 5 +++ .../Agc/AgcExports.Submissions.cs | 25 ++++++++++--- src/SharpEmu.Libs/Gpu/IGuestGpuBackend.cs | 7 ++++ .../Agc/AgcSubmissionPreparationTests.cs | 37 ++++++++++++++++++- 4 files changed, 66 insertions(+), 8 deletions(-) diff --git a/src/SharpEmu.GpuSplit/RemoteGpuBackend.cs b/src/SharpEmu.GpuSplit/RemoteGpuBackend.cs index cfdbfd1ee..19be9d0d4 100644 --- a/src/SharpEmu.GpuSplit/RemoteGpuBackend.cs +++ b/src/SharpEmu.GpuSplit/RemoteGpuBackend.cs @@ -116,6 +116,11 @@ public bool TrySubmitGuestImage(int videoOutHandle, int displayBufferIndex, ulon return _session.Writer.Write(GpuRemoteMessage.FlipRequest, in message); } + // The GPU process reads the command buffer and its register tables from the shared guest + // memory; nothing captured at submit crosses the channel (SubmitCommandStream sends the + // address and the length only). + public bool ConsumesSubmittedCommandBytes => false; + public void SubmitCommandStream(ICpuMemory memory, uint queue, ulong address, uint dwordCount, ulong submissionId, object? geometrySnapshots) { var message = new SubmitCommandStreamMessage diff --git a/src/SharpEmu.Libs/Agc/AgcExports.Submissions.cs b/src/SharpEmu.Libs/Agc/AgcExports.Submissions.cs index 620ec5cd9..6fc5dccbd 100644 --- a/src/SharpEmu.Libs/Agc/AgcExports.Submissions.cs +++ b/src/SharpEmu.Libs/Agc/AgcExports.Submissions.cs @@ -80,15 +80,28 @@ public static int DriverSubmitDcb(CpuContext ctx) if (dwordCount > 0xF_FFFF) return SetReturn(ctx, OrbisGen2Result.ORBIS_GEN2_ERROR_INVALID_ARGUMENT); var commandLength = (int)dwordCount * sizeof(uint); - var commandBytes = System.Buffers.ArrayPool.Shared.Rent(commandLength); - if (commandLength != 0 && !ctx.Memory.TryRead(commandAddress, commandBytes.AsSpan(0, commandLength))) + SubmittedCommandBuffer? submitted = null; + if (GuestGpu.Current.ConsumesSubmittedCommandBytes) { - System.Buffers.ArrayPool.Shared.Return(commandBytes); + var commandBytes = System.Buffers.ArrayPool.Shared.Rent(commandLength); + if (commandLength != 0 && !ctx.Memory.TryRead(commandAddress, commandBytes.AsSpan(0, commandLength))) + { + System.Buffers.ArrayPool.Shared.Return(commandBytes); + return SetReturn(ctx, OrbisGen2Result.ORBIS_GEN2_ERROR_MEMORY_FAULT); + } + + var registerTables = CaptureSubmittedTables(ctx, commandAddress, commandBytes.AsSpan(0, commandLength)); + var snapshots = CaptureSubmittedGeometry(ctx, gpuState, commandAddress, dwordCount); + submitted = new SubmittedCommandBuffer(commandBytes, snapshots, registerTables) { Length = commandLength, Pooled = true }; + } + else if (commandLength != 0 && !ctx.Memory.CanRead(commandAddress, (ulong)commandLength)) + { + // This backend's host reads the stream from guest memory itself and is handed no + // copy (the copy was rented, filled, scanned for tables and then dropped unread on + // every submit): the submit only answers for the range being mapped, as the copy did. return SetReturn(ctx, OrbisGen2Result.ORBIS_GEN2_ERROR_MEMORY_FAULT); } - var registerTables = CaptureSubmittedTables(ctx, commandAddress, commandBytes.AsSpan(0, commandLength)); - var snapshots = CaptureSubmittedGeometry(ctx, gpuState, commandAddress, dwordCount); SubmissionFlowProfile.RecordGuest(SubmissionFlowProfile.EventKind.GeometryCaptureFinished, 0, gpuState.SubmissionSequence + 1, commandAddress, dwordCount); if (profileEnabled) @@ -102,7 +115,7 @@ public static int DriverSubmitDcb(CpuContext ctx) commandAddress, dwordCount, ++gpuState.SubmissionSequence, - new SubmittedCommandBuffer(commandBytes, snapshots, registerTables) { Length = commandLength, Pooled = true }, out preparation)) + submitted, out preparation)) { return SetReturn(ctx, OrbisGen2Result.ORBIS_GEN2_ERROR_CANCELED); } diff --git a/src/SharpEmu.Libs/Gpu/IGuestGpuBackend.cs b/src/SharpEmu.Libs/Gpu/IGuestGpuBackend.cs index 6580407bc..07b3d2ddc 100644 --- a/src/SharpEmu.Libs/Gpu/IGuestGpuBackend.cs +++ b/src/SharpEmu.Libs/Gpu/IGuestGpuBackend.cs @@ -43,6 +43,13 @@ public interface IGuestGpuBackend /// submit skips the walk of the command buffer that builds them. bool ConsumesSubmittedGeometrySnapshots => false; + /// True when this backend's command-stream host reads the submit-time copy of a + /// command buffer and of its indirect register tables (the SubmittedCommandBuffer a + /// single-buffer AGC submit hands as geometrySnapshots). A backend whose host reads + /// the stream from guest memory itself says no: the guest submit then makes no copy and only + /// checks that the buffer is mapped. + bool ConsumesSubmittedCommandBytes => true; + // 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/tests/SharpEmu.Libs.Tests/Agc/AgcSubmissionPreparationTests.cs b/tests/SharpEmu.Libs.Tests/Agc/AgcSubmissionPreparationTests.cs index 45ead6287..f4deb0380 100644 --- a/tests/SharpEmu.Libs.Tests/Agc/AgcSubmissionPreparationTests.cs +++ b/tests/SharpEmu.Libs.Tests/Agc/AgcSubmissionPreparationTests.cs @@ -109,6 +109,35 @@ public void SubmitWalksTheCommandBufferOnlyForAHostThatReadsGeometrySnapshots(bo Assert.Equal(shadowedRegisters, AgcExports.GetGeometryCaptureRegistersForTests(memory).Count); } + // The split backend's host reads the stream from guest memory: a copy made at submit was + // dropped unread on every submit. + [Theory] + [InlineData(true)] + [InlineData(false)] + public void SubmitCopiesTheCommandBufferOnlyForAHostThatReadsTheCopy(bool consumesCopy) + { + var memory = Memory(); + SubmissionBackend backend = consumesCopy ? new SubmissionBackend() : new StreamReadingBackend(); + using var scope = new BackendScope(backend); + Assert.Equal(0, Submit(memory, "dcb")); + Assert.Equal(1, backend.Admissions); + Assert.Equal(consumesCopy, backend.LastSnapshots is SubmittedCommandBuffer); + if (!consumesCopy) Assert.Null(backend.LastSnapshots); + } + + [Theory] + [InlineData(true)] + [InlineData(false)] + public void SubmitOfAnUnmappedCommandBufferIsAMemoryFaultWhetherOrNotTheHostReadsTheCopy(bool consumesCopy) + { + var memory = Memory(); + Write(memory, Packet, Base + 0x100000); // Outside the 0x1000 bytes that are mapped. + SubmissionBackend backend = consumesCopy ? new SubmissionBackend() : new StreamReadingBackend(); + using var scope = new BackendScope(backend); + Assert.Equal(unchecked((int)OrbisGen2Result.ORBIS_GEN2_ERROR_MEMORY_FAULT), Submit(memory, "dcb")); + Assert.Equal(0, backend.Admissions); + } + private static FakeCpuMemory Memory() { var memory = new FakeCpuMemory(Base, 0x1000); @@ -149,11 +178,11 @@ private sealed class BackendScope : IDisposable } private class SubmissionBackend : IGuestGpuBackend { - public int Admissions; public uint LastQueue; + public int Admissions; public uint LastQueue; public object? LastSnapshots; public Action? OnAdmission; public string BackendName => "managed preparation control"; public void SubmitCommandStream(ICpuMemory memory, uint queue, ulong address, uint dwordCount, ulong submissionId, object? geometrySnapshots) - { OnAdmission?.Invoke(); LastQueue = queue; Admissions++; } + { OnAdmission?.Invoke(); LastQueue = queue; LastSnapshots = geometrySnapshots; Admissions++; } public void EnsureStarted(uint width, uint height) => throw new NotSupportedException(); public bool TryCompileProgram(ShaderCompileRequest request, out IGuestCompiledShader? shader, out string error) => throw new NotSupportedException(); public IGuestCompiledShader GetDepthOnlyFragmentShader() => throw new NotSupportedException(); @@ -172,6 +201,10 @@ private sealed class SnapshotConsumingBackend : SubmissionBackend, IGuestGpuBack { public bool ConsumesSubmittedGeometrySnapshots => true; } + private sealed class StreamReadingBackend : SubmissionBackend, IGuestGpuBackend + { + public bool ConsumesSubmittedCommandBytes => false; + } private sealed class PreparingBackend : SubmissionBackend, IGuestSubmissionPreparationBackend { public int Waits; public Func? OnWait; From 1c0e4c97639bd6ee08784ea752b82617c6263f88 Mon Sep 17 00:00:00 2001 From: kuba Date: Sun, 15 Nov 2026 23:14:36 +0000 Subject: [PATCH 102/178] [Metal] Consume a copy or fill kernel whose destination already holds its result by default SHARPEMU_METAL_V2_HOST_KERNEL_COPY now defaults to identical (0 runs every kernel as the dispatch it is, verify checks each one that would be consumed). Demon's Souls issues ~200 table copies per frame with one kernel; ~41% of the compared ones write what the destination already holds. A verify run of the game (r56-gcd) checked 169k such kernels on both sides with no mismatch. A kernel is only compared when no recorded GPU write, overlay or image covers either side. --- .../SharpEmu.Gpu.Metal/V2/MetalV2Diagnostics.cs | 17 ++++++++++------- ...alClearFoldingTests.HostKernelCopyElision.cs | 3 ++- 2 files changed, 12 insertions(+), 8 deletions(-) diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalV2Diagnostics.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalV2Diagnostics.cs index 7976506b0..bd4c173f3 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalV2Diagnostics.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalV2Diagnostics.cs @@ -220,11 +220,14 @@ private static HashSet ParseHashes(string? text) // SHARPEMU_METAL_V2_HOST_KERNEL_COPY: what the host does with a recognised copy or fill // kernel the image paths refuse whose destination already holds its result - // (MetalRenderHost.KernelFills). 0 (the default) runs it as the dispatch it is; identical - // consumes it and writes nothing; verify runs it and, once it completes, checks that the - // destination still holds what was there, reporting each kernel that would have been - // consumed wrongly. write (host writes of the changed pages) needs a ledger of the GPU's - // reads that does not exist yet, so it runs as 0. + // (MetalRenderHost.KernelFills). identical (the default) consumes it and writes nothing: + // a kernel is only compared when no recorded GPU write, overlay or image covers either + // side, so memory is what the dispatch would have read and written; 0 runs it as the + // dispatch it is; verify runs it and, once it completes, checks that the destination still + // holds what was there, reporting each kernel that would have been consumed wrongly. write + // (host writes of the changed pages) needs a ledger of the GPU's reads that does not exist + // yet, so it runs as 0. Demon's Souls: ~41% of its ~200 table copies per frame are + // identical; a verify run checked 169k of them with no mismatch. public static readonly MetalHostKernelCopyMode HostKernelCopy = ParseHostKernelCopy(Environment.GetEnvironmentVariable("SHARPEMU_METAL_V2_HOST_KERNEL_COPY")); @@ -240,9 +243,9 @@ internal static MetalHostKernelCopyMode ParseHostKernelCopy(string? text) { switch (text) { - case null or "" or "0": + case "0": return MetalHostKernelCopyMode.Off; - case "identical": + case null or "" or "identical": return MetalHostKernelCopyMode.Identical; case "verify": return MetalHostKernelCopyMode.Verify; diff --git a/tests/SharpEmu.Gpu.Metal.Tests/MetalClearFoldingTests.HostKernelCopyElision.cs b/tests/SharpEmu.Gpu.Metal.Tests/MetalClearFoldingTests.HostKernelCopyElision.cs index 20641e732..4ab177ec3 100644 --- a/tests/SharpEmu.Gpu.Metal.Tests/MetalClearFoldingTests.HostKernelCopyElision.cs +++ b/tests/SharpEmu.Gpu.Metal.Tests/MetalClearFoldingTests.HostKernelCopyElision.cs @@ -187,7 +187,8 @@ private static void RecordVerifiedCopy(MetalRenderHost host) } [Theory] - [InlineData(null, "Off")] + [InlineData(null, "Identical")] + [InlineData("", "Identical")] [InlineData("0", "Off")] [InlineData("identical", "Identical")] [InlineData("verify", "Verify")] From 76b6b1a724447ba5bad58ad9cd336d872473d6a1 Mon Sep 17 00:00:00 2001 From: kuba Date: Sun, 15 Nov 2026 23:36:03 +0000 Subject: [PATCH 103/178] [GPU] Hand out a memo rebuild without keeping it while the draw's words keep moving A rebuilt words miss replaced its entry's programs, so the long-lived memo pointed at a new program graph for every draw whose descriptor words move each frame (ring-allocated constant buffers: ~1/3 of Demon's Souls draws), and every gen0 collection of the GPU host promoted all of it. The entry now keeps a rebuild only when it evaluated the same words as the entry's last rebuild; verify checks the programs a take hands out, kept or not. SHARPEMU_RESOLVE_MEMO_HOLD_CHURN=0 keeps every rebuild as before; rebuilt_not_kept counts the rest. ResolveMemoRetentionBench drives the resolve path with a frame of draws whose words move: 1352 B allocated and 1352 B retained per draw before, 0 B retained after. --- .../Gpu/Pipelines/GraphicsResolveMemo.cs | 19 ++ .../Gpu/Pipelines/ShaderPipelineCache.cs | 94 +++++-- .../KeptStageInputsTests.ResolveMemo.cs | 42 ++++ .../ResolveMemoRetentionBenchTests.cs | 229 ++++++++++++++++++ 4 files changed, 367 insertions(+), 17 deletions(-) create mode 100644 tests/SharpEmu.Libs.Tests/Gpu/Pipelines/ResolveMemoRetentionBenchTests.cs diff --git a/src/SharpEmu.Libs/Gpu/Pipelines/GraphicsResolveMemo.cs b/src/SharpEmu.Libs/Gpu/Pipelines/GraphicsResolveMemo.cs index 6313f78ad..b66688772 100644 --- a/src/SharpEmu.Libs/Gpu/Pipelines/GraphicsResolveMemo.cs +++ b/src/SharpEmu.Libs/Gpu/Pipelines/GraphicsResolveMemo.cs @@ -97,6 +97,15 @@ internal sealed class GraphicsResolveMemo // snapshot its revalidation evaluated (ShaderPipelineCache.TryTakeResolveMemo). internal static readonly bool DefaultRebuild = Environment.GetEnvironmentVariable("SHARPEMU_RESOLVE_MEMO_REBUILD") != "0"; + // SHARPEMU_RESOLVE_MEMO_HOLD_CHURN=0: every rebuilt words miss replaces its entry's programs, as before. On (default), a + // rebuild is kept only when it evaluated the same words as the entry's last rebuild (Entry.RebuildSignature): a draw + // whose descriptor words move on every take (Demon's Souls: ring-allocated constant buffers, ~1/3 of its draws) is + // handed its rebuilt programs without the long-lived entry pointing at them, so they die young instead of being + // promoted by every gen0 collection (~56 MB each in game) and compacted. Its next take revalidates the programs the + // entry kept and rebuilds again, the work a kept rebuild would have cost it (its words moved again); words that + // settle are kept on their second rebuild and hit from then on. Only what is kept changes, never a result. + internal static readonly bool DefaultHoldChurn = Environment.GetEnvironmentVariable("SHARPEMU_RESOLVE_MEMO_HOLD_CHURN") != "0"; + internal static ResolveMemoMode ParseMode(string? value) => value?.Trim().ToLowerInvariant() switch { "0" or "off" => ResolveMemoMode.Off, @@ -128,6 +137,8 @@ internal sealed class Entry public long TablesGeneration; // GraphicsProgramsComparer.Fingerprint at insertion (verify: nothing wrote the shared result since). public ulong Fingerprint; + // The signature of the words this entry's last rebuild evaluated (HoldChurn), 0 before any. + public ulong RebuildSignature; } private const int MaxKeyBytes = 4096; @@ -160,6 +171,10 @@ public GraphicsResolveMemo(ResolveMemoMode mode, int capacity) // Whether a words miss is rebuilt from its revalidation (DefaultRebuild; tests set it). public bool Rebuild { get; set; } = DefaultRebuild; + // Whether a rebuild whose words differ from the entry's last rebuild is handed out without being kept (DefaultHoldChurn; + // tests set it). + public bool HoldChurn { get; set; } = DefaultHoldChurn; + public int Count => _count; public ulong Hash { get; private set; } @@ -388,6 +403,7 @@ public Entry Store() private static readonly ThreadCounter _hits = new(); private static readonly ThreadCounter _rebuilt = new(); + private static readonly ThreadCounter _rebuildHeld = new(); private static readonly ThreadCounter[] _rebuildRefused = NewCounters((int)ResolveMemoRebuildRefusal.Count); private static readonly ThreadCounter _evictions = new(); private static readonly ThreadCounter _entries = new(); @@ -405,6 +421,8 @@ public Entry Store() public static void NoteRebuilt() => _rebuilt.Increment(); + public static void NoteRebuildHeld() => _rebuildHeld.Increment(); + public static void NoteRebuildRefused(ResolveMemoRebuildRefusal cause) => _rebuildRefused[(int)cause].Increment(); public static void NoteShadowHit() => _shadowWouldHit.Increment(); @@ -432,6 +450,7 @@ public static string TakeReport() => FormattableString.Invariant( $"resolve_memo=(mode={DefaultMode.ToString().ToLowerInvariant()},hits={_hits.Take()},would_hit={_shadowWouldHit.Take()},") + "miss_by=(" + Take(_misses, "new", "epoch", "header", "identity", "tables", "semantics", "words", "generation") + ")," + FormattableString.Invariant($"words_rebuilt={_rebuilt.Take()},rebuild={(DefaultRebuild ? 1 : 0)},") + + FormattableString.Invariant($"rebuilt_not_kept={_rebuildHeld.Take()},hold_churn={(DefaultHoldChurn ? 1 : 0)},") + "rebuild_refused_by=(" + Take(_rebuildRefused, "origin", "refused", "evaluate", "failed", "specialization", "generation") + ")," + "key_miss=(" + Take(_keyMisses, "new", "user_data_only", "regs_only") + ")," + "uncacheable_by=(" + Take(_uncacheable, "frontend", "mesh", "tess", "calls", "unavailable", "tables", "trace", "origin", "key", "changed") + ")," + diff --git a/src/SharpEmu.Libs/Gpu/Pipelines/ShaderPipelineCache.cs b/src/SharpEmu.Libs/Gpu/Pipelines/ShaderPipelineCache.cs index d6c1d1e2f..2408db980 100644 --- a/src/SharpEmu.Libs/Gpu/Pipelines/ShaderPipelineCache.cs +++ b/src/SharpEmu.Libs/Gpu/Pipelines/ShaderPipelineCache.cs @@ -1,6 +1,7 @@ // Copyright (C) 2026 SharpEmu Emulator Project // SPDX-License-Identifier: GPL-2.0-or-later +using System.IO.Hashing; using System.Runtime.InteropServices; using SharpEmu.HLE; using SharpEmu.HLE.Diagnostics; @@ -381,6 +382,19 @@ internal bool ResolveMemoRebuild } } + // For tests: whether this cache's memo keeps only rebuilds whose words repeat (GraphicsResolveMemo.HoldChurn). + internal bool ResolveMemoHoldChurn + { + get => _resolveMemo?.HoldChurn ?? false; + set + { + lock (_resolveGate) + { + if (_resolveMemo is { } memo) memo.HoldChurn = value; + } + } + } + // Shadow mode: counts whether the memo would have the draw's key; true when it has not and the key is to be stored // once the draw resolved. private bool ShadowResolveMemo(RegisterBanks banks, ReadOnlySpan targetExportMapping, in KeptGraphicsFlags flags) @@ -437,7 +451,7 @@ private GraphicsPrograms ResolveThroughMemo(GraphicsResolveMemo memo, RegisterBa fillSerial = memo.FillSerial; if (memo.Find() is { } entry) { - if (TryTakeResolveMemo(memo, entry, flags.PixelActive, out var rebuilt) is not { } miss) + if (TryTakeResolveMemo(memo, entry, flags.PixelActive, out var taken, out var fingerprint, out var rebuilt) is not { } miss) { if (rebuilt) { @@ -451,8 +465,8 @@ private GraphicsPrograms ResolveThroughMemo(GraphicsResolveMemo memo, RegisterBa } return memo.Mode == ResolveMemoMode.Verify - ? VerifyResolveMemo(memo, entry, banks, targetExportMapping, flags) - : entry.Programs!; + ? VerifyResolveMemo(memo, entry, taken!, fingerprint, banks, targetExportMapping, flags) + : taken!; } GraphicsResolveMemo.NoteMiss(miss); @@ -492,10 +506,14 @@ private GraphicsPrograms ResolveFull(RegisterBanks banks, ReadOnlySpan + words is null ? hash * 31 + 1 : XxHash3.HashToUInt64(MemoryMarshal.AsBytes(words.AsSpan()), (long)(hash + (ulong)words.Length)); + // False when the stage's words no longer evaluate to its snapshot and it was not rebuilt (refusals counted). private bool RevalidateMemoStage(ref ShaderStageResources stage, bool rebuild, ref bool rebuilt) { @@ -760,16 +820,16 @@ private bool TryReadMemoTables(ShaderSource source, VertexInputInfo resolved, ou // (raced). Only a hit that still revalidates while a second full resolution still differs from it is a mismatch, and // a result written since it was kept always is; either stops emulation (on a speculative thread the work is // abandoned and counted, GpuFatal.VerifyFailed). - private GraphicsPrograms VerifyResolveMemo(GraphicsResolveMemo memo, GraphicsResolveMemo.Entry entry, RegisterBanks banks, - ReadOnlySpan targetExportMapping, in KeptGraphicsFlags flags) + // memoPrograms: what the take hands out (the entry's, or a rebuild kept or not), fingerprint: theirs when taken. + private GraphicsPrograms VerifyResolveMemo(GraphicsResolveMemo memo, GraphicsResolveMemo.Entry entry, GraphicsPrograms memoPrograms, + ulong fingerprint, RegisterBanks banks, ReadOnlySpan targetExportMapping, in KeptGraphicsFlags flags) { - var memoPrograms = entry.Programs!; var full = ResolveFull(banks, targetExportMapping, flags); GraphicsResolveMemo.NoteVerified(); var difference = GraphicsProgramsComparer.Difference(memoPrograms, full); if (difference is null) { - if (GraphicsProgramsComparer.Fingerprint(memoPrograms) == entry.Fingerprint) + if (GraphicsProgramsComparer.Fingerprint(memoPrograms) == fingerprint) { return memoPrograms; } @@ -789,7 +849,7 @@ private GraphicsPrograms VerifyResolveMemo(GraphicsResolveMemo memo, GraphicsRes return full; } - if (TryTakeResolveMemo(memo, entry, flags.PixelActive, out _, allowRebuild: false) is { } miss) + if (TryTakeResolveMemo(memo, entry, flags.PixelActive, out _, out _, out _, allowRebuild: false, held: memoPrograms) is { } miss) { GraphicsResolveMemo.NoteVerifyRaced(ResolveMemoVerifyRace.Changed); ReportResolveMemoRace(entry, difference, $"recheck=miss:{miss.ToString().ToLowerInvariant()}", stages); diff --git a/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/KeptStageInputsTests.ResolveMemo.cs b/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/KeptStageInputsTests.ResolveMemo.cs index dce7bcec6..8e8443577 100644 --- a/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/KeptStageInputsTests.ResolveMemo.cs +++ b/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/KeptStageInputsTests.ResolveMemo.cs @@ -86,6 +86,7 @@ public void ResolveMemo_TakesAnotherKeyForOtherUserDataAndComesBackToTheFirst() public void ResolveMemo_MissesWhenAStagesDescriptorWordChanges() { var cache = MemoCache(); + cache.ResolveMemoHoldChurn = false; UseLoadingPixelProgram(Descriptor); var first = Programs(cache, pixelActive: true); Assert.Same(first, Programs(cache, pixelActive: true)); @@ -104,6 +105,7 @@ public void ResolveMemo_RebuildsAWordsMissFromItsRevalidationAsTheFullResolution { var cache = MemoCache(); Assert.True(cache.ResolveMemoRebuild); + cache.ResolveMemoHoldChurn = false; UseLoadingPixelProgram(Descriptor); var first = Programs(cache, pixelActive: true); var firstBuffers = first.PixelInput.Stage.Resources.Buffers.Select(words => words.ToArray()).ToArray(); @@ -130,6 +132,46 @@ public void ResolveMemo_RebuildsAWordsMissFromItsRevalidationAsTheFullResolution Assert.Contains("hits=1,", Report()); } + // With the churn hold (default), a rebuild is handed out without the entry keeping it until a rebuild evaluates the + // same words as the one before it: a draw whose words move on every take leaves the memo pointing at what it kept, + // and words that settle are kept on their second rebuild and hit after that. Verify finds every take exact. + [Fact] + public void ResolveMemo_KeepsARebuildOnlyOnceItsWordsRepeat() + { + var cache = MemoCache(); + Assert.True(cache.ResolveMemoHoldChurn); + UseLoadingPixelProgram(Descriptor); + var first = Programs(cache, pixelActive: true); + Report(); + _guest.WriteWords(Descriptor, PipelineTestGuest.BufferDescriptor(StreamBase + 0x100, 16, 4, Format32x4Float)); + var moved = Programs(cache, pixelActive: true); + _guest.WriteWords(Descriptor, PipelineTestGuest.BufferDescriptor(StreamBase + 0x200, 16, 4, Format32x4Float)); + var movedAgain = Programs(cache, pixelActive: true); + var report = Report(); + Assert.Contains("words_rebuilt=2,", report); + Assert.Contains("rebuilt_not_kept=2,", report); + Assert.Contains("verify_checked=2,", report); + Assert.Contains("verify_failed=0)", report); + Assert.Contains(moved.PixelInput.Stage.Resources.Buffers, words => words[0] == unchecked((uint)(StreamBase + 0x100))); + Assert.Contains(movedAgain.PixelInput.Stage.Resources.Buffers, words => words[0] == unchecked((uint)(StreamBase + 0x200))); + + // The same words again: rebuilt from the kept programs once more, and this time kept. + var settled = Programs(cache, pixelActive: true); + report = Report(); + Assert.NotSame(movedAgain, settled); + Assert.Contains("words_rebuilt=1,", report); + Assert.Contains("rebuilt_not_kept=0,", report); + Assert.Same(settled, Programs(cache, pixelActive: true)); + Assert.Contains("hits=1,", Report()); + + // Back to the first words: the kept rebuild no longer holds, and the first programs are as they were. + _guest.WriteWords(Descriptor, PipelineTestGuest.BufferDescriptor(StreamBase, 16, 4, Format32x4Float)); + var back = Programs(cache, pixelActive: true); + Assert.NotSame(settled, back); + Assert.Equal(first.PixelInput.Stage.Resources.Buffers, back.PixelInput.Stage.Resources.Buffers); + Assert.Contains("verify_failed=0)", Report()); + } + // Words that specialize the program otherwise (another stride) may pick another permutation: not rebuilt, resolved in // full (and counted); with rebuild off every words miss resolves in full. [Theory] diff --git a/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/ResolveMemoRetentionBenchTests.cs b/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/ResolveMemoRetentionBenchTests.cs new file mode 100644 index 000000000..905da6fa0 --- /dev/null +++ b/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/ResolveMemoRetentionBenchTests.cs @@ -0,0 +1,229 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using System.Buffers.Binary; +using System.Diagnostics; +using SharpEmu.Libs.Gpu.GpuCommands.Registers; +using SharpEmu.Libs.Gpu.Pipelines; +using SharpEmu.Libs.Gpu.Rendering; +using SharpEmu.Libs.Tests.Gpu.Scheduling; +using Xunit; +using Xunit.Abstractions; + +namespace SharpEmu.Libs.Tests.Gpu.Pipelines; + +// What the graphics resolve path allocates per draw and what the resolve memo keeps of it, for a frame of draws repeated +// the way Demon's Souls repeats them: every draw has its own descriptor block (its own key), and each frame either +// nothing moves (hits), two of a draw's eight V#s get another base (ring-allocated constant buffers: words misses that +// the memo rebuilds), or the draw's pointer to its block moves (a new key every frame). Retained is what survives a gen0 +// collection made after the frame: bytes the long-lived memo now points at. The numbers go to the test output; run alone +// (the collection below is not parallelized) with --filter "FullyQualifiedName~ResolveMemoRetentionBench" and +// --logger "console;verbosity=detailed". +[Collection(SchedulingStateCollection.Name)] +public sealed class ResolveMemoRetentionBenchTests : IDisposable +{ + private const ulong VertexAddress = PipelineTestGuest.MemoryBase + 0x1000; + private const ulong VertexHeader = PipelineTestGuest.MemoryBase + 0x8000; + private const ulong UserDataBlock = PipelineTestGuest.MemoryBase + 0x9000; + private const ulong DirectOffsets = PipelineTestGuest.MemoryBase + 0x9100; + private const ulong Semantics = PipelineTestGuest.MemoryBase + 0x9200; + private const ulong AttributeTable = PipelineTestGuest.MemoryBase + 0xA000; + private const ulong BufferTable = PipelineTestGuest.MemoryBase + 0xA100; + private const ulong PixelAddress = PipelineTestGuest.MemoryBase + 0x3000; + private const ulong PixelHeader = PipelineTestGuest.MemoryBase + 0x8200; + private const ulong PixelUserDataBlock = PipelineTestGuest.MemoryBase + 0xC000; + private const ulong StreamBase = PipelineTestGuest.MemoryBase + 0x20000; + private const ulong Blocks = PipelineTestGuest.MemoryBase + 0x30000; + private const uint DirectResourceCount = 11; + private const uint VertexBufferTableType = 8; + private const uint VertexAttributeTableType = 10; + private const uint AttributeRegister = 0; + private const uint BufferRegister = 2; + private const uint Format32x4Float = 77; + private const int Buffers = 8; + private const int BlockBytes = Buffers * 16; + private const int Draws = 256; + private const int WarmFrames = 3; + private const int MeasuredFrames = 8; + + private readonly FatalScope _fatal = new(); + private readonly PipelineTestGuest _guest = new(); + private readonly RegisterBanks _banks = new(static message => new InvalidOperationException(message)); + private readonly ITestOutputHelper _output; + + public ResolveMemoRetentionBenchTests(ITestOutputHelper output) + { + _output = output; + WriteQword(UserDataBlock, DirectOffsets); + WriteHalf(UserDataBlock + 0x2C, (ushort)DirectResourceCount); + for (uint type = 0; type < DirectResourceCount; type++) + { + WriteHalf(DirectOffsets + type * 2, 0xFFFF); + } + + WriteHalf(DirectOffsets + VertexBufferTableType * 2, (ushort)BufferRegister); + WriteHalf(DirectOffsets + VertexAttributeTableType * 2, (ushort)AttributeRegister); + _guest.WriteWords(Semantics, 0 | (4u << 16), 1 | (4u << 8) | (2u << 16)); + _guest.RegisterProgram(VertexAddress, VertexHeader, PipelineTestGuest.EndProgram, UserDataBlock, Semantics, 2); + _guest.WriteWords(AttributeTable, 0, 16u << 14); + _guest.WriteWords(BufferTable, PipelineTestGuest.BufferDescriptor(StreamBase, 24, 3, Format32x4Float)); + _guest.RegisterProgram(PixelAddress, PixelHeader, LoadingProgram(), PixelUserDataBlock); + _banks.Shader.Vertex.ExportAddress = VertexAddress; + _banks.Shader.Pixel.Address = PixelAddress; + var registers = _banks.Shader.Vertex.GeometryUserScalars; + registers.Set(AttributeRegister, unchecked((uint)AttributeTable), UserScalarKind.Unknown); + registers.Set(AttributeRegister + 1, (uint)(AttributeTable >> 32), UserScalarKind.Unknown); + registers.Set(BufferRegister, unchecked((uint)BufferTable), UserScalarKind.Unknown); + registers.Set(BufferRegister + 1, (uint)(BufferTable >> 32), UserScalarKind.Unknown); + _banks.MarkWritten(1u << (int)RegisterStamp.VertexUserData); + } + + public void Dispose() => _fatal.Dispose(); + + // s_load_dwordx4 s[4+4i:7+4i], s[0:1], 16*i for each V#, then buffer_load_format_x v[1+i], v0, s[4+4i:7+4i] through + // each, then s_endpgm. + private static uint[] LoadingProgram() + { + var words = new List(); + for (var index = 0; index < Buffers; index++) + { + words.Add(0xF4080000u | ((uint)(4 + 4 * index) << 6)); + words.Add(0xFA000000u | (uint)(16 * index)); + } + + for (var index = 0; index < Buffers; index++) + { + words.Add(0xE0000000u); + words.Add(0x80000000u | ((uint)(1 + index) << 16) | ((uint)(1 + index) << 8)); + } + + words.Add(0xBF810000u); + return [.. words]; + } + + public enum Churn + { + // Nothing moves: every draw hits. + None, + // Two V#s of every draw take another base each frame: words misses. + Words, + // Every draw's pointer moves to a block of its own each frame: a new key every frame. + Keys, + } + + private void WriteBlock(ulong block, int draw, int frame, bool moveWords) + { + for (var index = 0; index < Buffers; index++) + { + var moved = moveWords && index < 2 ? (ulong)((frame * Draws + draw) % 4096) * 0x40 : 0; + _guest.WriteWords(block + (ulong)(16 * index), + PipelineTestGuest.BufferDescriptor(StreamBase + (ulong)(index * 0x40) + moved, 16, 4, Format32x4Float)); + } + } + + private ulong BlockOf(Churn churn, int draw, int frame) => + Blocks + (ulong)((churn == Churn.Keys ? frame * Draws + draw : draw) * BlockBytes); + + private void PointPixelAt(ulong block) + { + _banks.Shader.Pixel.UserScalars.Set(0, (uint)block, UserScalarKind.Unknown); + _banks.Shader.Pixel.UserScalars.Set(1, (uint)(block >> 32), UserScalarKind.Unknown); + _banks.MarkWritten(1u << (int)RegisterStamp.PixelUserData); + } + + private (double AllocPerDraw, double RetainedPerFrame, double NsPerDraw, string Report) Run(Churn churn, ResolveMemoMode mode, + Action? configure = null) + { + var cache = new ShaderPipelineCache(_guest.Context, _guest.Host, _guest.Compiler, _guest.Registry) { ResolveMemoMode = mode }; + configure?.Invoke(cache); + long allocated = 0, retained = 0, ticks = 0; + GraphicsResolveMemo.TakeReport(); + for (var frame = 0; frame < WarmFrames + MeasuredFrames; frame++) + { + var measured = frame >= WarmFrames; + if (measured && frame == WarmFrames) + { + GraphicsResolveMemo.TakeReport(); + } + + for (var draw = 0; draw < Draws; draw++) + { + if (frame == 0 || churn != Churn.None) + { + WriteBlock(BlockOf(churn, draw, frame), draw, frame, churn == Churn.Words); + } + } + + if (measured) + { + // Everything so far into gen2: the gen0 collection after the frame promotes only what the frame left + // reachable. + GC.Collect(1, GCCollectionMode.Forced, blocking: true); + } + + var before = GC.GetAllocatedBytesForCurrentThread(); + var started = Stopwatch.GetTimestamp(); + for (var draw = 0; draw < Draws; draw++) + { + PointPixelAt(BlockOf(churn, draw, frame)); + var programs = cache.GetGraphicsPrograms(_banks, [], pixelActive: true, depthBound: false); + Assert.True(programs.Available); + } + + var elapsed = Stopwatch.GetTimestamp() - started; + var after = GC.GetAllocatedBytesForCurrentThread(); + if (measured) + { + ticks += elapsed; + allocated += after - before; + GC.Collect(0, GCCollectionMode.Forced, blocking: true); + var info = GC.GetGCMemoryInfo(GCKind.Ephemeral); + retained += info.Generation == 0 ? info.PromotedBytes : 0; + } + } + + var report = GraphicsResolveMemo.TakeReport(); + Assert.Empty(_fatal.Messages); + GC.KeepAlive(cache); + return ((double)allocated / (Draws * MeasuredFrames), (double)retained / MeasuredFrames, + ticks * 1e9 / Stopwatch.Frequency / (Draws * MeasuredFrames), report); + } + + // tuned false: the memo as it was before the retention changes (every rebuild kept). + [Theory] + [InlineData(Churn.None, true)] + [InlineData(Churn.Words, true)] + [InlineData(Churn.Keys, true)] + [InlineData(Churn.Words, false)] + [InlineData(Churn.Keys, false)] + public void ResolveMemoRetentionBench(Churn churn, bool tuned) + { + var (alloc, retained, ns, report) = Run(churn, ResolveMemoMode.On, cache => cache.ResolveMemoHoldChurn = tuned); + _output.WriteLine(FormattableString.Invariant( + $"churn={churn} tuned={tuned} draws/frame={Draws} alloc_per_draw={alloc:F0} B retained_per_frame={retained / 1024:F1} KiB ({retained / Draws:F0} B/draw) resolve={ns:F0} ns/draw")); + _output.WriteLine(report); + } + + // The same frames under verify: every hit and rebuild is resolved again in full and compared. + [Fact] + public void ResolveMemoChurnVerifiesUnderVerifyMode() + { + var (_, _, _, report) = Run(Churn.Words, ResolveMemoMode.Verify); + Assert.Contains("verify_failed=0)", report); + Assert.DoesNotContain("verify_checked=0,", report); + } + + private void WriteQword(ulong address, ulong value) + { + var bytes = new byte[sizeof(ulong)]; + BinaryPrimitives.WriteUInt64LittleEndian(bytes, value); + _guest.Write(address, bytes); + } + + private void WriteHalf(ulong address, ushort value) + { + var bytes = new byte[sizeof(ushort)]; + BinaryPrimitives.WriteUInt16LittleEndian(bytes, value); + _guest.Write(address, bytes); + } +} From 87c1b6e56e5411614bae7126a1118334d34f49fc Mon Sep 17 00:00:00 2001 From: kuba Date: Sun, 15 Nov 2026 23:50:14 +0000 Subject: [PATCH 104/178] [Shader] Let a rebuilt fast snapshot share the buffer words its predecessor already holds A memo rebuild materialized every buffer's words into a new array although most of a draw's V#s keep their words when one ring-allocated constant buffer moves. With a specialization memo hit, a buffer whose words equal the replaced snapshot's takes that array (published snapshots are never written). Bench (8 V#s, 2 moving): 1352 -> 1112 B allocated per rebuilt draw. --- .../Resources/ResourceMaterializer.cs | 18 +++++++++++++++--- 1 file changed, 15 insertions(+), 3 deletions(-) diff --git a/src/SharpEmu.ShaderCompiler/Resources/ResourceMaterializer.cs b/src/SharpEmu.ShaderCompiler/Resources/ResourceMaterializer.cs index 0a6a04769..7cd2e916e 100644 --- a/src/SharpEmu.ShaderCompiler/Resources/ResourceMaterializer.cs +++ b/src/SharpEmu.ShaderCompiler/Resources/ResourceMaterializer.cs @@ -677,7 +677,7 @@ public static FastRevalidation RevalidateOrRebuildFast(ResourceSnapshot snapshot _lastFastOutcome = MaterializationTally.Outcome.FastMiss; ResourceSnapshot next = null!; ResourceSpecialization specialization = null!; - if (!MaterializeFromOutput(plan, inputs, output, ref next, ref specialization, out _)) + if (!MaterializeFromOutput(plan, inputs, output, ref next, ref specialization, out _, previous: snapshot)) { _lastRebuildRefusal = RebuildRefusal.Failed; return FastRevalidation.Stale; @@ -1330,8 +1330,11 @@ public static bool MaterializeFast( } } + // previous: the snapshot a rebuild replaces; with a specialization memo hit, a buffer whose words it already holds + // takes its array (published snapshots are never written, so equal words can share one). private static bool MaterializeFromOutput(ShaderResourcePlan plan, ResourceRuntimeInputs inputs, MaterializationProgram.Output output, - ref ResourceSnapshot snapshot, ref ResourceSpecialization specialization, out ResourceMaterializationFailure failure) + ref ResourceSnapshot snapshot, ref ResourceSpecialization specialization, out ResourceMaterializationFailure failure, + ResourceSnapshot? previous = null) { var info = plan.Info; var bufferCount = info.Buffers.Count; @@ -1355,10 +1358,19 @@ private static bool MaterializeFromOutput(ShaderResourcePlan plan, ResourceRunti } var buffers = new uint[bufferCount][]; + var held = memo is not null && previous is not null && previous.Buffers.Length == bufferCount ? previous.Buffers : null; for (var index = 0; index < bufferCount; index++) { var words = output.Source(index); - buffers[index] = memo is not null && (words[3] >> 30) != 0 ? new uint[words.Length] : words.ToArray(); + var zeroed = memo is not null && (words[3] >> 30) != 0; + if (held is not null && held[index] is { } kept && kept.Length == words.Length && + (zeroed ? !kept.AsSpan().ContainsAnyExcept(0u) : kept.AsSpan().SequenceEqual(words))) + { + buffers[index] = kept; + continue; + } + + buffers[index] = zeroed ? new uint[words.Length] : words.ToArray(); } var table = output.TableWords.ToArray(); From a4de7e6071f674ae3bc77052b8ce5c02c8549058 Mon Sep 17 00:00:00 2001 From: kuba Date: Sun, 15 Nov 2026 23:50:14 +0000 Subject: [PATCH 105/178] [GPU] Keep a new key's resolution only on its second miss, and share a rebuild's unchanged stage A draw whose user data names a new ring address every frame (Demon's Souls: ~6% of draws, key_miss user_data_only ~= evictions) got a memo entry, key copy and program graph per frame that the long-lived memo held until evicted, and pushed out entries that would have hit. A new key's full resolution is now kept only when a two-probe Bloom filter saw the key miss before (cleared after twice the capacity of first misses); first_miss_not_kept counts the rest. SHARPEMU_RESOLVE_MEMO_ADMIT_SEEN=0 keeps every new key as before. A rebuild now copies only the rebuilt stage's input description (the other is shared, as a hit shares the whole result), and the churn-hold signature hashes only the rebuilt stages' flattened tables (the full-snapshot hash cost ~250 ns per rebuild). ResolveMemoRetentionBench (256 draws/frame, ABBA medians): words churn 1352 B allocated / 1352 B retained per draw before, 872 B / 0 B after; new keys 3674 B / 3091 B before, 1664 B / 6 B after, resolve 11.1 -> 8.7 us; verify finds every take exact. --- .../Gpu/Pipelines/GraphicsResolveMemo.cs | 46 +++++++++++ .../Gpu/Pipelines/ShaderPipelineCache.cs | 79 +++++++++++-------- .../KeptStageInputsTests.ResolveMemo.cs | 33 +++++++- .../ResolveMemoRetentionBenchTests.cs | 77 +++++++++++++++--- 4 files changed, 189 insertions(+), 46 deletions(-) diff --git a/src/SharpEmu.Libs/Gpu/Pipelines/GraphicsResolveMemo.cs b/src/SharpEmu.Libs/Gpu/Pipelines/GraphicsResolveMemo.cs index b66688772..b798b88f7 100644 --- a/src/SharpEmu.Libs/Gpu/Pipelines/GraphicsResolveMemo.cs +++ b/src/SharpEmu.Libs/Gpu/Pipelines/GraphicsResolveMemo.cs @@ -106,6 +106,14 @@ internal sealed class GraphicsResolveMemo // settle are kept on their second rebuild and hit from then on. Only what is kept changes, never a result. internal static readonly bool DefaultHoldChurn = Environment.GetEnvironmentVariable("SHARPEMU_RESOLVE_MEMO_HOLD_CHURN") != "0"; + // SHARPEMU_RESOLVE_MEMO_ADMIT_SEEN=0: every full resolution under a new key is kept, as before. On (default), it is kept + // only when its key was missed before (SeenBefore): a draw whose user data names a new ring address every frame + // (Demon's Souls: ~6% of its draws, key_miss user_data_only ~= evictions) resolves in full every frame anyway, and + // keeping each of those resolutions made the long-lived memo point at a new entry, key and program graph per draw + // (promoted by every gen0 collection) while evicting entries that would have hit. A key that comes back is kept on + // its second miss and hits from its third take. Only what is kept changes, never a result. + internal static readonly bool DefaultAdmitSeen = Environment.GetEnvironmentVariable("SHARPEMU_RESOLVE_MEMO_ADMIT_SEEN") != "0"; + internal static ResolveMemoMode ParseMode(string? value) => value?.Trim().ToLowerInvariant() switch { "0" or "off" => ResolveMemoMode.Off, @@ -164,6 +172,30 @@ public GraphicsResolveMemo(ResolveMemoMode mode, int capacity) while (sets * Ways < capacity) sets <<= 1; _setMask = sets - 1; _ways = new Entry?[sets * Ways]; + // Eight bits per key the filter holds before it is cleared. + _seen = new ulong[Math.Max(1, _ways.Length * 2 * 8 / 64)]; + _seenMask = _seen.Length * 64 - 1; + } + + // Whether the filled key was missed before (since the filter was last cleared); records it when not. + public bool SeenBefore() + { + var first = (int)(Hash & (ulong)_seenMask); + var second = (int)((Hash >> 32) & (ulong)_seenMask); + if ((_seen[first >> 6] & (1UL << first)) != 0 && (_seen[second >> 6] & (1UL << second)) != 0) + { + return true; + } + + if (++_seenAdded > _ways.Length * 2) + { + Array.Clear(_seen); + _seenAdded = 1; + } + + _seen[first >> 6] |= 1UL << first; + _seen[second >> 6] |= 1UL << second; + return false; } public ResolveMemoMode Mode { get; } @@ -175,6 +207,16 @@ public GraphicsResolveMemo(ResolveMemoMode mode, int capacity) // tests set it). public bool HoldChurn { get; set; } = DefaultHoldChurn; + // Whether a new key's resolution is kept only on the key's second miss (DefaultAdmitSeen; tests set it). + public bool AdmitSeen { get; set; } = DefaultAdmitSeen; + + // The keys missed since the filter was last cleared, as a two-probe Bloom filter over the key hash: a false positive + // keeps a resolution on its first miss (as with AdmitSeen off), and a key is forgotten only when the filter is + // cleared, after twice the memo's capacity of first misses (~3% false positives at that fill). + private readonly ulong[] _seen; + private readonly int _seenMask; + private int _seenAdded; + public int Count => _count; public ulong Hash { get; private set; } @@ -404,6 +446,7 @@ public Entry Store() private static readonly ThreadCounter _hits = new(); private static readonly ThreadCounter _rebuilt = new(); private static readonly ThreadCounter _rebuildHeld = new(); + private static readonly ThreadCounter _notAdmitted = new(); private static readonly ThreadCounter[] _rebuildRefused = NewCounters((int)ResolveMemoRebuildRefusal.Count); private static readonly ThreadCounter _evictions = new(); private static readonly ThreadCounter _entries = new(); @@ -423,6 +466,8 @@ public Entry Store() public static void NoteRebuildHeld() => _rebuildHeld.Increment(); + public static void NoteNotAdmitted() => _notAdmitted.Increment(); + public static void NoteRebuildRefused(ResolveMemoRebuildRefusal cause) => _rebuildRefused[(int)cause].Increment(); public static void NoteShadowHit() => _shadowWouldHit.Increment(); @@ -454,6 +499,7 @@ public static string TakeReport() => FormattableString.Invariant( "rebuild_refused_by=(" + Take(_rebuildRefused, "origin", "refused", "evaluate", "failed", "specialization", "generation") + ")," + "key_miss=(" + Take(_keyMisses, "new", "user_data_only", "regs_only") + ")," + "uncacheable_by=(" + Take(_uncacheable, "frontend", "mesh", "tess", "calls", "unavailable", "tables", "trace", "origin", "key", "changed") + ")," + + FormattableString.Invariant($"first_miss_not_kept={_notAdmitted.Take()},admit_seen={(DefaultAdmitSeen ? 1 : 0)},") + FormattableString.Invariant($"evictions={_evictions.Take()},entries={_entries.Total},verify_checked={_verifyChecked.Take()},") + "verify_raced=(" + Take(_verifyRaced, "changed", "came_and_went", "superseded") + ")," + FormattableString.Invariant($"verify_failed={Interlocked.Read(ref _verifyFailed)})"); diff --git a/src/SharpEmu.Libs/Gpu/Pipelines/ShaderPipelineCache.cs b/src/SharpEmu.Libs/Gpu/Pipelines/ShaderPipelineCache.cs index 2408db980..a78dff358 100644 --- a/src/SharpEmu.Libs/Gpu/Pipelines/ShaderPipelineCache.cs +++ b/src/SharpEmu.Libs/Gpu/Pipelines/ShaderPipelineCache.cs @@ -395,6 +395,19 @@ internal bool ResolveMemoHoldChurn } } + // For tests: whether this cache's memo keeps a new key's resolution only on its second miss (GraphicsResolveMemo.AdmitSeen). + internal bool ResolveMemoAdmitSeen + { + get => _resolveMemo?.AdmitSeen ?? false; + set + { + lock (_resolveGate) + { + if (_resolveMemo is { } memo) memo.AdmitSeen = value; + } + } + } + // Shadow mode: counts whether the memo would have the draw's key; true when it has not and the key is to be stored // once the draw resolved. private bool ShadowResolveMemo(RegisterBanks banks, ReadOnlySpan targetExportMapping, in KeptGraphicsFlags flags) @@ -475,6 +488,12 @@ private GraphicsPrograms ResolveThroughMemo(GraphicsResolveMemo memo, RegisterBa { GraphicsResolveMemo.NoteMiss(ResolveMemoMiss.New); GraphicsResolveMemo.NoteKeyMiss(memo.ClassifyMiss()); + // GraphicsResolveMemo.DefaultAdmitSeen: a key's first miss resolves in full without being kept. + if (memo.AdmitSeen && !memo.SeenBefore()) + { + GraphicsResolveMemo.NoteNotAdmitted(); + cacheable = false; + } } } @@ -568,12 +587,15 @@ private GraphicsPrograms ResolveFull(RegisterBanks banks, ReadOnlySpan - words is null ? hash * 31 + 1 : XxHash3.HashToUInt64(MemoryMarshal.AsBytes(words.AsSpan()), (long)(hash + (ulong)words.Length)); + private static ulong SignTable(ulong hash, ResourceSnapshot snapshot) => + XxHash3.HashToUInt64(MemoryMarshal.AsBytes(snapshot.FlattenedResourceTable.AsSpan()), (long)hash); // False when the stage's words no longer evaluate to its snapshot and it was not rebuilt (refusals counted). private bool RevalidateMemoStage(ref ShaderStageResources stage, bool rebuild, ref bool rebuilt) @@ -672,12 +681,18 @@ private bool RevalidateMemoStage(ref ShaderStageResources stage, bool rebuild, r } } - // The programs with these stage resources in place of their own; the input descriptions are copied, never written: - // the result held before may still be on its way to the worker. - private static GraphicsPrograms WithStages(GraphicsPrograms programs, in ShaderStageResources vertexStage, ShaderStageResources? pixelStage) + // The programs with these stage resources in place of their own; the input descriptions of a rebuilt stage are + // copied, never written: the result held before may still be on its way to the worker. A stage not rebuilt keeps its + // input description, shared as a hit shares the whole result. + private static GraphicsPrograms WithStages(GraphicsPrograms programs, ShaderStageResources? vertexStage, ShaderStageResources? pixelStage) { - var vertexInput = programs.VertexInput.WithoutStage(); - vertexInput.Stage = vertexStage; + var vertexInput = programs.VertexInput; + if (vertexStage is { } vertex) + { + vertexInput = vertexInput.WithoutStage(); + vertexInput.Stage = vertex; + } + var pixelInput = programs.PixelInput; if (pixelStage is { } pixel) { diff --git a/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/KeptStageInputsTests.ResolveMemo.cs b/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/KeptStageInputsTests.ResolveMemo.cs index 8e8443577..95c752e19 100644 --- a/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/KeptStageInputsTests.ResolveMemo.cs +++ b/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/KeptStageInputsTests.ResolveMemo.cs @@ -20,8 +20,9 @@ public sealed partial class KeptStageInputsTests private const ulong Descriptor = PipelineTestGuest.MemoryBase + 0xD000; private const ulong OtherDescriptor = PipelineTestGuest.MemoryBase + 0xD100; - private ShaderPipelineCache MemoCache(ResolveMemoMode mode = ResolveMemoMode.Verify) => - new(_guest.Context, _guest.Host, _guest.Compiler, _guest.Registry) { ResolveMemoMode = mode }; + // admitSeen false (most tests here): a new key's resolution is kept on its first miss, so the second take hits. + private ShaderPipelineCache MemoCache(ResolveMemoMode mode = ResolveMemoMode.Verify, bool admitSeen = false) => + new(_guest.Context, _guest.Host, _guest.Compiler, _guest.Registry) { ResolveMemoMode = mode, ResolveMemoAdmitSeen = admitSeen }; private GraphicsPrograms Programs(ShaderPipelineCache cache, bool pixelActive) { @@ -132,6 +133,34 @@ public void ResolveMemo_RebuildsAWordsMissFromItsRevalidationAsTheFullResolution Assert.Contains("hits=1,", Report()); } + // With the first-miss filter (default), a new key's full resolution is kept only on the key's second miss: a key seen + // once (a draw whose user data names a new address every frame) leaves nothing in the memo. + [Fact] + public void ResolveMemo_KeepsANewKeysResolutionOnlyOnItsSecondMiss() + { + var cache = MemoCache(admitSeen: true); + Assert.True(cache.ResolveMemoAdmitSeen); + UseLoadingPixelProgram(Descriptor); + Report(); + var first = Programs(cache, pixelActive: true); + var second = Programs(cache, pixelActive: true); + var report = Report(); + Assert.NotSame(first, second); + Assert.Contains("new=2,", report); + Assert.Contains("first_miss_not_kept=1,", report); + Assert.Same(second, Programs(cache, pixelActive: true)); + report = Report(); + Assert.Contains("hits=1,", report); + Assert.Contains("verify_failed=0)", report); + + // Another key seen once is not kept and leaves the kept one in place. + PointPixelAt(OtherDescriptor); + Programs(cache, pixelActive: true); + Assert.Contains("first_miss_not_kept=1,", Report()); + PointPixelAt(Descriptor); + Assert.Same(second, Programs(cache, pixelActive: true)); + } + // With the churn hold (default), a rebuild is handed out without the entry keeping it until a rebuild evaluates the // same words as the one before it: a draw whose words move on every take leaves the memo pointing at what it kept, // and words that settle are kept on their second rebuild and hit after that. Verify finds every take exact. diff --git a/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/ResolveMemoRetentionBenchTests.cs b/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/ResolveMemoRetentionBenchTests.cs index 905da6fa0..f9661cb2d 100644 --- a/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/ResolveMemoRetentionBenchTests.cs +++ b/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/ResolveMemoRetentionBenchTests.cs @@ -144,6 +144,7 @@ private void PointPixelAt(ulong block) if (measured && frame == WarmFrames) { GraphicsResolveMemo.TakeReport(); + SharpEmu.ShaderCompiler.Resources.ResourceMaterializer.TakeReadProofReport(); } for (var draw = 0; draw < Draws; draw++) @@ -182,26 +183,78 @@ private void PointPixelAt(ulong block) } } - var report = GraphicsResolveMemo.TakeReport(); + var report = GraphicsResolveMemo.TakeReport() + " " + SharpEmu.ShaderCompiler.Resources.ResourceMaterializer.TakeReadProofReport(); Assert.Empty(_fatal.Messages); GC.KeepAlive(cache); return ((double)allocated / (Draws * MeasuredFrames), (double)retained / MeasuredFrames, ticks * 1e9 / Stopwatch.Frequency / (Draws * MeasuredFrames), report); } - // tuned false: the memo as it was before the retention changes (every rebuild kept). + // tuned false: the memo as it was before the retention changes (every rebuild and every new key's resolution kept). + // Both arms run on caches of their own in ABBA order (three rounds) after a warm-up pass of each; the timing is each arm's + // median. [Theory] - [InlineData(Churn.None, true)] - [InlineData(Churn.Words, true)] - [InlineData(Churn.Keys, true)] - [InlineData(Churn.Words, false)] - [InlineData(Churn.Keys, false)] - public void ResolveMemoRetentionBench(Churn churn, bool tuned) + [InlineData(Churn.None)] + [InlineData(Churn.Words)] + [InlineData(Churn.Keys)] + public void ResolveMemoRetentionBench(Churn churn) { - var (alloc, retained, ns, report) = Run(churn, ResolveMemoMode.On, cache => cache.ResolveMemoHoldChurn = tuned); - _output.WriteLine(FormattableString.Invariant( - $"churn={churn} tuned={tuned} draws/frame={Draws} alloc_per_draw={alloc:F0} B retained_per_frame={retained / 1024:F1} KiB ({retained / Draws:F0} B/draw) resolve={ns:F0} ns/draw")); - _output.WriteLine(report); + (double Alloc, double Retained, double Ns, string Report) Arm(bool tuned) => Run(churn, ResolveMemoMode.On, cache => + { + cache.ResolveMemoHoldChurn = tuned; + cache.ResolveMemoAdmitSeen = tuned; + }); + + Arm(false); + Arm(true); + var arms = new[] { new List<(double Alloc, double Retained, double Ns, string Report)>(), new() }; + for (var round = 0; round < 3; round++) + { + foreach (var tuned in new[] { false, true, true, false }) + { + arms[tuned ? 1 : 0].Add(Arm(tuned)); + } + } + + foreach (var tuned in new[] { false, true }) + { + var runs = arms[tuned ? 1 : 0]; + var times = runs.Select(run => run.Ns).Order().ToArray(); + _output.WriteLine(FormattableString.Invariant( + $"churn={churn} tuned={tuned} draws/frame={Draws} alloc_per_draw={runs[0].Alloc:F0} B retained_per_frame={runs[0].Retained / 1024:F1} KiB ({runs[0].Retained / Draws:F0} B/draw) resolve_median={times[times.Length / 2]:F0} ns/draw (min {times[0]:F0}, max {times[^1]:F0}, n={times.Length})")); + _output.WriteLine(runs[^1].Report); + } + } + + // A rebuild shares what its words left as they were: the input description of the stage not rebuilt, and the word + // arrays of the six V#s that kept their base; verify finds it exact. + [Fact] + public void ARebuildSharesWhatItsWordsLeftUnchanged() + { + var cache = new ShaderPipelineCache(_guest.Context, _guest.Host, _guest.Compiler, _guest.Registry) + { + ResolveMemoMode = ResolveMemoMode.Verify, + ResolveMemoAdmitSeen = false, + }; + var block = BlockOf(Churn.Words, 0, 0); + WriteBlock(block, 0, 0, moveWords: true); + PointPixelAt(block); + var first = cache.GetGraphicsPrograms(_banks, [], pixelActive: true, depthBound: false); + GraphicsResolveMemo.TakeReport(); + WriteBlock(block, 0, 1, moveWords: true); + var rebuilt = cache.GetGraphicsPrograms(_banks, [], pixelActive: true, depthBound: false); + var report = GraphicsResolveMemo.TakeReport(); + Assert.Contains("words_rebuilt=1,", report); + Assert.Contains("verify_failed=0)", report); + Assert.NotSame(first, rebuilt); + Assert.Same(first.VertexInput, rebuilt.VertexInput); + Assert.NotSame(first.PixelInput, rebuilt.PixelInput); + var before = first.PixelInput.Stage.Resources.Buffers; + var after = rebuilt.PixelInput.Stage.Resources.Buffers; + Assert.Equal(Buffers, after.Length); + Assert.Equal(Buffers - 2, after.Count(words => before.Any(held => ReferenceEquals(held, words)))); + Assert.Equal(2, after.Count(words => !before.Any(held => held.AsSpan().SequenceEqual(words)))); + Assert.Empty(_fatal.Messages); } // The same frames under verify: every hit and rebuild is resolved again in full and compared. From 6b938703fee34b003e6302c77a113761db94e84c Mon Sep 17 00:00:00 2001 From: kuba Date: Sun, 15 Nov 2026 23:51:45 +0000 Subject: [PATCH 106/178] [GPU] Hold a memo rebuild only when it follows another rebuild of the entry Holding every rebuild whose words differ from the last rebuild's cost the hits of draws whose words change every other take (each change was held, rebuilt again, then kept). A rebuild right after a hit is now kept at once as before; only a rebuild that follows another one is held unless both evaluated the same words, and the signature is computed only then. A draw whose words move on every take still keeps nothing after its first change (bench: 0 B retained per draw, resolve time equal to keeping every rebuild: 1719 vs 1730 ns median). --- .../Gpu/Pipelines/GraphicsResolveMemo.cs | 20 +++++++++------- .../Gpu/Pipelines/ShaderPipelineCache.cs | 22 +++++++++++++----- .../KeptStageInputsTests.ResolveMemo.cs | 23 ++++++++++++------- 3 files changed, 43 insertions(+), 22 deletions(-) diff --git a/src/SharpEmu.Libs/Gpu/Pipelines/GraphicsResolveMemo.cs b/src/SharpEmu.Libs/Gpu/Pipelines/GraphicsResolveMemo.cs index b798b88f7..d02bf1625 100644 --- a/src/SharpEmu.Libs/Gpu/Pipelines/GraphicsResolveMemo.cs +++ b/src/SharpEmu.Libs/Gpu/Pipelines/GraphicsResolveMemo.cs @@ -98,12 +98,14 @@ internal sealed class GraphicsResolveMemo internal static readonly bool DefaultRebuild = Environment.GetEnvironmentVariable("SHARPEMU_RESOLVE_MEMO_REBUILD") != "0"; // SHARPEMU_RESOLVE_MEMO_HOLD_CHURN=0: every rebuilt words miss replaces its entry's programs, as before. On (default), a - // rebuild is kept only when it evaluated the same words as the entry's last rebuild (Entry.RebuildSignature): a draw - // whose descriptor words move on every take (Demon's Souls: ring-allocated constant buffers, ~1/3 of its draws) is - // handed its rebuilt programs without the long-lived entry pointing at them, so they die young instead of being - // promoted by every gen0 collection (~56 MB each in game) and compacted. Its next take revalidates the programs the - // entry kept and rebuilds again, the work a kept rebuild would have cost it (its words moved again); words that - // settle are kept on their second rebuild and hit from then on. Only what is kept changes, never a result. + // rebuild right after another rebuild of the same entry is kept only when it evaluated the same words as that one + // (Entry.RebuildSignature): a draw whose descriptor words move on every take (Demon's Souls: ring-allocated constant + // buffers, ~1/3 of its draws) is handed its rebuilt programs without the long-lived entry pointing at them, so they die + // young instead of being promoted by every gen0 collection (~56 MB each in game) and compacted. Its next take + // revalidates the programs the entry kept and rebuilds again, the work a kept rebuild would have cost it (its words + // moved again); words that settle are kept on their second rebuild and hit from then on, and a change after a hit is + // kept at once as before (words that change every other take keep their hits). Only what is kept changes, never a + // result. internal static readonly bool DefaultHoldChurn = Environment.GetEnvironmentVariable("SHARPEMU_RESOLVE_MEMO_HOLD_CHURN") != "0"; // SHARPEMU_RESOLVE_MEMO_ADMIT_SEEN=0: every full resolution under a new key is kept, as before. On (default), it is kept @@ -145,8 +147,10 @@ internal sealed class Entry public long TablesGeneration; // GraphicsProgramsComparer.Fingerprint at insertion (verify: nothing wrote the shared result since). public ulong Fingerprint; - // The signature of the words this entry's last rebuild evaluated (HoldChurn), 0 before any. + // The signature of the words this entry's last rebuild evaluated when it followed another rebuild (HoldChurn), else 0. public ulong RebuildSignature; + // Whether the entry's last take rebuilt (kept or not) rather than hit (HoldChurn). + public bool RebuiltLast; } private const int MaxKeyBytes = 4096; @@ -203,7 +207,7 @@ public bool SeenBefore() // Whether a words miss is rebuilt from its revalidation (DefaultRebuild; tests set it). public bool Rebuild { get; set; } = DefaultRebuild; - // Whether a rebuild whose words differ from the entry's last rebuild is handed out without being kept (DefaultHoldChurn; + // Whether a rebuild that follows another one with other words is handed out without being kept (DefaultHoldChurn; // tests set it). public bool HoldChurn { get; set; } = DefaultHoldChurn; diff --git a/src/SharpEmu.Libs/Gpu/Pipelines/ShaderPipelineCache.cs b/src/SharpEmu.Libs/Gpu/Pipelines/ShaderPipelineCache.cs index a78dff358..84bd8158c 100644 --- a/src/SharpEmu.Libs/Gpu/Pipelines/ShaderPipelineCache.cs +++ b/src/SharpEmu.Libs/Gpu/Pipelines/ShaderPipelineCache.cs @@ -608,24 +608,34 @@ private GraphicsPrograms ResolveFull(RegisterBanks banks, ReadOnlySpan words[0] == unchecked((uint)(StreamBase + 0x100))); Assert.Contains(movedAgain.PixelInput.Stage.Resources.Buffers, words => words[0] == unchecked((uint)(StreamBase + 0x200))); + Assert.Contains(movedThird.PixelInput.Stage.Resources.Buffers, words => words[0] == unchecked((uint)(StreamBase + 0x300))); // The same words again: rebuilt from the kept programs once more, and this time kept. var settled = Programs(cache, pixelActive: true); report = Report(); - Assert.NotSame(movedAgain, settled); + Assert.NotSame(movedThird, settled); Assert.Contains("words_rebuilt=1,", report); Assert.Contains("rebuilt_not_kept=0,", report); Assert.Same(settled, Programs(cache, pixelActive: true)); Assert.Contains("hits=1,", Report()); - // Back to the first words: the kept rebuild no longer holds, and the first programs are as they were. + // A change after a hit is kept at once. _guest.WriteWords(Descriptor, PipelineTestGuest.BufferDescriptor(StreamBase, 16, 4, Format32x4Float)); var back = Programs(cache, pixelActive: true); Assert.NotSame(settled, back); Assert.Equal(first.PixelInput.Stage.Resources.Buffers, back.PixelInput.Stage.Resources.Buffers); + Assert.Contains("rebuilt_not_kept=0,", Report()); + Assert.Same(back, Programs(cache, pixelActive: true)); Assert.Contains("verify_failed=0)", Report()); } From a0846a4a1beb596e293087b177edbbb30c5c5973 Mon Sep 17 00:00:00 2001 From: kuba Date: Mon, 16 Nov 2026 00:05:47 +0000 Subject: [PATCH 107/178] [Agc] Take a copyless submit whose buffer only a read can answer for, and keep geometry capture its own capability Review of 7f7789944: ICpuMemory.CanRead wants one mapping where TryRead reads a range that spans mappings in pieces, so a command buffer over two mappings would have been refused with MEMORY_FAULT on the split backend. A buffer CanRead refuses is now read once to decide, which is what the copy did. Geometry snapshots are captured for a backend that reads them whether or not it reads the command bytes, as the multi-buffer submit does. --- .../Agc/AgcExports.Submissions.cs | 24 +++++++++++++++---- .../Agc/AgcSubmissionPreparationTests.cs | 19 +++++++++++++++ 2 files changed, 39 insertions(+), 4 deletions(-) diff --git a/src/SharpEmu.Libs/Agc/AgcExports.Submissions.cs b/src/SharpEmu.Libs/Agc/AgcExports.Submissions.cs index 6fc5dccbd..41c049734 100644 --- a/src/SharpEmu.Libs/Agc/AgcExports.Submissions.cs +++ b/src/SharpEmu.Libs/Agc/AgcExports.Submissions.cs @@ -80,7 +80,7 @@ public static int DriverSubmitDcb(CpuContext ctx) if (dwordCount > 0xF_FFFF) return SetReturn(ctx, OrbisGen2Result.ORBIS_GEN2_ERROR_INVALID_ARGUMENT); var commandLength = (int)dwordCount * sizeof(uint); - SubmittedCommandBuffer? submitted = null; + object? submitted; if (GuestGpu.Current.ConsumesSubmittedCommandBytes) { var commandBytes = System.Buffers.ArrayPool.Shared.Rent(commandLength); @@ -94,12 +94,21 @@ public static int DriverSubmitDcb(CpuContext ctx) var snapshots = CaptureSubmittedGeometry(ctx, gpuState, commandAddress, dwordCount); submitted = new SubmittedCommandBuffer(commandBytes, snapshots, registerTables) { Length = commandLength, Pooled = true }; } - else if (commandLength != 0 && !ctx.Memory.CanRead(commandAddress, (ulong)commandLength)) + else { // This backend's host reads the stream from guest memory itself and is handed no // copy (the copy was rented, filled, scanned for tables and then dropped unread on - // every submit): the submit only answers for the range being mapped, as the copy did. - return SetReturn(ctx, OrbisGen2Result.ORBIS_GEN2_ERROR_MEMORY_FAULT); + // every submit): the submit only answers for the buffer being readable, as the copy + // did. CanRead wants one mapping; a buffer it refuses (one that spans mappings) is + // read once to decide, which is what the copy was. + if (commandLength != 0 && !ctx.Memory.CanRead(commandAddress, (ulong)commandLength) && + !IsReadableByCopy(ctx.Memory, commandAddress, commandLength)) + { + return SetReturn(ctx, OrbisGen2Result.ORBIS_GEN2_ERROR_MEMORY_FAULT); + } + + // Geometry snapshots are their own capability, as in the multi-buffer submit. + submitted = CaptureSubmittedGeometry(ctx, gpuState, commandAddress, dwordCount); } SubmissionFlowProfile.RecordGuest(SubmissionFlowProfile.EventKind.GeometryCaptureFinished, @@ -432,6 +441,13 @@ public static int DriverSubmitMultiDcbs(CpuContext ctx) return (int)OrbisGen2Result.ORBIS_GEN2_OK; } + private static bool IsReadableByCopy(ICpuMemory memory, ulong address, int length) + { + var scratch = System.Buffers.ArrayPool.Shared.Rent(length); + try { return memory.TryRead(address, scratch.AsSpan(0, length)); } + finally { System.Buffers.ArrayPool.Shared.Return(scratch); } + } + private static Dictionary? CaptureSubmittedTables(CpuContext ctx, ulong address, ReadOnlySpan commands) { var words = System.Runtime.InteropServices.MemoryMarshal.Cast(commands); diff --git a/tests/SharpEmu.Libs.Tests/Agc/AgcSubmissionPreparationTests.cs b/tests/SharpEmu.Libs.Tests/Agc/AgcSubmissionPreparationTests.cs index f4deb0380..dcb8c8873 100644 --- a/tests/SharpEmu.Libs.Tests/Agc/AgcSubmissionPreparationTests.cs +++ b/tests/SharpEmu.Libs.Tests/Agc/AgcSubmissionPreparationTests.cs @@ -138,6 +138,25 @@ public void SubmitOfAnUnmappedCommandBufferIsAMemoryFaultWhetherOrNotTheHostRead Assert.Equal(0, backend.Admissions); } + // CanRead answers for one mapping; the copy read a buffer that spans mappings in pieces. + [Fact] + public void SubmitWithoutACopyStillTakesABufferThatOnlyAReadCanAnswerFor() + { + var memory = new ReadOnlyAnswers(Memory()); + var backend = new StreamReadingBackend(); + using var scope = new BackendScope(backend); + var context = new CpuContext(memory, Generation.Gen5); + context[CpuRegister.Rdi] = Packet; + Assert.Equal(0, AgcExports.DriverSubmitDcb(context)); + Assert.Equal(1, backend.Admissions); + } + + private sealed class ReadOnlyAnswers(FakeCpuMemory inner) : ICpuMemory + { + public bool TryRead(ulong virtualAddress, Span destination) => inner.TryRead(virtualAddress, destination); + public bool TryWrite(ulong virtualAddress, ReadOnlySpan source) => inner.TryWrite(virtualAddress, source); + } + private static FakeCpuMemory Memory() { var memory = new FakeCpuMemory(Base, 0x1000); From 7afc253cc00bb41a4e92491e9bda2509563a79bd Mon Sep 17 00:00:00 2001 From: kuba Date: Mon, 16 Nov 2026 01:02:14 +0000 Subject: [PATCH 108/178] [Diag] Early-label probe: publish chosen command-processor writes once the previous flip has completed SHARPEMU_METAL_V2_EARLY_LABEL_PROBE=1|all|, default off. A measurement of what the guest does when a frame-pacing word lands before the GPU work recorded ahead of it; it breaks the console's ordering and is not a mode to play in. Demon's Souls: =1 and =all die in ~30 s (the game recycles command buffers on its per-buffer done markers); the two frame words alone change nothing, the game starts its next frame on flip completion. --- .../V2/MetalCommandStream.cs | 68 +++++++++++++++++++ .../V2/MetalV2Diagnostics.cs | 39 +++++++++++ 2 files changed, 107 insertions(+) diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalCommandStream.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalCommandStream.cs index 4fc10db5c..4ebfb6185 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalCommandStream.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalCommandStream.cs @@ -893,6 +893,7 @@ public void RecordEndOfPipe(in EndOfPipeWrite write) break; case EndOfPipeWriteKind.Flip: case EndOfPipeWriteKind.FlipWithWrite32: + NoteFlipSerialForEarlyLabels(); QueueCompletion(() => { if (!encoded) PublishHostLabel(in label, owed); @@ -901,6 +902,7 @@ public void RecordEndOfPipe(in EndOfPipeWrite write) }); break; case EndOfPipeWriteKind.FlipWithInterruptWriteBack32: + NoteFlipSerialForEarlyLabels(); QueueCompletion(() => { if (!encoded) PublishHostLabel(in label, owed); @@ -1413,6 +1415,11 @@ public void RecordCommandProcessorWrite(ulong address, ReadOnlySpan source throw Fatal($"A command-processor write has an invalid range: address=0x{address:X16} bytes={source.Length}."); } + if (TryPublishEarlyLabel(address, source, kind, causal)) + { + return; + } + if (TryEncodeCommandProcessorWrite(address, source, kind, causal)) { Interlocked.Increment(ref _gpuTimedCommandProcessorWrites); @@ -1447,6 +1454,67 @@ public void RecordCommandProcessorWrite(ulong address, ReadOnlySpan source }, lazy ? (address, bytes.Length) : null); } + // SHARPEMU_METAL_V2_EARLY_LABEL_PROBE (MetalV2Diagnostics.EarlyLabelProbe): the serial whose completion + // carries the last flip recorded so far. A probed write is published when that serial completes. + private ulong _earlyLabelFlipSerial; + private long _earlyLabelCount; + private long _earlyLabelAlreadyComplete; + + private void NoteFlipSerialForEarlyLabels() + { + if (MetalV2Diagnostics.EarlyLabelProbe == 0) + { + return; + } + + // The serial QueueCompletion is about to put the flip on. + var pending = LastWorkSerial; + _earlyLabelFlipSerial = pending != 0 && pending <= _previousSerial ? pending : SubmissionSerial; + } + + private bool TryPublishEarlyLabel(ulong address, ReadOnlySpan source, string kind, bool causal) + { + var mode = MetalV2Diagnostics.EarlyLabelProbe; + if (mode == 0 || source.Length > sizeof(ulong) || (mode == 1 && !causal) || + (mode == 3 && Array.IndexOf(MetalV2Diagnostics.EarlyLabelProbeAddresses, address) < 0)) + { + return false; + } + + var bytes = source.ToArray(); + var gate = _earlyLabelFlipSerial; + var count = Interlocked.Increment(ref _earlyLabelCount); + if (gate <= CompletedSerial) + { + Interlocked.Increment(ref _earlyLabelAlreadyComplete); + } + + if (count <= 16 || count % 4096 == 0) + { + Console.Error.WriteLine( + $"[METAL-V2][EARLY-LABEL] probe count={count} already_complete={Interlocked.Read(ref _earlyLabelAlreadyComplete)} " + + $"address=0x{address:X16} bytes={bytes.Length} value=0x{FirstValue(bytes):X} kind={kind} causal={causal} " + + $"gate={gate} open={SubmissionSerial} completed={CompletedSerial}"); + } + + var landedKind = CommandProcessorWriteHistory.Enabled ? "early:" + kind : null; + _completions.Enqueue(gate, () => + { + if (!_memory.TryWrite(address, bytes)) + { + throw Fatal( + $"An early command-processor write cannot be written to guest memory: address=0x{address:X16} bytes={bytes.Length}."); + } + + _imageCache.InvalidateMemory(address, (ulong)bytes.Length); + if (landedKind is not null && CommandProcessorWriteHistory.Enabled) + { + CommandProcessorWriteHistory.Record(-1, address, bytes.Length, FirstValue(bytes), landedKind, deferred: true); + } + }); + return true; + } + private bool TryEncodeCommandProcessorWrite(ulong address, ReadOnlySpan source, string kind, bool causal) { using var phaseScope = SharpEmu.Libs.VideoOut.RenderPhaseProfile.MeasureDetail(SharpEmu.Libs.VideoOut.RenderPhaseProfile.Phase.CommandProcessorWrite); diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalV2Diagnostics.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalV2Diagnostics.cs index bd4c173f3..4bd321076 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalV2Diagnostics.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalV2Diagnostics.cs @@ -143,6 +143,45 @@ private static HashSet ParseHashes(string? text) public static readonly bool DeferEndOfPipe = DeferBarriers && Environment.GetEnvironmentVariable("SHARPEMU_METAL_V2_DEFER_EOP") == "1"; + // SHARPEMU_METAL_V2_EARLY_LABEL_PROBE=1 (or =all) is a measurement, not a mode to play in: a small + // command-processor write the interpreter flags causal (=all: any of up to eight bytes) reaches guest + // memory once the last flip recorded before it has completed, instead of after the GPU work recorded + // before the write. A title that paces its frames on such a word then submits its next frame while + // this one is still on the GPU, which is not what the console does: the guest may reuse memory the + // unfinished work still reads. It exists to measure what one frame of overlap would be worth. + // A comma-separated list of hex addresses instead narrows it to the writes that start at one of them. + public static readonly ulong[] EarlyLabelProbeAddresses = ParseEarlyLabelAddresses( + Environment.GetEnvironmentVariable("SHARPEMU_METAL_V2_EARLY_LABEL_PROBE")); + + public static readonly int EarlyLabelProbe = + Environment.GetEnvironmentVariable("SHARPEMU_METAL_V2_EARLY_LABEL_PROBE") switch + { + "1" => 1, + "all" => 2, + _ => EarlyLabelProbeAddresses.Length != 0 ? 3 : 0, + }; + + private static ulong[] ParseEarlyLabelAddresses(string? value) + { + if (string.IsNullOrWhiteSpace(value) || value is "1" or "all") + { + return []; + } + + var addresses = new List(); + foreach (var part in value.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)) + { + var text = part.StartsWith("0x", StringComparison.OrdinalIgnoreCase) ? part[2..] : part; + if (ulong.TryParse(text, System.Globalization.NumberStyles.HexNumber, + System.Globalization.CultureInfo.InvariantCulture, out var address)) + { + addresses.Add(address); + } + } + + return [.. addresses]; + } + // SHARPEMU_METAL_V2_REPORT_VERTEX_LAYOUT=1 keeps the vertex descriptor each // pipeline was built with, for the per-draw report: a stride or an attribute format // that does not match what the program fetches is invisible in everything else. From 9aad70d58e4e3f054dbc4def856fae4390238096 Mon Sep 17 00:00:00 2001 From: kuba Date: Mon, 16 Nov 2026 01:24:31 +0000 Subject: [PATCH 109/178] [VideoOut] Flip ahead: publish a recorded flip once the flip before it has really completed SHARPEMU_FLIP_AHEAD=1, default off. A GPU-queued flip the GPU host reports recorded, committed and captured as a copy (NoteFlipRecorded, carried across the split as FlipEvent Recorded) has its guest-visible completion published once the GPU-queued flip before it on the handle has really completed and been published; only the oldest unpublished request on a handle may go, so an unpublished CPU flip before it holds it back. The request stays for the pacer; its real completion still releases the GPU slot and sets the ready timestamp without publishing again or re-triggering events, and a cancel gives the slot back. A notice that arrives after the real completion is ignored. Off, or without notices, the sequence is unchanged. [VIDEOOUT][FLIP-AHEAD] reports flips published at record, at the previous completion, late notices and the mean lead over the real completion, at most every 2 s. --- src/SharpEmu.GpuRemote/GpuSplitMessages.cs | 3 + src/SharpEmu.GpuSplit/GuestProcessSide.cs | 3 + src/SharpEmu.GpuSplit/RemoteVideoOutBridge.cs | 2 + .../VideoOut/VideoOutBackendServices.cs | 12 + .../VideoOut/VideoOutExports.FlipAhead.cs | 233 ++++++++++++++ .../VideoOut/VideoOutExports.FlipRequests.cs | 74 ++++- .../Gpu/Split/SplitHookTests.cs | 2 + .../VideoOut/VideoOutFlipAheadTests.cs | 292 ++++++++++++++++++ 8 files changed, 610 insertions(+), 11 deletions(-) create mode 100644 src/SharpEmu.Libs/VideoOut/VideoOutExports.FlipAhead.cs create mode 100644 tests/SharpEmu.Libs.Tests/VideoOut/VideoOutFlipAheadTests.cs diff --git a/src/SharpEmu.GpuRemote/GpuSplitMessages.cs b/src/SharpEmu.GpuRemote/GpuSplitMessages.cs index d9eccfd68..359b55cb2 100644 --- a/src/SharpEmu.GpuRemote/GpuSplitMessages.cs +++ b/src/SharpEmu.GpuRemote/GpuSplitMessages.cs @@ -43,6 +43,9 @@ public enum GpuSplitFlipEvent : uint /// CompleteFlip. Completed = 6, + + /// NoteFlipRecorded (SHARPEMU_FLIP_AHEAD). + Recorded = 7, } /// The kinds of . diff --git a/src/SharpEmu.GpuSplit/GuestProcessSide.cs b/src/SharpEmu.GpuSplit/GuestProcessSide.cs index 425f27518..da4d46cd2 100644 --- a/src/SharpEmu.GpuSplit/GuestProcessSide.cs +++ b/src/SharpEmu.GpuSplit/GuestProcessSide.cs @@ -77,6 +77,9 @@ public void FlipEvent(GpuSplitFlipEvent kind, ulong requestId) case GpuSplitFlipEvent.Completed: VideoOutBackendServices.CompleteFlip(requestId); break; + case GpuSplitFlipEvent.Recorded: + VideoOutBackendServices.NoteFlipRecorded(requestId); + break; } } diff --git a/src/SharpEmu.GpuSplit/RemoteVideoOutBridge.cs b/src/SharpEmu.GpuSplit/RemoteVideoOutBridge.cs index 517144961..680a187c2 100644 --- a/src/SharpEmu.GpuSplit/RemoteVideoOutBridge.cs +++ b/src/SharpEmu.GpuSplit/RemoteVideoOutBridge.cs @@ -83,6 +83,8 @@ public bool IsFlipPresentationPending(ulong requestId) => public void MarkFlipPresented(ulong requestId) => FlipEvent(GpuSplitFlipEvent.Presented, requestId); + public void NoteFlipRecorded(ulong requestId) => FlipEvent(GpuSplitFlipEvent.Recorded, requestId); + public void NotifyPresentationWindowClosed() => host.SendNotice(GpuSplitNotice.PresentationWindowClosed); // Only a flip that names no buffer (-1) is released here; every other flip answers false without diff --git a/src/SharpEmu.Libs/VideoOut/VideoOutBackendServices.cs b/src/SharpEmu.Libs/VideoOut/VideoOutBackendServices.cs index 3b3dda0c5..aba99437e 100644 --- a/src/SharpEmu.Libs/VideoOut/VideoOutBackendServices.cs +++ b/src/SharpEmu.Libs/VideoOut/VideoOutBackendServices.cs @@ -74,6 +74,16 @@ public static void CompleteFlipOnGpu(ulong requestId) VideoOutExports.CompleteFlipOnGpu(requestId); } + // SHARPEMU_FLIP_AHEAD: the GPU host recorded the flip, committed the buffer carrying it + // and captured its frame as a copy (VideoOutExports.NoteFlipRecorded). + public static void NoteFlipRecorded(ulong requestId) + { + if (Bridge is { } bridge) + bridge.NoteFlipRecorded(requestId); + else + VideoOutExports.NoteFlipRecorded(requestId); + } + public static void DiscardFlip(ulong requestId) { if (Bridge is { } bridge) @@ -204,6 +214,8 @@ public interface IVideoOutBackendBridge void MarkFlipPresented(ulong requestId); + void NoteFlipRecorded(ulong requestId); + void NotifyPresentationWindowClosed(); bool ReleaseNoBufferFlip(int bufferIndex, ulong requestId); diff --git a/src/SharpEmu.Libs/VideoOut/VideoOutExports.FlipAhead.cs b/src/SharpEmu.Libs/VideoOut/VideoOutExports.FlipAhead.cs new file mode 100644 index 000000000..4ab7b331e --- /dev/null +++ b/src/SharpEmu.Libs/VideoOut/VideoOutExports.FlipAhead.cs @@ -0,0 +1,233 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using System.Diagnostics; + +namespace SharpEmu.Libs.VideoOut; + +// SHARPEMU_FLIP_AHEAD=1 (experimental, default off). A GPU-queued flip's guest-visible +// completion (flip count, process time, flip arg, current buffer, the previous buffer's +// label, the pending count and the flip events) is published once the GPU host has recorded +// the flip, committed the buffer carrying it and handed the presenter a copy of its frame +// (NoteFlipRecorded), and the GPU-queued flip before it on the handle has really completed +// on the GPU and been published. The guest is then at most one flip ahead of the GPU. The +// request itself stays in the table for the pacer, which presents or drops it as before, and +// its real GPU completion still releases the GPU slot and sets the ready timestamp. Without +// the notice (switch off, or a flip whose frame was not copied) nothing here runs. +public static partial class VideoOutExports +{ + internal static bool FlipAheadEnabled { get; set; } = string.Equals( + Environment.GetEnvironmentVariable("SHARPEMU_FLIP_AHEAD"), "1", StringComparison.Ordinal); + + // The last GPU-queued request reserved on each handle. Guarded by the state gate. + private static readonly Dictionary _lastGpuQueuedFlip = new(); + + private static long _flipAheadAtRecord; + private static long _flipAheadAtPrevious; + private static long _flipAheadLateNotices; + private static long _flipAheadLeadTicks; + private static long _flipAheadLeadCount; + private static long _flipAheadReportedAt; + + // Caller holds the state gate. + private static void NoteGpuQueuedFlipLocked(FlipRequest request) + { + if (_lastGpuQueuedFlip.TryGetValue(request.Handle, out var previous) && + previous.Outcome != FlipOutcome.Cancelled && + !(previous.State == FlipRequestState.Completed && previous.GpuCompleted && previous.EventsTriggered)) + { + request.AheadPrevious = previous; + } + + _lastGpuQueuedFlip[request.Handle] = request; + } + + /// + /// The GPU host recorded this flip, committed the command buffer that carries it and + /// captured its frame as a copy the guest cannot overwrite. A notice for a request that is + /// already past that point (its real completion came first, it was cancelled or published) + /// is ignored, and the flip keeps today's timing. + /// + internal static void NoteFlipRecorded(ulong requestId) + { + if (!FlipAheadEnabled) + { + return; + } + + int handle; + lock (_stateGate) + { + if (!_flipRequests.TryGetValue(requestId, out var request) || !request.GpuQueued || + request.State != FlipRequestState.Reserved) + { + Interlocked.Increment(ref _flipAheadLateNotices); + return; + } + + request.AheadRecorded = true; + handle = request.Handle; + } + + DrainFlipAhead(handle, requestId); + } + + // Caller holds the state gate. The real completion of a flip published ahead. + private static void CompleteAheadFlipOnGpuLocked(FlipRequest request) + { + ReleaseGpuQueueSlotLocked(request); + request.GpuCompleted = true; + Interlocked.Add(ref _flipAheadLeadTicks, Math.Max(0, Stopwatch.GetTimestamp() - request.AheadPublishedAt)); + Interlocked.Increment(ref _flipAheadLeadCount); + RemoveIfFinishedLocked(request); + Monitor.PulseAll(_stateGate); + } + + // Outside the state gate. The flip's counters were published: trigger its events, then let + // the flip after it go ahead if it was waiting for this one. + private static void TriggerPublishedFlip(FlipRequest request) + { + TriggerFlipEvents(request); + if (!FlipAheadEnabled) + { + return; + } + + lock (_stateGate) + { + request.EventsTriggered = true; + } + + DrainFlipAhead(request.Handle, noticed: 0); + } + + // Outside the state gate. Publishes, oldest first, every flip on the handle that may go + // ahead now. noticed is the request whose recorded notice is being handled, if any. + private static void DrainFlipAhead(int handle, ulong noticed) + { + if (!FlipAheadEnabled) + { + return; + } + + while (true) + { + FlipRequest? next; + lock (_stateGate) + { + next = FindFlipAheadCandidateLocked(handle); + if (next is not null) + { + // Set first: a dropped frame's request must outlive the publication until its + // real completion releases the GPU slot (RemoveIfFinishedLocked). + next.AheadPublishedAt = Stopwatch.GetTimestamp(); + PublishFlipLocked(next); + Interlocked.Increment(ref next.RequestId == noticed ? ref _flipAheadAtRecord : ref _flipAheadAtPrevious); + } + } + + if (next is null) + { + break; + } + + TriggerFlipEvents(next); + lock (_stateGate) + { + next.EventsTriggered = true; + } + } + + ReportFlipAhead(); + } + + // Caller holds the state gate. Only the oldest unpublished request on the handle may be + // published, so the guest sees flips in order; an unpublished CPU flip before it blocks it. + private static FlipRequest? FindFlipAheadCandidateLocked(int handle) + { + FlipRequest? oldest = null; + foreach (var request in _flipRequests.Values) + { + if (request.Handle == handle && request.State != FlipRequestState.Completed && + (oldest is null || request.RequestId < oldest.RequestId)) + { + oldest = request; + } + } + + if (oldest is null || !oldest.AheadRecorded || !oldest.GpuQueued || oldest.State != FlipRequestState.Reserved) + { + return null; + } + + var previous = oldest.AheadPrevious; + if (previous is not null && previous.Outcome != FlipOutcome.Cancelled && + !(previous.State == FlipRequestState.Completed && previous.GpuCompleted && previous.EventsTriggered)) + { + return null; + } + + return oldest; + } + + // At most one line every two seconds, and only while flips go ahead. + private static void ReportFlipAhead() + { + var now = Stopwatch.GetTimestamp(); + var last = Interlocked.Read(ref _flipAheadReportedAt); + if (now - last < 2 * Stopwatch.Frequency || + Interlocked.CompareExchange(ref _flipAheadReportedAt, now, last) != last) + { + return; + } + + var atRecord = Interlocked.Exchange(ref _flipAheadAtRecord, 0); + var atPrevious = Interlocked.Exchange(ref _flipAheadAtPrevious, 0); + var late = Interlocked.Exchange(ref _flipAheadLateNotices, 0); + var leadTicks = Interlocked.Exchange(ref _flipAheadLeadTicks, 0); + var leadCount = Interlocked.Exchange(ref _flipAheadLeadCount, 0); + if (last == 0 || atRecord + atPrevious + late == 0) + { + return; + } + + var leadMs = leadCount == 0 ? 0 : leadTicks * 1000.0 / Stopwatch.Frequency / leadCount; + Console.Error.WriteLine( + $"[VIDEOOUT][FLIP-AHEAD] ahead_at_record={atRecord} ahead_at_previous_completion={atPrevious} " + + $"late_notices={late} lead_ms_mean={leadMs.ToString("F1", System.Globalization.CultureInfo.InvariantCulture)} " + + $"lead_samples={leadCount} seconds={((now - last) / (double)Stopwatch.Frequency).ToString("F1", System.Globalization.CultureInfo.InvariantCulture)}"); + } + + internal readonly record struct FlipAheadCounters(long AtRecord, long AtPrevious, long LateNotices, long LeadSamples); + + internal static FlipAheadCounters PeekFlipAheadCountersForTests() => new( + Interlocked.Read(ref _flipAheadAtRecord), + Interlocked.Read(ref _flipAheadAtPrevious), + Interlocked.Read(ref _flipAheadLateNotices), + Interlocked.Read(ref _flipAheadLeadCount)); + + internal static void ResetFlipAheadForTests(bool enabled) + { + lock (_stateGate) + { + _lastGpuQueuedFlip.Clear(); + } + + FlipAheadEnabled = enabled; + // Keep the report from consuming the counters while a test reads them. + Interlocked.Exchange(ref _flipAheadReportedAt, Stopwatch.GetTimestamp() + 3600 * Stopwatch.Frequency); + Interlocked.Exchange(ref _flipAheadAtRecord, 0); + Interlocked.Exchange(ref _flipAheadAtPrevious, 0); + Interlocked.Exchange(ref _flipAheadLateNotices, 0); + Interlocked.Exchange(ref _flipAheadLeadTicks, 0); + Interlocked.Exchange(ref _flipAheadLeadCount, 0); + } + + internal static int GetGpuQueueCountForTests(int handle) + { + lock (_stateGate) + { + return _ports.TryGetValue(handle, out var port) ? port.GpuQueueCount : -1; + } + } +} diff --git a/src/SharpEmu.Libs/VideoOut/VideoOutExports.FlipRequests.cs b/src/SharpEmu.Libs/VideoOut/VideoOutExports.FlipRequests.cs index a2d0c0fc3..9a5484e92 100644 --- a/src/SharpEmu.Libs/VideoOut/VideoOutExports.FlipRequests.cs +++ b/src/SharpEmu.Libs/VideoOut/VideoOutExports.FlipRequests.cs @@ -47,6 +47,18 @@ private sealed class FlipRequest public int FlipEventCount; public FlipRequestState State; public FlipOutcome Outcome; + + // SHARPEMU_FLIP_AHEAD (see VideoOutExports.FlipAhead.cs). The GPU host recorded the flip, + // committed the buffer carrying it and handed the presenter a copy of its frame. + public bool AheadRecorded; + // The GPU really finished the submission carrying the flip (CompleteFlipOnGpu ran). + public bool GpuCompleted; + // The flip events of the published flip have been triggered. + public bool EventsTriggered; + // When the guest-visible completion was published ahead of the GPU; zero otherwise. + public long AheadPublishedAt; + // The GPU-queued flip reserved before this one on the same handle, until this one is published. + public FlipRequest? AheadPrevious; } private static readonly Dictionary _flipRequests = new(); @@ -146,6 +158,10 @@ internal static int TryReserveFlipRequest( } _flipRequests.Add(request.RequestId, request); + if (gpuQueued && FlipAheadEnabled) + { + NoteGpuQueuedFlipLocked(request); + } } if (bufferIndex >= 0 && TryGetDisplayBufferInfo(handle, bufferIndex, out var displayBuffer)) @@ -237,10 +253,11 @@ internal static void CompleteFlip(ulong requestId) } ReleaseGpuQueueSlotLocked(request); + request.GpuCompleted = true; PublishFlipLocked(request); } - TriggerFlipEvents(request); + TriggerPublishedFlip(request); } /// @@ -253,25 +270,49 @@ internal static void CompleteFlip(ulong requestId) internal static void CompleteFlipOnGpu(ulong requestId) { FlipRequest request; + var aheadAlready = false; lock (_stateGate) { - if (!_flipRequests.TryGetValue(requestId, out request!) || request.State != FlipRequestState.Reserved) + if (!_flipRequests.TryGetValue(requestId, out request!)) { return; } - ReleaseGpuQueueSlotLocked(request); - if (request.Outcome == FlipOutcome.Pending) + if (request.State != FlipRequestState.Reserved) { - request.State = FlipRequestState.GpuDone; - Monitor.PulseAll(_stateGate); - return; + // A flip published ahead still owes its GPU-side state; the guest was told already, + // so neither the counters nor the events are published again. + if (request.AheadPublishedAt == 0 || request.GpuCompleted) + { + return; + } + + CompleteAheadFlipOnGpuLocked(request); + aheadAlready = true; + } + else + { + ReleaseGpuQueueSlotLocked(request); + request.GpuCompleted = true; + if (request.Outcome == FlipOutcome.Pending) + { + request.State = FlipRequestState.GpuDone; + Monitor.PulseAll(_stateGate); + return; + } + + PublishFlipLocked(request); } + } - PublishFlipLocked(request); + if (aheadAlready) + { + // The flip after this one may be waiting for this real completion. + DrainFlipAhead(request.Handle, noticed: 0); + return; } - TriggerFlipEvents(request); + TriggerPublishedFlip(request); } // Caller holds the state gate. The GPU no longer holds the request. @@ -288,6 +329,7 @@ private static void ReleaseGpuQueueSlotLocked(FlipRequest request) private static void PublishFlipLocked(FlipRequest request) { request.State = FlipRequestState.Completed; + request.AheadPrevious = null; if (_ports.TryGetValue(request.Handle, out var port)) { port.FlipCount++; @@ -385,7 +427,7 @@ private static bool SetFlipOutcome(ulong requestId, FlipOutcome outcome) if (published is not null) { - TriggerFlipEvents(published); + TriggerPublishedFlip(published); } return true; @@ -394,7 +436,9 @@ private static bool SetFlipOutcome(ulong requestId, FlipOutcome outcome) // Both responsibilities are done: the retirement ran and the presenter released the frame. private static void RemoveIfFinishedLocked(FlipRequest request) { - if (request.State == FlipRequestState.Completed && request.Outcome != FlipOutcome.Pending) + // A flip published ahead of the GPU stays until its real completion has released its GPU slot. + if (request.State == FlipRequestState.Completed && request.Outcome != FlipOutcome.Pending && + (request.AheadPublishedAt == 0 || request.GpuCompleted)) { _flipRequests.Remove(request.RequestId); } @@ -461,6 +505,14 @@ private static void CancelFlipLocked(FlipRequest request) request.FlipEvents = null; } } + else if (request.AheadPublishedAt != 0 && !request.GpuCompleted && request.GpuQueued && + _ports.TryGetValue(request.Handle, out var aheadPort)) + { + // Published ahead of the GPU: the guest was told, the GPU slot was still held. + aheadPort.GpuQueueCount = Math.Max(0, aheadPort.GpuQueueCount - 1); + } + + request.AheadPrevious = null; // Completed requests leave event-array ownership with the completion caller. request.Outcome = FlipOutcome.Cancelled; _flipRequests.Remove(request.RequestId); diff --git a/tests/SharpEmu.Libs.Tests/Gpu/Split/SplitHookTests.cs b/tests/SharpEmu.Libs.Tests/Gpu/Split/SplitHookTests.cs index e1d52c3f9..d9a34ea7e 100644 --- a/tests/SharpEmu.Libs.Tests/Gpu/Split/SplitHookTests.cs +++ b/tests/SharpEmu.Libs.Tests/Gpu/Split/SplitHookTests.cs @@ -310,6 +310,8 @@ public long NextFlipPresentTimestamp(ulong requestId, long timestamp) public void CompleteFlipOnGpu(ulong requestId) => Calls.Add($"gpu {requestId}"); + public void NoteFlipRecorded(ulong requestId) => Calls.Add($"recorded {requestId}"); + public void DiscardFlip(ulong requestId) => Calls.Add($"discard {requestId}"); public string GetApplicationTitleId() diff --git a/tests/SharpEmu.Libs.Tests/VideoOut/VideoOutFlipAheadTests.cs b/tests/SharpEmu.Libs.Tests/VideoOut/VideoOutFlipAheadTests.cs new file mode 100644 index 000000000..8b806cb8f --- /dev/null +++ b/tests/SharpEmu.Libs.Tests/VideoOut/VideoOutFlipAheadTests.cs @@ -0,0 +1,292 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using System.Buffers.Binary; +using System.Diagnostics; +using SharpEmu.HLE; +using SharpEmu.Libs.Kernel; +using SharpEmu.Libs.Tests.Gpu.Scheduling; +using SharpEmu.Libs.VideoOut; +using Xunit; + +namespace SharpEmu.Libs.Tests.VideoOut; + +// SHARPEMU_FLIP_AHEAD: a flip the GPU host recorded (NoteFlipRecorded) is published to the guest +// once the flip before it really completed on the GPU; the request stays for the pacer and its +// real completion releases the GPU slot without publishing again. +[Collection(SchedulingStateCollection.Name)] +public sealed class VideoOutFlipAheadTests : IDisposable +{ + private const ulong MemoryBase = 0x1_0000_0000; + private const ulong StatusAddress = MemoryBase + 0x100; + private const ulong ScratchAddress = MemoryBase + 0x200; + private const ulong EventAddress = MemoryBase + 0x300; + private const ulong OutCountAddress = MemoryBase + 0x400; + private const ulong TimeoutAddress = MemoryBase + 0x480; + private const int TimedOut = unchecked((int)0x8002003C); + + private readonly FakeCpuMemory _memory = new(MemoryBase, 0x1000); + private readonly CpuContext _context; + private readonly int _handle; + private ulong _queue; + + public VideoOutFlipAheadTests() + { + _context = new CpuContext(_memory, Generation.Gen5); + _context[CpuRegister.Rdi] = 0; + _context[CpuRegister.Rsi] = 0; + _context[CpuRegister.Rdx] = 0; + _context[CpuRegister.Rcx] = 0; + _handle = VideoOutExports.VideoOutOpen(_context); + Assert.True(_handle > 0); + VideoOutExports.ResetFlipAheadForTests(enabled: true); + } + + public void Dispose() + { + if (_queue != 0) + { + _context[CpuRegister.Rdi] = _queue; + _ = KernelEventQueueCompatExports.KernelDeleteEqueue(_context); + } + + _context[CpuRegister.Rdi] = unchecked((ulong)_handle); + _ = VideoOutExports.VideoOutClose(_context); + VideoOutExports.ResetFlipAheadForTests(enabled: false); + } + + private ulong Reserve(long flipArg, bool gpuQueued = true) + { + Assert.Equal(0, VideoOutExports.TryReserveFlipRequest(_handle, -1, 2, flipArg, gpuQueued, out var requestId)); + return requestId; + } + + private (ulong Count, long FlipArg, int GpuQueue, int Pending) Status() + { + _context[CpuRegister.Rdi] = unchecked((ulong)_handle); + _context[CpuRegister.Rsi] = StatusAddress; + Assert.Equal(0, VideoOutExports.VideoOutGetFlipStatus(_context)); + Span status = stackalloc byte[0x40]; + Assert.True(_memory.TryRead(StatusAddress, status)); + return (BinaryPrimitives.ReadUInt64LittleEndian(status), + BinaryPrimitives.ReadInt64LittleEndian(status[0x18..]), + BinaryPrimitives.ReadInt32LittleEndian(status[0x30..]), + BinaryPrimitives.ReadInt32LittleEndian(status[0x34..])); + } + + private void AddFlipEvent() + { + _context[CpuRegister.Rdi] = ScratchAddress; + _context[CpuRegister.Rsi] = 0; + Assert.Equal(0, KernelEventQueueCompatExports.KernelCreateEqueue(_context)); + Assert.True(_context.TryReadUInt64(ScratchAddress, out _queue)); + _context[CpuRegister.Rdi] = _queue; + _context[CpuRegister.Rsi] = unchecked((ulong)_handle); + _context[CpuRegister.Rdx] = 0x55; + Assert.Equal(0, VideoOutExports.VideoOutAddFlipEvent(_context)); + } + + private int WaitOne(uint timeoutUsec) + { + Assert.True(_memory.TryWrite(TimeoutAddress, BitConverter.GetBytes(timeoutUsec))); + _context[CpuRegister.Rdi] = _queue; + _context[CpuRegister.Rsi] = EventAddress; + _context[CpuRegister.Rdx] = 1; + _context[CpuRegister.Rcx] = OutCountAddress; + _context[CpuRegister.R8] = TimeoutAddress; + return KernelEventQueueCompatExports.KernelWaitEqueue(_context); + } + + [Fact] + public void AheadPublicationPublishesOnceAndTheRealCompletionOnlyReleasesTheGpuSlot() + { + AddFlipEvent(); + var before = Status(); + var request = Reserve(101); + Assert.Equal(before.GpuQueue + 1, Status().GpuQueue); + + VideoOutExports.NoteFlipRecorded(request); + var ahead = Status(); + Assert.Equal(before.Count + 1, ahead.Count); + Assert.Equal(101, ahead.FlipArg); + Assert.Equal(before.Pending, ahead.Pending); + // The GPU still holds the flip. + Assert.Equal(before.GpuQueue + 1, ahead.GpuQueue); + Assert.Equal(0, WaitOne(100_000)); + // The pacer still has the request. + Assert.True(VideoOutExports.IsFlipPresentationPending(request)); + Assert.Equal(VideoOutExports.FlipOutcome.Pending, VideoOutExports.GetFlipOutcomeForTests(request)); + + VideoOutExports.CompleteFlipOnGpu(request); + VideoOutExports.CompleteFlipOnGpu(request); + var done = Status(); + Assert.Equal(ahead.Count, done.Count); + Assert.Equal(before.GpuQueue, done.GpuQueue); + Assert.Equal(TimedOut, WaitOne(1_000)); + Assert.True(VideoOutExports.CanPresentFlip(request, Stopwatch.GetTimestamp())); + + VideoOutExports.MarkFlipPresented(request); + Assert.Equal(ahead.Count, Status().Count); + Assert.Equal(TimedOut, WaitOne(1_000)); + Assert.Null(VideoOutExports.GetFlipOutcomeForTests(request)); + + var counters = VideoOutExports.PeekFlipAheadCountersForTests(); + Assert.Equal(1, counters.AtRecord); + Assert.Equal(0, counters.AtPrevious); + Assert.Equal(1, counters.LeadSamples); + } + + [Fact] + public void TheNextFlipWaitsForThePreviousRealCompletion() + { + var before = Status(); + var first = Reserve(111); + var second = Reserve(112); + + VideoOutExports.NoteFlipRecorded(first); + VideoOutExports.NoteFlipRecorded(second); + Assert.Equal(before.Count + 1, Status().Count); + Assert.Equal(111, Status().FlipArg); + + VideoOutExports.CompleteFlipOnGpu(first); + Assert.Equal(before.Count + 2, Status().Count); + Assert.Equal(112, Status().FlipArg); + + var counters = VideoOutExports.PeekFlipAheadCountersForTests(); + Assert.Equal(1, counters.AtRecord); + Assert.Equal(1, counters.AtPrevious); + + VideoOutExports.CompleteFlipOnGpu(second); + VideoOutExports.MarkFlipPresented(first); + VideoOutExports.MarkFlipPresented(second); + Assert.Equal(before.Count + 2, Status().Count); + Assert.Equal(before.GpuQueue, Status().GpuQueue); + Assert.Equal(before.Pending, Status().Pending); + Assert.Null(VideoOutExports.GetFlipOutcomeForTests(first)); + Assert.Null(VideoOutExports.GetFlipOutcomeForTests(second)); + } + + // A flip whose predecessor was not published ahead goes no later than today: when the + // predecessor is shown, never before it. + [Fact] + public void AFlipIsNeverPublishedBeforeTheOneBeforeIt() + { + var before = Status(); + var first = Reserve(121); + var second = Reserve(122); + + VideoOutExports.NoteFlipRecorded(second); + Assert.Equal(before.Count, Status().Count); + + VideoOutExports.CompleteFlipOnGpu(first); + Assert.Equal(before.Count, Status().Count); + + VideoOutExports.MarkFlipPresented(first); + Assert.Equal(before.Count + 2, Status().Count); + Assert.Equal(122, Status().FlipArg); + + VideoOutExports.CompleteFlipOnGpu(second); + VideoOutExports.MarkFlipPresented(second); + Assert.Equal(before.Count + 2, Status().Count); + Assert.Equal(before.GpuQueue, Status().GpuQueue); + } + + [Fact] + public void ThePacerStillPresentsAFlipPublishedAheadInOrder() + { + var before = Status(); + var first = Reserve(131); + VideoOutExports.NoteFlipRecorded(first); + var second = Reserve(132); + // The guest's next flip arrives before the first was shown; both stay with the pacer. + Assert.False(VideoOutExports.IsFlipDone(_handle, -1)); + Assert.True(VideoOutExports.IsFlipPresentationPending(first)); + Assert.True(VideoOutExports.IsFlipPresentationPending(second)); + + // Shown before its real completion: the request outlives the presentation until then. + VideoOutExports.MarkFlipPresented(first); + Assert.Equal(VideoOutExports.FlipOutcome.Presented, VideoOutExports.GetFlipOutcomeForTests(first)); + Assert.Equal(before.GpuQueue + 2, Status().GpuQueue); + VideoOutExports.CompleteFlipOnGpu(first); + Assert.Null(VideoOutExports.GetFlipOutcomeForTests(first)); + Assert.Equal(before.GpuQueue + 1, Status().GpuQueue); + + VideoOutExports.NoteFlipRecorded(second); + Assert.Equal(before.Count + 2, Status().Count); + VideoOutExports.CompleteFlipOnGpu(second); + VideoOutExports.DiscardFlip(second); + Assert.Equal(before.Count + 2, Status().Count); + Assert.True(VideoOutExports.IsFlipDone(_handle, -1)); + Assert.Null(VideoOutExports.GetFlipOutcomeForTests(second)); + Assert.Equal(before.GpuQueue, Status().GpuQueue); + Assert.Equal(before.Pending, Status().Pending); + } + + [Fact] + public void ALateNoticeAndCancelledOrCpuFlipsKeepTodaysTiming() + { + var before = Status(); + + // Real completion first: the notice is ignored and presentation publishes. + var late = Reserve(141); + VideoOutExports.CompleteFlipOnGpu(late); + VideoOutExports.NoteFlipRecorded(late); + Assert.Equal(before.Count, Status().Count); + VideoOutExports.MarkFlipPresented(late); + Assert.Equal(before.Count + 1, Status().Count); + + // Cancelled: nothing is published. + var cancelled = Reserve(142); + VideoOutExports.CancelFlip(cancelled); + VideoOutExports.NoteFlipRecorded(cancelled); + Assert.Equal(before.Count + 1, Status().Count); + + // A CPU flip is not GPU-queued: a notice for it is ignored. + var cpu = Reserve(143, gpuQueued: false); + VideoOutExports.NoteFlipRecorded(cpu); + Assert.Equal(before.Count + 1, Status().Count); + + // An unpublished CPU flip before a GPU flip holds the GPU flip back. + var gpu = Reserve(144); + VideoOutExports.NoteFlipRecorded(gpu); + Assert.Equal(before.Count + 1, Status().Count); + VideoOutExports.CompleteFlip(cpu); + Assert.Equal(before.Count + 3, Status().Count); + Assert.Equal(144, Status().FlipArg); + VideoOutExports.MarkFlipPresented(cpu); + + // Cancelling a flip published ahead gives its GPU slot back. + Assert.Equal(before.GpuQueue + 1, Status().GpuQueue); + VideoOutExports.CancelFlip(gpu); + Assert.Equal(before.GpuQueue, Status().GpuQueue); + Assert.Equal(before.Pending, Status().Pending); + Assert.Equal(before.Count + 3, Status().Count); + + Assert.Equal(3, VideoOutExports.PeekFlipAheadCountersForTests().LateNotices); + } + + [Fact] + public void WithTheSwitchOffTheNoticeChangesNothing() + { + VideoOutExports.ResetFlipAheadForTests(enabled: false); + AddFlipEvent(); + var before = Status(); + var request = Reserve(151); + + VideoOutExports.NoteFlipRecorded(request); + Assert.Equal(before.Count, Status().Count); + Assert.Equal(TimedOut, WaitOne(1_000)); + + VideoOutExports.CompleteFlipOnGpu(request); + Assert.Equal(before.Count, Status().Count); + Assert.Equal(before.GpuQueue, Status().GpuQueue); + Assert.Equal(before.Pending + 1, Status().Pending); + + VideoOutExports.MarkFlipPresented(request); + Assert.Equal(before.Count + 1, Status().Count); + Assert.Equal(before.Pending, Status().Pending); + Assert.Equal(0, WaitOne(100_000)); + Assert.Null(VideoOutExports.GetFlipOutcomeForTests(request)); + Assert.Equal(default, VideoOutExports.PeekFlipAheadCountersForTests()); + } +} From 530a8d58323961fb44b112255c22deaf57b5cf94 Mon Sep 17 00:00:00 2001 From: kuba Date: Mon, 16 Nov 2026 01:24:31 +0000 Subject: [PATCH 110/178] [Metal] Flip ahead: hand the presenter a stream-ordered copy of the flip's frame With SHARPEMU_FLIP_AHEAD=1 a GPU flip's presented view is blitted, in the stream's open command buffer at the flip and fenced like every encoder, into a presenter-owned texture of the same format, size and swizzle (MetalFlipCopyPool, up to 7). Without it the presenter samples the display image itself until the next promotion, so a guest told of a flip early could draw its next frame into the frame on screen. A pool texture is reused only when it is not presented, queued or being encoded and the last presentation that sampled it has completed. A refused copy (pool exhausted, not a single-level 2D texture, multisampled, creation or encoder failure) is logged once, counted, and the frame goes live as today. The recorded notice is sent after the flip's completion is queued, only for a copied frame whose previous frame was a copy too. Interrupts and labels stay at the real completion. [METAL-PRESENT] gains flip_copies, flip_copy_refused, flip_copy_pool, flip_copy_pool_high and flip_copy_mb while the switch is on. --- docs/macos/configuration.md | 1 + .../V2/MetalCommandStream.cs | 20 +- .../V2/MetalFlipCopyPool.cs | 298 ++++++++++++++++++ .../V2/MetalRenderHost.FlipCopy.cs | 153 +++++++++ .../V2/MetalV2Diagnostics.cs | 5 + .../SharpEmu.Gpu.Metal/V2/MetalV2Presenter.cs | 50 ++- .../MetalFlipCopyTests.cs | 104 ++++++ 7 files changed, 626 insertions(+), 5 deletions(-) create mode 100644 src/graphics/SharpEmu.Gpu.Metal/V2/MetalFlipCopyPool.cs create mode 100644 src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.FlipCopy.cs create mode 100644 tests/SharpEmu.Gpu.Metal.Tests/MetalFlipCopyTests.cs diff --git a/docs/macos/configuration.md b/docs/macos/configuration.md index 8920bbf6c..d22936e7f 100644 --- a/docs/macos/configuration.md +++ b/docs/macos/configuration.md @@ -41,6 +41,7 @@ them for measurements or to isolate a problem. | `SHARPEMU_GUEST_BACKING_SHAREABLE` | unset | `1` makes the guest backing shareable with another process, and keeps a shared table and log of guest views. This is groundwork for the two-process split (`SHARPEMU_GPU_PROCESS=1` sets it too). See [Guest memory for the two-process split](split-shared-memory.md). | | `SHARPEMU_HLE_FAST_PATH` | on | `0` disables the native stubs for `pthread_self` and `pthread_getspecific`. They are also off while import or pthread tracing is active. | | `SHARPEMU_STALL_WATCHDOG_SECONDS` | `20` | Seconds without import progress before the stall watchdog acts. `0` disables it. | +| `SHARPEMU_FLIP_AHEAD` | off | Experimental. `1` tells the game a GPU flip is done once the flip is recorded and the flip before it has really finished on the GPU, instead of when the frame is shown, so the game can build its next frame while the GPU draws this one (at most one flip ahead). Each such frame is copied in the GPU stream into a presenter-owned texture (up to 7 textures the size of the display buffer), so what is shown is unchanged; a flip whose frame cannot be copied keeps the usual timing, and the refusal is logged once. Pacing, interrupts and labels are unchanged. Counters: `[VIDEOOUT][FLIP-AHEAD]` and the `flip_copy*` fields of `[METAL-PRESENT]`. | ## Metal memory diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalCommandStream.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalCommandStream.cs index 4ebfb6185..e617bdd1d 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalCommandStream.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalCommandStream.cs @@ -900,6 +900,7 @@ public void RecordEndOfPipe(in EndOfPipeWrite write) VideoOutBackendServices.CompleteFlipOnGpu(requestId); MetalV2Presenter.SignalFlipPacer(); }); + NoteFlipRecordedIfEligible(requestId); break; case EndOfPipeWriteKind.FlipWithInterruptWriteBack32: NoteFlipSerialForEarlyLabels(); @@ -910,6 +911,7 @@ public void RecordEndOfPipe(in EndOfPipeWrite write) MetalV2Presenter.SignalFlipPacer(); TriggerInterrupt(eventId, 0); }); + NoteFlipRecordedIfEligible(requestId); break; case EndOfPipeWriteKind.GdsWrite32: RecordEndOfPipeGdsWrite(in write); @@ -2916,7 +2918,7 @@ public ulong PrepareFlip(int handle, int index, int flipMode, long flipArgument) try { - CaptureFlip(handle, index, requestId, flipMode, flipArgument); + CaptureFlip(handle, index, requestId, flipMode, flipArgument, gpuQueued: true); } catch { @@ -2937,7 +2939,7 @@ public void PrepareCpuFlip(int handle, int index, ulong requestId) } DrainDraws(); - CaptureFlip(handle, index, requestId, flipMode: 0, flipArg: 0); + CaptureFlip(handle, index, requestId, flipMode: 0, flipArg: 0, gpuQueued: false); } // The display surface is a cached image like any other; the flip hands its @@ -2950,7 +2952,7 @@ public void PrepareCpuFlip(int handle, int index, ulong requestId) internal static long FlipsDiscarded; internal static long FlipsPublished; - private void CaptureFlip(int handle, int index, ulong requestId, int flipMode, long flipArg) + private void CaptureFlip(int handle, int index, ulong requestId, int flipMode, long flipArg, bool gpuQueued) { Interlocked.Increment(ref _flipAttempts); Interlocked.Increment(ref FlipsCaptured); @@ -3014,6 +3016,11 @@ private void CaptureFlip(int handle, int index, ulong requestId, int flipMode, l if (_dumpThisFlip) { DumpTexture(image.Texture, "flip-after-refresh"); } SampleFlipLuma(image.Texture); var texture = PresentationViewOf(imageIdentifier, image, in request); + // SHARPEMU_FLIP_AHEAD: the presenter gets a copy taken here, in the stream, instead of + // the display image the guest may render into once it hears of the flip. + var presented = texture; + var copied = MetalV2Diagnostics.FlipAhead && gpuQueued && _flipTarget is not null && texture != 0 && + TryCopyFlipFrame(texture, out presented); var serial = SubmissionSerial; FlushCommandBuffer(PassEndCause.Present); if (_flipTarget is null || texture == 0) @@ -3038,12 +3045,17 @@ private void CaptureFlip(int handle, int index, ulong requestId, int flipMode, l Interlocked.Increment(ref FlipsPublished); ReportFlipSurface(in displayBuffer, in request, imageIdentifier, image, texture); _flipTarget.PublishGuestFrame( - texture, + presented, Math.Max(displayBuffer.Width, 1), Math.Max(displayBuffer.Height, 1), requestId, serial, VideoOutBackendServices.IsHdrPixelFormat(displayBuffer.PixelFormat)); + if (MetalV2Diagnostics.FlipAhead) + { + NoteFlipFrameCaptured(requestId, copied); + } + VideoOutBackendServices.TraceGpuFlip( _memory, handle, index, flipMode, flipArg, displayBuffer.Address, requestId); // The shared phase profile measures the whole draw translation path, which v2 diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalFlipCopyPool.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalFlipCopyPool.cs new file mode 100644 index 000000000..29123fd17 --- /dev/null +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalFlipCopyPool.cs @@ -0,0 +1,298 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using System.Runtime.InteropServices; + +namespace SharpEmu.Gpu.Metal.V2; + +/// +/// SHARPEMU_FLIP_AHEAD: the presenter-owned textures a GPU flip's frame is copied into, in the +/// stream at the flip (MetalRenderHost.FlipCopy.cs). Without the copy the presenter samples the +/// display image's own texture until the next frame replaces it, so a guest told of flip N before +/// N is shown could render the next frame into the buffer still on screen. +/// A texture goes back to the pool only once the presenter can no longer read it: it is not +/// the presented frame, not queued, not being encoded by a presentation, and the last +/// presentation command buffer that sampled it has completed. +/// +internal static partial class MetalFlipCopyPool +{ + // The frame on screen, the frames the presenter queues (MaxPendingFrames = 4), the one the + // stream is writing, and one whose last presentation may still be on the GPU. + internal const int Capacity = 7; + + internal enum Refusal + { + PoolExhausted, + TextureType, + Multisampled, + Layout, + TextureCreate, + Encoder, + Count, + } + + private static readonly string[] RefusalNames = + ["pool_exhausted", "texture_type", "multisampled", "layout", "texture_create", "encoder"]; + + private sealed class Entry + { + public nint Texture; + public nint Presented; + public ulong PixelFormat; + public uint Width; + public uint Height; + public MtlTextureSwizzleChannels Swizzle; + public nint LastSampledBy; + } + + private static readonly object _gate = new(); + private static readonly List _entries = new(); + private static readonly long[] _refusals = new long[(int)Refusal.Count]; + private static long _copies; + private static int _highWater; + private static ulong _copyBytes; + + private static readonly nint SelSwizzle = MetalNative.Selector("swizzle"); + private static readonly nint SelStatus = MetalNative.Selector("status"); + private static readonly nint SelRetain = MetalNative.Selector("retain"); + private static readonly nint SelRelease = MetalNative.Selector("release"); + private static readonly nint SelSetUsage = MetalNative.Selector("setUsage:"); + private static readonly nint SelSetStorageMode = MetalNative.Selector("setStorageMode:"); + private static readonly nint SelNewTexture = MetalNative.Selector("newTextureWithDescriptor:"); + private static readonly nint SelNewSwizzledView = + MetalNative.Selector("newTextureViewWithPixelFormat:textureType:levels:slices:swizzle:"); + + // MTLCommandBufferStatusCompleted; Error (5) is past it too. + private const nuint CommandBufferCompleted = 4; + + [LibraryImport("/usr/lib/libobjc.A.dylib", EntryPoint = "objc_msgSend")] + private static partial MtlTextureSwizzleChannels SendSwizzle(nint receiver, nint selector); + + /// The swizzle the presenter samples a texture through. + internal static MtlTextureSwizzleChannels SwizzleOf(nint texture) => SendSwizzle(texture, SelSwizzle); + + /// + /// A texture of this shape the presenter cannot read any more, or a new one. destination is + /// what the copy writes, presented what the presenter is handed (the same texture, or a view + /// of it with the source's swizzle). + /// + internal static bool TryAcquire(nint device, ulong pixelFormat, uint width, uint height, + MtlTextureSwizzleChannels swizzle, out nint destination, out nint presented, out Refusal refusal) + { + destination = 0; + presented = 0; + refusal = Refusal.Count; + lock (_gate) + { + Entry? free = null; + Entry? reclaim = null; + var held = 0; + foreach (var entry in _entries) + { + if (IsReadableLocked(entry)) + { + held++; + continue; + } + + var matches = entry.PixelFormat == pixelFormat && entry.Width == width && entry.Height == height && + SameSwizzle(entry.Swizzle, swizzle); + if (matches) + { + free ??= entry; + } + else + { + reclaim ??= entry; + } + } + + if (free is null) + { + if (_entries.Count >= Capacity) + { + if (reclaim is null) + { + refusal = Refusal.PoolExhausted; + return false; + } + + ReleaseLocked(reclaim); + _entries.Remove(reclaim); + } + + free = Create(device, pixelFormat, width, height, swizzle); + if (free is null) + { + refusal = Refusal.TextureCreate; + return false; + } + + _entries.Add(free); + } + + _highWater = Math.Max(_highWater, held + 1); + destination = free.Texture; + presented = free.Presented; + return true; + } + } + + internal static void NoteCopy(ulong bytes) + { + Interlocked.Increment(ref _copies); + Interlocked.Exchange(ref _copyBytes, bytes); + } + + internal static void NoteRefusal(Refusal refusal) => Interlocked.Increment(ref _refusals[(int)refusal]); + + internal static string RefusalName(Refusal refusal) => RefusalNames[(int)refusal]; + + /// A presentation command buffer, now committed, sampled this texture. + internal static void NoteSampled(nint texture, nint commandBuffer) + { + if (texture == 0 || commandBuffer == 0) + { + return; + } + + lock (_gate) + { + foreach (var entry in _entries) + { + if (entry.Presented != texture) + { + continue; + } + + MetalNative.SendVoid(commandBuffer, SelRetain); + if (entry.LastSampledBy != 0) + { + MetalNative.SendVoid(entry.LastSampledBy, SelRelease); + } + + entry.LastSampledBy = commandBuffer; + return; + } + } + } + + /// Copies, refusals by reason, the most textures the presenter could read at once plus the one written. + internal static string TakeReport() + { + var copies = Interlocked.Exchange(ref _copies, 0); + var refusals = new System.Text.StringBuilder(); + for (var index = 0; index < (int)Refusal.Count; index++) + { + var count = Interlocked.Exchange(ref _refusals[index], 0); + if (count != 0) + { + refusals.Append(refusals.Length == 0 ? "" : ",").Append(RefusalNames[index]).Append(':').Append(count); + } + } + + int pool; + int high; + lock (_gate) + { + pool = _entries.Count; + high = _highWater; + } + + return $"flip_copies={copies} flip_copy_refused={(refusals.Length == 0 ? "0" : refusals.ToString())} " + + $"flip_copy_pool={pool} flip_copy_pool_high={high} flip_copy_mb={Interlocked.Read(ref _copyBytes) / (1024.0 * 1024.0):F1}"; + } + + // Caller holds the gate. + private static bool IsReadableLocked(Entry entry) + { + if (MetalV2Presenter.IsFlipCopyHeld(entry.Presented)) + { + return true; + } + + if (entry.LastSampledBy == 0) + { + return false; + } + + if (MetalV2Native.SendValue(entry.LastSampledBy, SelStatus) < CommandBufferCompleted) + { + return true; + } + + MetalNative.SendVoid(entry.LastSampledBy, SelRelease); + entry.LastSampledBy = 0; + return false; + } + + private static bool SameSwizzle(MtlTextureSwizzleChannels left, MtlTextureSwizzleChannels right) => + left.Red == right.Red && left.Green == right.Green && left.Blue == right.Blue && left.Alpha == right.Alpha; + + // MTLTextureSwizzleRed..Alpha are 2..5. + private static bool IsIdentity(MtlTextureSwizzleChannels swizzle) => + swizzle.Red == 2 && swizzle.Green == 3 && swizzle.Blue == 4 && swizzle.Alpha == 5; + + private static Entry? Create(nint device, ulong pixelFormat, uint width, uint height, MtlTextureSwizzleChannels swizzle) + { + var descriptor = MetalNative.SendTextureDescriptor( + MetalNative.Class("MTLTextureDescriptor"), + MetalNative.Selector("texture2DDescriptorWithPixelFormat:width:height:mipmapped:"), + (nuint)pixelFormat, + width, + height, + mipmapped: false); + if (descriptor == 0) + { + return null; + } + + var identity = IsIdentity(swizzle); + MetalV2Native.SendVoidValue(descriptor, SelSetUsage, + (nuint)(Mtl.TextureUsageShaderRead | (identity ? 0 : Mtl.TextureUsagePixelFormatView))); + MetalV2Native.SendVoidValue(descriptor, SelSetStorageMode, Mtl.StorageModePrivate); + var texture = MetalNative.Send(device, SelNewTexture, descriptor); + if (texture == 0) + { + return null; + } + + var presented = texture; + if (!identity) + { + presented = MetalV2Native.SendNewSwizzledTextureView( + texture, SelNewSwizzledView, (nuint)pixelFormat, (nuint)Mtl.TextureType2D, + new NsRange { Location = 0, Length = 1 }, new NsRange { Location = 0, Length = 1 }, swizzle); + if (presented == 0) + { + MetalNative.SendVoid(texture, SelRelease); + return null; + } + } + + return new Entry + { + Texture = texture, + Presented = presented, + PixelFormat = pixelFormat, + Width = width, + Height = height, + Swizzle = swizzle, + }; + } + + // Caller holds the gate; the entry is not readable. + private static void ReleaseLocked(Entry entry) + { + if (entry.Presented != entry.Texture) + { + MetalNative.SendVoid(entry.Presented, SelRelease); + } + + MetalNative.SendVoid(entry.Texture, SelRelease); + if (entry.LastSampledBy != 0) + { + MetalNative.SendVoid(entry.LastSampledBy, SelRelease); + } + } +} diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.FlipCopy.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.FlipCopy.cs new file mode 100644 index 000000000..db9f1ae83 --- /dev/null +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.FlipCopy.cs @@ -0,0 +1,153 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using SharpEmu.Libs.VideoOut; + +namespace SharpEmu.Gpu.Metal.V2; + +// SHARPEMU_FLIP_AHEAD: a GPU flip's frame is copied, in the stream at the flip, into a texture +// only the presenter reads (MetalFlipCopyPool), and video-out is told once the flip is recorded +// and the buffer carrying it committed, so it may publish the flip to the guest before the GPU +// finishes it (VideoOutExports.FlipAhead.cs). +internal sealed partial class MetalRenderHost +{ + private static readonly nint SelMipmapLevelCount = MetalNative.Selector("mipmapLevelCount"); + private static readonly nint SelArrayLength = MetalNative.Selector("arrayLength"); + private static readonly nint SelAllocatedSize = MetalNative.Selector("allocatedSize"); + + // The flips whose frame was copied while the frame before them was a copy too: the only + // ones whose recorded notice is sent. Worker thread; locked for the command thread's sake. + private readonly List _flipAheadEligible = new(); + + // Whether the last frame handed to the presenter was a copy. A frame handed over live (a CPU + // flip, a refused copy) is the display image itself, which stays on screen until the next + // frame is promoted: the guest must not hear of that next flip before it is shown. + private bool _previousFlipFrameCopied = true; + + // Copies the flip's presented view into a pool texture at this point of the stream. False + // (refused, logged once and counted) leaves the frame to be presented live, as today. + internal bool TryCopyFlipFrame(nint source, out nint presented) + { + presented = source; + var type = (ulong)MetalV2Native.SendValue(source, SelTextureType); + if (type != Mtl.TextureType2D) + { + return RefuseFlipCopy(MetalFlipCopyPool.Refusal.TextureType, $"type={type}"); + } + + var samples = (ulong)MetalV2Native.SendValue(source, SelSampleCount); + if (samples > 1) + { + return RefuseFlipCopy(MetalFlipCopyPool.Refusal.Multisampled, $"samples={samples}"); + } + + var levels = (ulong)MetalV2Native.SendValue(source, SelMipmapLevelCount); + var layers = (ulong)MetalV2Native.SendValue(source, SelArrayLength); + if (levels != 1 || layers != 1) + { + return RefuseFlipCopy(MetalFlipCopyPool.Refusal.Layout, $"levels={levels} layers={layers}"); + } + + var pixelFormat = (ulong)MetalV2Native.SendValue(source, SelPixelFormat); + var width = (uint)MetalV2Native.SendValue(source, SelWidth); + var height = (uint)MetalV2Native.SendValue(source, SelHeight); + var swizzle = MetalFlipCopyPool.SwizzleOf(source); + if (!MetalFlipCopyPool.TryAcquire(_device, pixelFormat, width, height, swizzle, + out var destination, out var copy, out var refusal)) + { + return RefuseFlipCopy(refusal, $"format={pixelFormat} {width}x{height} capacity={MetalFlipCopyPool.Capacity}"); + } + + EndEncoders(PassEndCause.Present); + var encoder = MetalNative.Send(EnsureCommandBuffer(), SelBlitEncoder); + MetalMemoryTelemetry.BlitEncoders.Add(); + if (encoder == 0) + { + return RefuseFlipCopy(MetalFlipCopyPool.Refusal.Encoder, $"format={pixelFormat} {width}x{height}"); + } + + // Fenced like every other encoder of the stream: after the passes that drew the frame, + // before anything recorded after the flip. + WaitForPreviousEncoder(encoder, render: false); + try + { + MetalNative.SendCopyTextureSlice( + encoder, + SelCopyTextureSlice, + source, + 0, + 0, + default, + new MtlSize { Width = width, Height = height, Depth = 1 }, + destination, + 0, + 0, + default); + } + finally + { + UpdateEncoderFence(encoder, render: false); + MetalNative.SendVoid(encoder, SelEndEncoding); + } + + NoteRecordedWork(); + MetalFlipCopyPool.NoteCopy((ulong)MetalV2Native.SendValue(destination, SelAllocatedSize)); + presented = copy; + return true; + } + + private static bool RefuseFlipCopy(MetalFlipCopyPool.Refusal refusal, string detail) + { + MetalFlipCopyPool.NoteRefusal(refusal); + MetalV2Diagnostics.WarnOnce( + $"flip-copy-{MetalFlipCopyPool.RefusalName(refusal)}", + $"Flip ahead: a flip's frame could not be copied for the presenter ({MetalFlipCopyPool.RefusalName(refusal)}: " + + $"{detail}); it is presented live and published to the guest at presentation, as without the switch."); + return false; + } + + // After the frame went to the presenter: copied flips whose previous frame was a copy too + // may be published ahead once their end-of-pipe completion is queued. + private void NoteFlipFrameCaptured(ulong requestId, bool copied) + { + var eligible = copied && _previousFlipFrameCopied; + _previousFlipFrameCopied = copied; + if (!eligible) + { + return; + } + + lock (_flipAheadEligible) + { + // A flip whose end-of-pipe write never reaches RecordEndOfPipe (a label published by + // the interpreter) keeps today's timing; its entry is dropped here. + if (_flipAheadEligible.Count >= 8) + { + _flipAheadEligible.RemoveAt(0); + } + + _flipAheadEligible.Add(requestId); + } + } + + // RecordEndOfPipe queued the flip's completion: the buffer carrying it is committed (or the + // completion already ran inline, in which case video-out ignores the late notice). + private void NoteFlipRecordedIfEligible(ulong requestId) + { + if (!MetalV2Diagnostics.FlipAhead || requestId == 0) + { + return; + } + + bool eligible; + lock (_flipAheadEligible) + { + eligible = _flipAheadEligible.Remove(requestId); + } + + if (eligible) + { + VideoOutBackendServices.NoteFlipRecorded(requestId); + } + } +} diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalV2Diagnostics.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalV2Diagnostics.cs index 4bd321076..d07215d3c 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalV2Diagnostics.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalV2Diagnostics.cs @@ -153,6 +153,11 @@ private static HashSet ParseHashes(string? text) public static readonly ulong[] EarlyLabelProbeAddresses = ParseEarlyLabelAddresses( Environment.GetEnvironmentVariable("SHARPEMU_METAL_V2_EARLY_LABEL_PROBE")); + // SHARPEMU_FLIP_AHEAD=1 (experimental, default off): a GPU flip hands the presenter a copy of its + // frame, blitted in the stream at the flip, and tells video-out the flip is recorded, so the guest + // may learn of it before the GPU finishes it (VideoOutExports.FlipAhead.cs, MetalFlipCopyPool). + public static readonly bool FlipAhead = Environment.GetEnvironmentVariable("SHARPEMU_FLIP_AHEAD") == "1"; + public static readonly int EarlyLabelProbe = Environment.GetEnvironmentVariable("SHARPEMU_METAL_V2_EARLY_LABEL_PROBE") switch { diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalV2Presenter.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalV2Presenter.cs index eab98df3e..6121dcb1a 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalV2Presenter.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalV2Presenter.cs @@ -711,6 +711,11 @@ private static void PresentFrame() if (presented != 0) { MetalNative.Send(presented, MetalNative.Selector("retain")); + if (MetalV2Diagnostics.FlipAhead) + { + // A flip copy being encoded is not handed back to the pool (IsFlipCopyHeld). + _encodingTexture = presented; + } } } @@ -782,6 +787,11 @@ private static void PresentFrame() MetalNative.SendVoid(commandBuffer, MetalNative.Selector("presentDrawable:"), drawable); MetalMemoryTelemetry.Commits.Add(); MetalNative.SendVoid(commandBuffer, MetalNative.Selector("commit")); + if (MetalV2Diagnostics.FlipAhead && presented != 0 && texture == presented) + { + MetalFlipCopyPool.NoteSampled(presented, commandBuffer); + } + PresentationCache.RecordPresented(in stamp); PerfOverlay.RecordPresent(); ReportPresentationStatistics(); @@ -790,6 +800,14 @@ private static void PresentFrame() { if (presented != 0) { + if (MetalV2Diagnostics.FlipAhead) + { + lock (_frameGate) + { + _encodingTexture = 0; + } + } + MetalNative.SendVoid(presented, MetalNative.Selector("release")); } } @@ -818,6 +836,35 @@ private static void AdoptPendingFrame() private static readonly AutoResetEvent _flipPacerSignal = new(false); + // SHARPEMU_FLIP_AHEAD: the presented frame PresentFrame is encoding outside the frame gate. + private static nint _encodingTexture; + + /// + /// SHARPEMU_FLIP_AHEAD: whether the presenter may still read this flip copy from the CPU + /// side: it is the presented frame, a queued one, or the one a presentation is encoding. + /// The pool checks the presentation command buffers that sampled it itself. + /// + internal static bool IsFlipCopyHeld(nint texture) + { + lock (_frameGate) + { + if (texture == _presentTexture || texture == _encodingTexture) + { + return true; + } + + foreach (var frame in _pendingFrames) + { + if (frame.Texture == texture) + { + return true; + } + } + + return false; + } + } + // Wakes the pacer: a frame was published or a flip submission completed. internal static void SignalFlipPacer() => _flipPacerSignal.Set(); @@ -1291,7 +1338,8 @@ private static void ReportPresentationStatistics(bool presented = true) $"host_hz={hostHz} seconds={window} published={published} adopt_blocked={blocked} " + $"flip_attempts={flips.Attempts} flip_no_buffer={flips.WithoutBuffer} " + $"flip_discarded={flips.Discarded} flip_published={flips.Published} " + - $"flip_refreshed={flips.Refreshed} {DescribeGpuMemory()}"); + $"flip_refreshed={flips.Refreshed} {DescribeGpuMemory()}" + + (MetalV2Diagnostics.FlipAhead ? " " + MetalFlipCopyPool.TakeReport() : "")); } private static readonly nint SelCurrentAllocatedSize = MetalNative.Selector("currentAllocatedSize"); diff --git a/tests/SharpEmu.Gpu.Metal.Tests/MetalFlipCopyTests.cs b/tests/SharpEmu.Gpu.Metal.Tests/MetalFlipCopyTests.cs new file mode 100644 index 000000000..a5173cc22 --- /dev/null +++ b/tests/SharpEmu.Gpu.Metal.Tests/MetalFlipCopyTests.cs @@ -0,0 +1,104 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using System.Runtime.InteropServices; +using SharpEmu.Gpu.Metal.V2; +using SharpEmu.Libs.Gpu.Abstractions; +using Xunit; +using Xunit.Abstractions; + +namespace SharpEmu.Gpu.Metal.Tests; + +/// +/// SHARPEMU_FLIP_AHEAD: the frame a flip hands the presenter is a copy taken in the stream at the +/// flip, so a draw into the display image recorded after the flip does not reach it. +/// +public sealed class MetalFlipCopyTests(ITestOutputHelper output) +{ + private const uint Side = 64; + private const ulong Address = MetalPassRig.GuestBase + 0x10000; + + [Fact] + public void ADrawIntoTheDisplayImageRecordedAfterTheFlipDoesNotChangeTheCapturedFrame() + { + if (!RequireDevice()) return; + using var rig = new MetalPassRig(Device.Value, 1024 * 1024); + var host = rig.Host; + var formats = new[] { GpuFormat.R8G8B8A8Unorm }; + var red = rig.Pipeline(formats, ["1.0f, 0.0f, 0.0f, 1.0f"]); + var green = rig.Pipeline(formats, ["0.0f, 1.0f, 0.0f, 1.0f"]); + var target = rig.MakeTarget(Address, GpuFormat.R8G8B8A8Unorm, Side, Side); + + using (host.BeginPreparation()) + { + rig.Draw(red, [target]); + host.EndRendering(); + } + + var display = host.ImageCache.GetImage(target.State.Image).Texture; + Assert.True(host.TryCopyFlipFrame(display, out var captured)); + Assert.NotEqual(display, captured); + + // The next frame, recorded after the flip, renders into the same display image. + using (host.BeginPreparation()) + { + rig.Draw(green, [target]); + host.EndRendering(); + } + + host.FlushAndWaitForGpu(MetalWaitReason.Synchronize); + var frame = ReadTexture(Device.Value, captured); + var next = ReadTexture(Device.Value, host.ImageCache.GetImage(target.State.Image).Texture); + output.WriteLine($"captured=0x{BitConverter.ToUInt32(frame, 0):X8} display=0x{BitConverter.ToUInt32(next, 0):X8}"); + for (var texel = 0; texel < frame.Length; texel += 4) + { + Assert.Equal([0xFF, 0x00, 0x00, 0xFF], frame.AsSpan(texel, 4).ToArray()); + Assert.Equal([0x00, 0xFF, 0x00, 0xFF], next.AsSpan(texel, 4).ToArray()); + } + } + + private static byte[] ReadTexture(nint device, nint texture) + { + const nuint bytes = Side * Side * 4; + var queue = MetalNative.Send(device, MetalNative.Selector("newCommandQueue")); + var buffer = MetalNative.SendNewBuffer(device, MetalNative.Selector("newBufferWithLength:options:"), bytes, 0); + try + { + var commandBuffer = MetalNative.Send(queue, MetalNative.Selector("commandBuffer")); + var blit = MetalNative.Send(commandBuffer, MetalNative.Selector("blitCommandEncoder")); + MetalNative.SendCopyTextureToBufferOptions( + blit, + MetalNative.Selector( + "copyFromTexture:sourceSlice:sourceLevel:sourceOrigin:sourceSize:" + + "toBuffer:destinationOffset:destinationBytesPerRow:destinationBytesPerImage:options:"), + texture, 0, 0, default, new MtlSize { Width = Side, Height = Side, Depth = 1 }, + buffer, 0, Side * 4, bytes, 0); + MetalNative.SendVoid(blit, MetalNative.Selector("endEncoding")); + MetalNative.SendVoid(commandBuffer, MetalNative.Selector("commit")); + MetalNative.SendVoid(commandBuffer, MetalNative.Selector("waitUntilCompleted")); + var result = new byte[bytes]; + Marshal.Copy(MetalNative.Send(buffer, MetalNative.Selector("contents")), result, 0, result.Length); + return result; + } + finally + { + MetalNative.SendVoid(buffer, MetalNative.Selector("release")); + MetalNative.SendVoid(queue, MetalNative.Selector("release")); + } + } + + private bool RequireDevice() + { + if (Environment.GetEnvironmentVariable("SHARPEMU_TEST_REQUIRE_DEVICE") != "1") + { + output.WriteLine("The flip copy is encoded on the device only behind the exclusive device gate."); + return false; + } + + Assert.True(OperatingSystem.IsMacOS()); + Assert.NotEqual(0, Device.Value); + return true; + } + + private static readonly Lazy Device = new(MetalNative.MTLCreateSystemDefaultDevice); +} From fd1fd4aa3d2b04a602532376079e481546f73a29 Mon Sep 17 00:00:00 2001 From: kuba Date: Mon, 16 Nov 2026 01:35:46 +0000 Subject: [PATCH 111/178] Revert "[Metal] Flip ahead: hand the presenter a stream-ordered copy of the flip's frame" This reverts commit 530a8d58323961fb44b112255c22deaf57b5cf94. --- docs/macos/configuration.md | 1 - .../V2/MetalCommandStream.cs | 20 +- .../V2/MetalFlipCopyPool.cs | 298 ------------------ .../V2/MetalRenderHost.FlipCopy.cs | 153 --------- .../V2/MetalV2Diagnostics.cs | 5 - .../SharpEmu.Gpu.Metal/V2/MetalV2Presenter.cs | 50 +-- .../MetalFlipCopyTests.cs | 104 ------ 7 files changed, 5 insertions(+), 626 deletions(-) delete mode 100644 src/graphics/SharpEmu.Gpu.Metal/V2/MetalFlipCopyPool.cs delete mode 100644 src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.FlipCopy.cs delete mode 100644 tests/SharpEmu.Gpu.Metal.Tests/MetalFlipCopyTests.cs diff --git a/docs/macos/configuration.md b/docs/macos/configuration.md index d22936e7f..8920bbf6c 100644 --- a/docs/macos/configuration.md +++ b/docs/macos/configuration.md @@ -41,7 +41,6 @@ them for measurements or to isolate a problem. | `SHARPEMU_GUEST_BACKING_SHAREABLE` | unset | `1` makes the guest backing shareable with another process, and keeps a shared table and log of guest views. This is groundwork for the two-process split (`SHARPEMU_GPU_PROCESS=1` sets it too). See [Guest memory for the two-process split](split-shared-memory.md). | | `SHARPEMU_HLE_FAST_PATH` | on | `0` disables the native stubs for `pthread_self` and `pthread_getspecific`. They are also off while import or pthread tracing is active. | | `SHARPEMU_STALL_WATCHDOG_SECONDS` | `20` | Seconds without import progress before the stall watchdog acts. `0` disables it. | -| `SHARPEMU_FLIP_AHEAD` | off | Experimental. `1` tells the game a GPU flip is done once the flip is recorded and the flip before it has really finished on the GPU, instead of when the frame is shown, so the game can build its next frame while the GPU draws this one (at most one flip ahead). Each such frame is copied in the GPU stream into a presenter-owned texture (up to 7 textures the size of the display buffer), so what is shown is unchanged; a flip whose frame cannot be copied keeps the usual timing, and the refusal is logged once. Pacing, interrupts and labels are unchanged. Counters: `[VIDEOOUT][FLIP-AHEAD]` and the `flip_copy*` fields of `[METAL-PRESENT]`. | ## Metal memory diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalCommandStream.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalCommandStream.cs index e617bdd1d..4ebfb6185 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalCommandStream.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalCommandStream.cs @@ -900,7 +900,6 @@ public void RecordEndOfPipe(in EndOfPipeWrite write) VideoOutBackendServices.CompleteFlipOnGpu(requestId); MetalV2Presenter.SignalFlipPacer(); }); - NoteFlipRecordedIfEligible(requestId); break; case EndOfPipeWriteKind.FlipWithInterruptWriteBack32: NoteFlipSerialForEarlyLabels(); @@ -911,7 +910,6 @@ public void RecordEndOfPipe(in EndOfPipeWrite write) MetalV2Presenter.SignalFlipPacer(); TriggerInterrupt(eventId, 0); }); - NoteFlipRecordedIfEligible(requestId); break; case EndOfPipeWriteKind.GdsWrite32: RecordEndOfPipeGdsWrite(in write); @@ -2918,7 +2916,7 @@ public ulong PrepareFlip(int handle, int index, int flipMode, long flipArgument) try { - CaptureFlip(handle, index, requestId, flipMode, flipArgument, gpuQueued: true); + CaptureFlip(handle, index, requestId, flipMode, flipArgument); } catch { @@ -2939,7 +2937,7 @@ public void PrepareCpuFlip(int handle, int index, ulong requestId) } DrainDraws(); - CaptureFlip(handle, index, requestId, flipMode: 0, flipArg: 0, gpuQueued: false); + CaptureFlip(handle, index, requestId, flipMode: 0, flipArg: 0); } // The display surface is a cached image like any other; the flip hands its @@ -2952,7 +2950,7 @@ public void PrepareCpuFlip(int handle, int index, ulong requestId) internal static long FlipsDiscarded; internal static long FlipsPublished; - private void CaptureFlip(int handle, int index, ulong requestId, int flipMode, long flipArg, bool gpuQueued) + private void CaptureFlip(int handle, int index, ulong requestId, int flipMode, long flipArg) { Interlocked.Increment(ref _flipAttempts); Interlocked.Increment(ref FlipsCaptured); @@ -3016,11 +3014,6 @@ private void CaptureFlip(int handle, int index, ulong requestId, int flipMode, l if (_dumpThisFlip) { DumpTexture(image.Texture, "flip-after-refresh"); } SampleFlipLuma(image.Texture); var texture = PresentationViewOf(imageIdentifier, image, in request); - // SHARPEMU_FLIP_AHEAD: the presenter gets a copy taken here, in the stream, instead of - // the display image the guest may render into once it hears of the flip. - var presented = texture; - var copied = MetalV2Diagnostics.FlipAhead && gpuQueued && _flipTarget is not null && texture != 0 && - TryCopyFlipFrame(texture, out presented); var serial = SubmissionSerial; FlushCommandBuffer(PassEndCause.Present); if (_flipTarget is null || texture == 0) @@ -3045,17 +3038,12 @@ private void CaptureFlip(int handle, int index, ulong requestId, int flipMode, l Interlocked.Increment(ref FlipsPublished); ReportFlipSurface(in displayBuffer, in request, imageIdentifier, image, texture); _flipTarget.PublishGuestFrame( - presented, + texture, Math.Max(displayBuffer.Width, 1), Math.Max(displayBuffer.Height, 1), requestId, serial, VideoOutBackendServices.IsHdrPixelFormat(displayBuffer.PixelFormat)); - if (MetalV2Diagnostics.FlipAhead) - { - NoteFlipFrameCaptured(requestId, copied); - } - VideoOutBackendServices.TraceGpuFlip( _memory, handle, index, flipMode, flipArg, displayBuffer.Address, requestId); // The shared phase profile measures the whole draw translation path, which v2 diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalFlipCopyPool.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalFlipCopyPool.cs deleted file mode 100644 index 29123fd17..000000000 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalFlipCopyPool.cs +++ /dev/null @@ -1,298 +0,0 @@ -// Copyright (C) 2026 SharpEmu Emulator Project -// SPDX-License-Identifier: GPL-2.0-or-later - -using System.Runtime.InteropServices; - -namespace SharpEmu.Gpu.Metal.V2; - -/// -/// SHARPEMU_FLIP_AHEAD: the presenter-owned textures a GPU flip's frame is copied into, in the -/// stream at the flip (MetalRenderHost.FlipCopy.cs). Without the copy the presenter samples the -/// display image's own texture until the next frame replaces it, so a guest told of flip N before -/// N is shown could render the next frame into the buffer still on screen. -/// A texture goes back to the pool only once the presenter can no longer read it: it is not -/// the presented frame, not queued, not being encoded by a presentation, and the last -/// presentation command buffer that sampled it has completed. -/// -internal static partial class MetalFlipCopyPool -{ - // The frame on screen, the frames the presenter queues (MaxPendingFrames = 4), the one the - // stream is writing, and one whose last presentation may still be on the GPU. - internal const int Capacity = 7; - - internal enum Refusal - { - PoolExhausted, - TextureType, - Multisampled, - Layout, - TextureCreate, - Encoder, - Count, - } - - private static readonly string[] RefusalNames = - ["pool_exhausted", "texture_type", "multisampled", "layout", "texture_create", "encoder"]; - - private sealed class Entry - { - public nint Texture; - public nint Presented; - public ulong PixelFormat; - public uint Width; - public uint Height; - public MtlTextureSwizzleChannels Swizzle; - public nint LastSampledBy; - } - - private static readonly object _gate = new(); - private static readonly List _entries = new(); - private static readonly long[] _refusals = new long[(int)Refusal.Count]; - private static long _copies; - private static int _highWater; - private static ulong _copyBytes; - - private static readonly nint SelSwizzle = MetalNative.Selector("swizzle"); - private static readonly nint SelStatus = MetalNative.Selector("status"); - private static readonly nint SelRetain = MetalNative.Selector("retain"); - private static readonly nint SelRelease = MetalNative.Selector("release"); - private static readonly nint SelSetUsage = MetalNative.Selector("setUsage:"); - private static readonly nint SelSetStorageMode = MetalNative.Selector("setStorageMode:"); - private static readonly nint SelNewTexture = MetalNative.Selector("newTextureWithDescriptor:"); - private static readonly nint SelNewSwizzledView = - MetalNative.Selector("newTextureViewWithPixelFormat:textureType:levels:slices:swizzle:"); - - // MTLCommandBufferStatusCompleted; Error (5) is past it too. - private const nuint CommandBufferCompleted = 4; - - [LibraryImport("/usr/lib/libobjc.A.dylib", EntryPoint = "objc_msgSend")] - private static partial MtlTextureSwizzleChannels SendSwizzle(nint receiver, nint selector); - - /// The swizzle the presenter samples a texture through. - internal static MtlTextureSwizzleChannels SwizzleOf(nint texture) => SendSwizzle(texture, SelSwizzle); - - /// - /// A texture of this shape the presenter cannot read any more, or a new one. destination is - /// what the copy writes, presented what the presenter is handed (the same texture, or a view - /// of it with the source's swizzle). - /// - internal static bool TryAcquire(nint device, ulong pixelFormat, uint width, uint height, - MtlTextureSwizzleChannels swizzle, out nint destination, out nint presented, out Refusal refusal) - { - destination = 0; - presented = 0; - refusal = Refusal.Count; - lock (_gate) - { - Entry? free = null; - Entry? reclaim = null; - var held = 0; - foreach (var entry in _entries) - { - if (IsReadableLocked(entry)) - { - held++; - continue; - } - - var matches = entry.PixelFormat == pixelFormat && entry.Width == width && entry.Height == height && - SameSwizzle(entry.Swizzle, swizzle); - if (matches) - { - free ??= entry; - } - else - { - reclaim ??= entry; - } - } - - if (free is null) - { - if (_entries.Count >= Capacity) - { - if (reclaim is null) - { - refusal = Refusal.PoolExhausted; - return false; - } - - ReleaseLocked(reclaim); - _entries.Remove(reclaim); - } - - free = Create(device, pixelFormat, width, height, swizzle); - if (free is null) - { - refusal = Refusal.TextureCreate; - return false; - } - - _entries.Add(free); - } - - _highWater = Math.Max(_highWater, held + 1); - destination = free.Texture; - presented = free.Presented; - return true; - } - } - - internal static void NoteCopy(ulong bytes) - { - Interlocked.Increment(ref _copies); - Interlocked.Exchange(ref _copyBytes, bytes); - } - - internal static void NoteRefusal(Refusal refusal) => Interlocked.Increment(ref _refusals[(int)refusal]); - - internal static string RefusalName(Refusal refusal) => RefusalNames[(int)refusal]; - - /// A presentation command buffer, now committed, sampled this texture. - internal static void NoteSampled(nint texture, nint commandBuffer) - { - if (texture == 0 || commandBuffer == 0) - { - return; - } - - lock (_gate) - { - foreach (var entry in _entries) - { - if (entry.Presented != texture) - { - continue; - } - - MetalNative.SendVoid(commandBuffer, SelRetain); - if (entry.LastSampledBy != 0) - { - MetalNative.SendVoid(entry.LastSampledBy, SelRelease); - } - - entry.LastSampledBy = commandBuffer; - return; - } - } - } - - /// Copies, refusals by reason, the most textures the presenter could read at once plus the one written. - internal static string TakeReport() - { - var copies = Interlocked.Exchange(ref _copies, 0); - var refusals = new System.Text.StringBuilder(); - for (var index = 0; index < (int)Refusal.Count; index++) - { - var count = Interlocked.Exchange(ref _refusals[index], 0); - if (count != 0) - { - refusals.Append(refusals.Length == 0 ? "" : ",").Append(RefusalNames[index]).Append(':').Append(count); - } - } - - int pool; - int high; - lock (_gate) - { - pool = _entries.Count; - high = _highWater; - } - - return $"flip_copies={copies} flip_copy_refused={(refusals.Length == 0 ? "0" : refusals.ToString())} " + - $"flip_copy_pool={pool} flip_copy_pool_high={high} flip_copy_mb={Interlocked.Read(ref _copyBytes) / (1024.0 * 1024.0):F1}"; - } - - // Caller holds the gate. - private static bool IsReadableLocked(Entry entry) - { - if (MetalV2Presenter.IsFlipCopyHeld(entry.Presented)) - { - return true; - } - - if (entry.LastSampledBy == 0) - { - return false; - } - - if (MetalV2Native.SendValue(entry.LastSampledBy, SelStatus) < CommandBufferCompleted) - { - return true; - } - - MetalNative.SendVoid(entry.LastSampledBy, SelRelease); - entry.LastSampledBy = 0; - return false; - } - - private static bool SameSwizzle(MtlTextureSwizzleChannels left, MtlTextureSwizzleChannels right) => - left.Red == right.Red && left.Green == right.Green && left.Blue == right.Blue && left.Alpha == right.Alpha; - - // MTLTextureSwizzleRed..Alpha are 2..5. - private static bool IsIdentity(MtlTextureSwizzleChannels swizzle) => - swizzle.Red == 2 && swizzle.Green == 3 && swizzle.Blue == 4 && swizzle.Alpha == 5; - - private static Entry? Create(nint device, ulong pixelFormat, uint width, uint height, MtlTextureSwizzleChannels swizzle) - { - var descriptor = MetalNative.SendTextureDescriptor( - MetalNative.Class("MTLTextureDescriptor"), - MetalNative.Selector("texture2DDescriptorWithPixelFormat:width:height:mipmapped:"), - (nuint)pixelFormat, - width, - height, - mipmapped: false); - if (descriptor == 0) - { - return null; - } - - var identity = IsIdentity(swizzle); - MetalV2Native.SendVoidValue(descriptor, SelSetUsage, - (nuint)(Mtl.TextureUsageShaderRead | (identity ? 0 : Mtl.TextureUsagePixelFormatView))); - MetalV2Native.SendVoidValue(descriptor, SelSetStorageMode, Mtl.StorageModePrivate); - var texture = MetalNative.Send(device, SelNewTexture, descriptor); - if (texture == 0) - { - return null; - } - - var presented = texture; - if (!identity) - { - presented = MetalV2Native.SendNewSwizzledTextureView( - texture, SelNewSwizzledView, (nuint)pixelFormat, (nuint)Mtl.TextureType2D, - new NsRange { Location = 0, Length = 1 }, new NsRange { Location = 0, Length = 1 }, swizzle); - if (presented == 0) - { - MetalNative.SendVoid(texture, SelRelease); - return null; - } - } - - return new Entry - { - Texture = texture, - Presented = presented, - PixelFormat = pixelFormat, - Width = width, - Height = height, - Swizzle = swizzle, - }; - } - - // Caller holds the gate; the entry is not readable. - private static void ReleaseLocked(Entry entry) - { - if (entry.Presented != entry.Texture) - { - MetalNative.SendVoid(entry.Presented, SelRelease); - } - - MetalNative.SendVoid(entry.Texture, SelRelease); - if (entry.LastSampledBy != 0) - { - MetalNative.SendVoid(entry.LastSampledBy, SelRelease); - } - } -} diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.FlipCopy.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.FlipCopy.cs deleted file mode 100644 index db9f1ae83..000000000 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.FlipCopy.cs +++ /dev/null @@ -1,153 +0,0 @@ -// Copyright (C) 2026 SharpEmu Emulator Project -// SPDX-License-Identifier: GPL-2.0-or-later - -using SharpEmu.Libs.VideoOut; - -namespace SharpEmu.Gpu.Metal.V2; - -// SHARPEMU_FLIP_AHEAD: a GPU flip's frame is copied, in the stream at the flip, into a texture -// only the presenter reads (MetalFlipCopyPool), and video-out is told once the flip is recorded -// and the buffer carrying it committed, so it may publish the flip to the guest before the GPU -// finishes it (VideoOutExports.FlipAhead.cs). -internal sealed partial class MetalRenderHost -{ - private static readonly nint SelMipmapLevelCount = MetalNative.Selector("mipmapLevelCount"); - private static readonly nint SelArrayLength = MetalNative.Selector("arrayLength"); - private static readonly nint SelAllocatedSize = MetalNative.Selector("allocatedSize"); - - // The flips whose frame was copied while the frame before them was a copy too: the only - // ones whose recorded notice is sent. Worker thread; locked for the command thread's sake. - private readonly List _flipAheadEligible = new(); - - // Whether the last frame handed to the presenter was a copy. A frame handed over live (a CPU - // flip, a refused copy) is the display image itself, which stays on screen until the next - // frame is promoted: the guest must not hear of that next flip before it is shown. - private bool _previousFlipFrameCopied = true; - - // Copies the flip's presented view into a pool texture at this point of the stream. False - // (refused, logged once and counted) leaves the frame to be presented live, as today. - internal bool TryCopyFlipFrame(nint source, out nint presented) - { - presented = source; - var type = (ulong)MetalV2Native.SendValue(source, SelTextureType); - if (type != Mtl.TextureType2D) - { - return RefuseFlipCopy(MetalFlipCopyPool.Refusal.TextureType, $"type={type}"); - } - - var samples = (ulong)MetalV2Native.SendValue(source, SelSampleCount); - if (samples > 1) - { - return RefuseFlipCopy(MetalFlipCopyPool.Refusal.Multisampled, $"samples={samples}"); - } - - var levels = (ulong)MetalV2Native.SendValue(source, SelMipmapLevelCount); - var layers = (ulong)MetalV2Native.SendValue(source, SelArrayLength); - if (levels != 1 || layers != 1) - { - return RefuseFlipCopy(MetalFlipCopyPool.Refusal.Layout, $"levels={levels} layers={layers}"); - } - - var pixelFormat = (ulong)MetalV2Native.SendValue(source, SelPixelFormat); - var width = (uint)MetalV2Native.SendValue(source, SelWidth); - var height = (uint)MetalV2Native.SendValue(source, SelHeight); - var swizzle = MetalFlipCopyPool.SwizzleOf(source); - if (!MetalFlipCopyPool.TryAcquire(_device, pixelFormat, width, height, swizzle, - out var destination, out var copy, out var refusal)) - { - return RefuseFlipCopy(refusal, $"format={pixelFormat} {width}x{height} capacity={MetalFlipCopyPool.Capacity}"); - } - - EndEncoders(PassEndCause.Present); - var encoder = MetalNative.Send(EnsureCommandBuffer(), SelBlitEncoder); - MetalMemoryTelemetry.BlitEncoders.Add(); - if (encoder == 0) - { - return RefuseFlipCopy(MetalFlipCopyPool.Refusal.Encoder, $"format={pixelFormat} {width}x{height}"); - } - - // Fenced like every other encoder of the stream: after the passes that drew the frame, - // before anything recorded after the flip. - WaitForPreviousEncoder(encoder, render: false); - try - { - MetalNative.SendCopyTextureSlice( - encoder, - SelCopyTextureSlice, - source, - 0, - 0, - default, - new MtlSize { Width = width, Height = height, Depth = 1 }, - destination, - 0, - 0, - default); - } - finally - { - UpdateEncoderFence(encoder, render: false); - MetalNative.SendVoid(encoder, SelEndEncoding); - } - - NoteRecordedWork(); - MetalFlipCopyPool.NoteCopy((ulong)MetalV2Native.SendValue(destination, SelAllocatedSize)); - presented = copy; - return true; - } - - private static bool RefuseFlipCopy(MetalFlipCopyPool.Refusal refusal, string detail) - { - MetalFlipCopyPool.NoteRefusal(refusal); - MetalV2Diagnostics.WarnOnce( - $"flip-copy-{MetalFlipCopyPool.RefusalName(refusal)}", - $"Flip ahead: a flip's frame could not be copied for the presenter ({MetalFlipCopyPool.RefusalName(refusal)}: " + - $"{detail}); it is presented live and published to the guest at presentation, as without the switch."); - return false; - } - - // After the frame went to the presenter: copied flips whose previous frame was a copy too - // may be published ahead once their end-of-pipe completion is queued. - private void NoteFlipFrameCaptured(ulong requestId, bool copied) - { - var eligible = copied && _previousFlipFrameCopied; - _previousFlipFrameCopied = copied; - if (!eligible) - { - return; - } - - lock (_flipAheadEligible) - { - // A flip whose end-of-pipe write never reaches RecordEndOfPipe (a label published by - // the interpreter) keeps today's timing; its entry is dropped here. - if (_flipAheadEligible.Count >= 8) - { - _flipAheadEligible.RemoveAt(0); - } - - _flipAheadEligible.Add(requestId); - } - } - - // RecordEndOfPipe queued the flip's completion: the buffer carrying it is committed (or the - // completion already ran inline, in which case video-out ignores the late notice). - private void NoteFlipRecordedIfEligible(ulong requestId) - { - if (!MetalV2Diagnostics.FlipAhead || requestId == 0) - { - return; - } - - bool eligible; - lock (_flipAheadEligible) - { - eligible = _flipAheadEligible.Remove(requestId); - } - - if (eligible) - { - VideoOutBackendServices.NoteFlipRecorded(requestId); - } - } -} diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalV2Diagnostics.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalV2Diagnostics.cs index d07215d3c..4bd321076 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalV2Diagnostics.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalV2Diagnostics.cs @@ -153,11 +153,6 @@ private static HashSet ParseHashes(string? text) public static readonly ulong[] EarlyLabelProbeAddresses = ParseEarlyLabelAddresses( Environment.GetEnvironmentVariable("SHARPEMU_METAL_V2_EARLY_LABEL_PROBE")); - // SHARPEMU_FLIP_AHEAD=1 (experimental, default off): a GPU flip hands the presenter a copy of its - // frame, blitted in the stream at the flip, and tells video-out the flip is recorded, so the guest - // may learn of it before the GPU finishes it (VideoOutExports.FlipAhead.cs, MetalFlipCopyPool). - public static readonly bool FlipAhead = Environment.GetEnvironmentVariable("SHARPEMU_FLIP_AHEAD") == "1"; - public static readonly int EarlyLabelProbe = Environment.GetEnvironmentVariable("SHARPEMU_METAL_V2_EARLY_LABEL_PROBE") switch { diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalV2Presenter.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalV2Presenter.cs index 6121dcb1a..eab98df3e 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalV2Presenter.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalV2Presenter.cs @@ -711,11 +711,6 @@ private static void PresentFrame() if (presented != 0) { MetalNative.Send(presented, MetalNative.Selector("retain")); - if (MetalV2Diagnostics.FlipAhead) - { - // A flip copy being encoded is not handed back to the pool (IsFlipCopyHeld). - _encodingTexture = presented; - } } } @@ -787,11 +782,6 @@ private static void PresentFrame() MetalNative.SendVoid(commandBuffer, MetalNative.Selector("presentDrawable:"), drawable); MetalMemoryTelemetry.Commits.Add(); MetalNative.SendVoid(commandBuffer, MetalNative.Selector("commit")); - if (MetalV2Diagnostics.FlipAhead && presented != 0 && texture == presented) - { - MetalFlipCopyPool.NoteSampled(presented, commandBuffer); - } - PresentationCache.RecordPresented(in stamp); PerfOverlay.RecordPresent(); ReportPresentationStatistics(); @@ -800,14 +790,6 @@ private static void PresentFrame() { if (presented != 0) { - if (MetalV2Diagnostics.FlipAhead) - { - lock (_frameGate) - { - _encodingTexture = 0; - } - } - MetalNative.SendVoid(presented, MetalNative.Selector("release")); } } @@ -836,35 +818,6 @@ private static void AdoptPendingFrame() private static readonly AutoResetEvent _flipPacerSignal = new(false); - // SHARPEMU_FLIP_AHEAD: the presented frame PresentFrame is encoding outside the frame gate. - private static nint _encodingTexture; - - /// - /// SHARPEMU_FLIP_AHEAD: whether the presenter may still read this flip copy from the CPU - /// side: it is the presented frame, a queued one, or the one a presentation is encoding. - /// The pool checks the presentation command buffers that sampled it itself. - /// - internal static bool IsFlipCopyHeld(nint texture) - { - lock (_frameGate) - { - if (texture == _presentTexture || texture == _encodingTexture) - { - return true; - } - - foreach (var frame in _pendingFrames) - { - if (frame.Texture == texture) - { - return true; - } - } - - return false; - } - } - // Wakes the pacer: a frame was published or a flip submission completed. internal static void SignalFlipPacer() => _flipPacerSignal.Set(); @@ -1338,8 +1291,7 @@ private static void ReportPresentationStatistics(bool presented = true) $"host_hz={hostHz} seconds={window} published={published} adopt_blocked={blocked} " + $"flip_attempts={flips.Attempts} flip_no_buffer={flips.WithoutBuffer} " + $"flip_discarded={flips.Discarded} flip_published={flips.Published} " + - $"flip_refreshed={flips.Refreshed} {DescribeGpuMemory()}" + - (MetalV2Diagnostics.FlipAhead ? " " + MetalFlipCopyPool.TakeReport() : "")); + $"flip_refreshed={flips.Refreshed} {DescribeGpuMemory()}"); } private static readonly nint SelCurrentAllocatedSize = MetalNative.Selector("currentAllocatedSize"); diff --git a/tests/SharpEmu.Gpu.Metal.Tests/MetalFlipCopyTests.cs b/tests/SharpEmu.Gpu.Metal.Tests/MetalFlipCopyTests.cs deleted file mode 100644 index a5173cc22..000000000 --- a/tests/SharpEmu.Gpu.Metal.Tests/MetalFlipCopyTests.cs +++ /dev/null @@ -1,104 +0,0 @@ -// Copyright (C) 2026 SharpEmu Emulator Project -// SPDX-License-Identifier: GPL-2.0-or-later - -using System.Runtime.InteropServices; -using SharpEmu.Gpu.Metal.V2; -using SharpEmu.Libs.Gpu.Abstractions; -using Xunit; -using Xunit.Abstractions; - -namespace SharpEmu.Gpu.Metal.Tests; - -/// -/// SHARPEMU_FLIP_AHEAD: the frame a flip hands the presenter is a copy taken in the stream at the -/// flip, so a draw into the display image recorded after the flip does not reach it. -/// -public sealed class MetalFlipCopyTests(ITestOutputHelper output) -{ - private const uint Side = 64; - private const ulong Address = MetalPassRig.GuestBase + 0x10000; - - [Fact] - public void ADrawIntoTheDisplayImageRecordedAfterTheFlipDoesNotChangeTheCapturedFrame() - { - if (!RequireDevice()) return; - using var rig = new MetalPassRig(Device.Value, 1024 * 1024); - var host = rig.Host; - var formats = new[] { GpuFormat.R8G8B8A8Unorm }; - var red = rig.Pipeline(formats, ["1.0f, 0.0f, 0.0f, 1.0f"]); - var green = rig.Pipeline(formats, ["0.0f, 1.0f, 0.0f, 1.0f"]); - var target = rig.MakeTarget(Address, GpuFormat.R8G8B8A8Unorm, Side, Side); - - using (host.BeginPreparation()) - { - rig.Draw(red, [target]); - host.EndRendering(); - } - - var display = host.ImageCache.GetImage(target.State.Image).Texture; - Assert.True(host.TryCopyFlipFrame(display, out var captured)); - Assert.NotEqual(display, captured); - - // The next frame, recorded after the flip, renders into the same display image. - using (host.BeginPreparation()) - { - rig.Draw(green, [target]); - host.EndRendering(); - } - - host.FlushAndWaitForGpu(MetalWaitReason.Synchronize); - var frame = ReadTexture(Device.Value, captured); - var next = ReadTexture(Device.Value, host.ImageCache.GetImage(target.State.Image).Texture); - output.WriteLine($"captured=0x{BitConverter.ToUInt32(frame, 0):X8} display=0x{BitConverter.ToUInt32(next, 0):X8}"); - for (var texel = 0; texel < frame.Length; texel += 4) - { - Assert.Equal([0xFF, 0x00, 0x00, 0xFF], frame.AsSpan(texel, 4).ToArray()); - Assert.Equal([0x00, 0xFF, 0x00, 0xFF], next.AsSpan(texel, 4).ToArray()); - } - } - - private static byte[] ReadTexture(nint device, nint texture) - { - const nuint bytes = Side * Side * 4; - var queue = MetalNative.Send(device, MetalNative.Selector("newCommandQueue")); - var buffer = MetalNative.SendNewBuffer(device, MetalNative.Selector("newBufferWithLength:options:"), bytes, 0); - try - { - var commandBuffer = MetalNative.Send(queue, MetalNative.Selector("commandBuffer")); - var blit = MetalNative.Send(commandBuffer, MetalNative.Selector("blitCommandEncoder")); - MetalNative.SendCopyTextureToBufferOptions( - blit, - MetalNative.Selector( - "copyFromTexture:sourceSlice:sourceLevel:sourceOrigin:sourceSize:" + - "toBuffer:destinationOffset:destinationBytesPerRow:destinationBytesPerImage:options:"), - texture, 0, 0, default, new MtlSize { Width = Side, Height = Side, Depth = 1 }, - buffer, 0, Side * 4, bytes, 0); - MetalNative.SendVoid(blit, MetalNative.Selector("endEncoding")); - MetalNative.SendVoid(commandBuffer, MetalNative.Selector("commit")); - MetalNative.SendVoid(commandBuffer, MetalNative.Selector("waitUntilCompleted")); - var result = new byte[bytes]; - Marshal.Copy(MetalNative.Send(buffer, MetalNative.Selector("contents")), result, 0, result.Length); - return result; - } - finally - { - MetalNative.SendVoid(buffer, MetalNative.Selector("release")); - MetalNative.SendVoid(queue, MetalNative.Selector("release")); - } - } - - private bool RequireDevice() - { - if (Environment.GetEnvironmentVariable("SHARPEMU_TEST_REQUIRE_DEVICE") != "1") - { - output.WriteLine("The flip copy is encoded on the device only behind the exclusive device gate."); - return false; - } - - Assert.True(OperatingSystem.IsMacOS()); - Assert.NotEqual(0, Device.Value); - return true; - } - - private static readonly Lazy Device = new(MetalNative.MTLCreateSystemDefaultDevice); -} From 79e60ed4318881db3e87715084377ef8375005c6 Mon Sep 17 00:00:00 2001 From: kuba Date: Mon, 16 Nov 2026 01:35:47 +0000 Subject: [PATCH 112/178] Revert "[VideoOut] Flip ahead: publish a recorded flip once the flip before it has really completed" This reverts commit 9aad70d58e4e3f054dbc4def856fae4390238096. --- src/SharpEmu.GpuRemote/GpuSplitMessages.cs | 3 - src/SharpEmu.GpuSplit/GuestProcessSide.cs | 3 - src/SharpEmu.GpuSplit/RemoteVideoOutBridge.cs | 2 - .../VideoOut/VideoOutBackendServices.cs | 12 - .../VideoOut/VideoOutExports.FlipAhead.cs | 233 -------------- .../VideoOut/VideoOutExports.FlipRequests.cs | 74 +---- .../Gpu/Split/SplitHookTests.cs | 2 - .../VideoOut/VideoOutFlipAheadTests.cs | 292 ------------------ 8 files changed, 11 insertions(+), 610 deletions(-) delete mode 100644 src/SharpEmu.Libs/VideoOut/VideoOutExports.FlipAhead.cs delete mode 100644 tests/SharpEmu.Libs.Tests/VideoOut/VideoOutFlipAheadTests.cs diff --git a/src/SharpEmu.GpuRemote/GpuSplitMessages.cs b/src/SharpEmu.GpuRemote/GpuSplitMessages.cs index 359b55cb2..d9eccfd68 100644 --- a/src/SharpEmu.GpuRemote/GpuSplitMessages.cs +++ b/src/SharpEmu.GpuRemote/GpuSplitMessages.cs @@ -43,9 +43,6 @@ public enum GpuSplitFlipEvent : uint /// CompleteFlip. Completed = 6, - - /// NoteFlipRecorded (SHARPEMU_FLIP_AHEAD). - Recorded = 7, } /// The kinds of . diff --git a/src/SharpEmu.GpuSplit/GuestProcessSide.cs b/src/SharpEmu.GpuSplit/GuestProcessSide.cs index da4d46cd2..425f27518 100644 --- a/src/SharpEmu.GpuSplit/GuestProcessSide.cs +++ b/src/SharpEmu.GpuSplit/GuestProcessSide.cs @@ -77,9 +77,6 @@ public void FlipEvent(GpuSplitFlipEvent kind, ulong requestId) case GpuSplitFlipEvent.Completed: VideoOutBackendServices.CompleteFlip(requestId); break; - case GpuSplitFlipEvent.Recorded: - VideoOutBackendServices.NoteFlipRecorded(requestId); - break; } } diff --git a/src/SharpEmu.GpuSplit/RemoteVideoOutBridge.cs b/src/SharpEmu.GpuSplit/RemoteVideoOutBridge.cs index 680a187c2..517144961 100644 --- a/src/SharpEmu.GpuSplit/RemoteVideoOutBridge.cs +++ b/src/SharpEmu.GpuSplit/RemoteVideoOutBridge.cs @@ -83,8 +83,6 @@ public bool IsFlipPresentationPending(ulong requestId) => public void MarkFlipPresented(ulong requestId) => FlipEvent(GpuSplitFlipEvent.Presented, requestId); - public void NoteFlipRecorded(ulong requestId) => FlipEvent(GpuSplitFlipEvent.Recorded, requestId); - public void NotifyPresentationWindowClosed() => host.SendNotice(GpuSplitNotice.PresentationWindowClosed); // Only a flip that names no buffer (-1) is released here; every other flip answers false without diff --git a/src/SharpEmu.Libs/VideoOut/VideoOutBackendServices.cs b/src/SharpEmu.Libs/VideoOut/VideoOutBackendServices.cs index aba99437e..3b3dda0c5 100644 --- a/src/SharpEmu.Libs/VideoOut/VideoOutBackendServices.cs +++ b/src/SharpEmu.Libs/VideoOut/VideoOutBackendServices.cs @@ -74,16 +74,6 @@ public static void CompleteFlipOnGpu(ulong requestId) VideoOutExports.CompleteFlipOnGpu(requestId); } - // SHARPEMU_FLIP_AHEAD: the GPU host recorded the flip, committed the buffer carrying it - // and captured its frame as a copy (VideoOutExports.NoteFlipRecorded). - public static void NoteFlipRecorded(ulong requestId) - { - if (Bridge is { } bridge) - bridge.NoteFlipRecorded(requestId); - else - VideoOutExports.NoteFlipRecorded(requestId); - } - public static void DiscardFlip(ulong requestId) { if (Bridge is { } bridge) @@ -214,8 +204,6 @@ public interface IVideoOutBackendBridge void MarkFlipPresented(ulong requestId); - void NoteFlipRecorded(ulong requestId); - void NotifyPresentationWindowClosed(); bool ReleaseNoBufferFlip(int bufferIndex, ulong requestId); diff --git a/src/SharpEmu.Libs/VideoOut/VideoOutExports.FlipAhead.cs b/src/SharpEmu.Libs/VideoOut/VideoOutExports.FlipAhead.cs deleted file mode 100644 index 4ab7b331e..000000000 --- a/src/SharpEmu.Libs/VideoOut/VideoOutExports.FlipAhead.cs +++ /dev/null @@ -1,233 +0,0 @@ -// Copyright (C) 2026 SharpEmu Emulator Project -// SPDX-License-Identifier: GPL-2.0-or-later - -using System.Diagnostics; - -namespace SharpEmu.Libs.VideoOut; - -// SHARPEMU_FLIP_AHEAD=1 (experimental, default off). A GPU-queued flip's guest-visible -// completion (flip count, process time, flip arg, current buffer, the previous buffer's -// label, the pending count and the flip events) is published once the GPU host has recorded -// the flip, committed the buffer carrying it and handed the presenter a copy of its frame -// (NoteFlipRecorded), and the GPU-queued flip before it on the handle has really completed -// on the GPU and been published. The guest is then at most one flip ahead of the GPU. The -// request itself stays in the table for the pacer, which presents or drops it as before, and -// its real GPU completion still releases the GPU slot and sets the ready timestamp. Without -// the notice (switch off, or a flip whose frame was not copied) nothing here runs. -public static partial class VideoOutExports -{ - internal static bool FlipAheadEnabled { get; set; } = string.Equals( - Environment.GetEnvironmentVariable("SHARPEMU_FLIP_AHEAD"), "1", StringComparison.Ordinal); - - // The last GPU-queued request reserved on each handle. Guarded by the state gate. - private static readonly Dictionary _lastGpuQueuedFlip = new(); - - private static long _flipAheadAtRecord; - private static long _flipAheadAtPrevious; - private static long _flipAheadLateNotices; - private static long _flipAheadLeadTicks; - private static long _flipAheadLeadCount; - private static long _flipAheadReportedAt; - - // Caller holds the state gate. - private static void NoteGpuQueuedFlipLocked(FlipRequest request) - { - if (_lastGpuQueuedFlip.TryGetValue(request.Handle, out var previous) && - previous.Outcome != FlipOutcome.Cancelled && - !(previous.State == FlipRequestState.Completed && previous.GpuCompleted && previous.EventsTriggered)) - { - request.AheadPrevious = previous; - } - - _lastGpuQueuedFlip[request.Handle] = request; - } - - /// - /// The GPU host recorded this flip, committed the command buffer that carries it and - /// captured its frame as a copy the guest cannot overwrite. A notice for a request that is - /// already past that point (its real completion came first, it was cancelled or published) - /// is ignored, and the flip keeps today's timing. - /// - internal static void NoteFlipRecorded(ulong requestId) - { - if (!FlipAheadEnabled) - { - return; - } - - int handle; - lock (_stateGate) - { - if (!_flipRequests.TryGetValue(requestId, out var request) || !request.GpuQueued || - request.State != FlipRequestState.Reserved) - { - Interlocked.Increment(ref _flipAheadLateNotices); - return; - } - - request.AheadRecorded = true; - handle = request.Handle; - } - - DrainFlipAhead(handle, requestId); - } - - // Caller holds the state gate. The real completion of a flip published ahead. - private static void CompleteAheadFlipOnGpuLocked(FlipRequest request) - { - ReleaseGpuQueueSlotLocked(request); - request.GpuCompleted = true; - Interlocked.Add(ref _flipAheadLeadTicks, Math.Max(0, Stopwatch.GetTimestamp() - request.AheadPublishedAt)); - Interlocked.Increment(ref _flipAheadLeadCount); - RemoveIfFinishedLocked(request); - Monitor.PulseAll(_stateGate); - } - - // Outside the state gate. The flip's counters were published: trigger its events, then let - // the flip after it go ahead if it was waiting for this one. - private static void TriggerPublishedFlip(FlipRequest request) - { - TriggerFlipEvents(request); - if (!FlipAheadEnabled) - { - return; - } - - lock (_stateGate) - { - request.EventsTriggered = true; - } - - DrainFlipAhead(request.Handle, noticed: 0); - } - - // Outside the state gate. Publishes, oldest first, every flip on the handle that may go - // ahead now. noticed is the request whose recorded notice is being handled, if any. - private static void DrainFlipAhead(int handle, ulong noticed) - { - if (!FlipAheadEnabled) - { - return; - } - - while (true) - { - FlipRequest? next; - lock (_stateGate) - { - next = FindFlipAheadCandidateLocked(handle); - if (next is not null) - { - // Set first: a dropped frame's request must outlive the publication until its - // real completion releases the GPU slot (RemoveIfFinishedLocked). - next.AheadPublishedAt = Stopwatch.GetTimestamp(); - PublishFlipLocked(next); - Interlocked.Increment(ref next.RequestId == noticed ? ref _flipAheadAtRecord : ref _flipAheadAtPrevious); - } - } - - if (next is null) - { - break; - } - - TriggerFlipEvents(next); - lock (_stateGate) - { - next.EventsTriggered = true; - } - } - - ReportFlipAhead(); - } - - // Caller holds the state gate. Only the oldest unpublished request on the handle may be - // published, so the guest sees flips in order; an unpublished CPU flip before it blocks it. - private static FlipRequest? FindFlipAheadCandidateLocked(int handle) - { - FlipRequest? oldest = null; - foreach (var request in _flipRequests.Values) - { - if (request.Handle == handle && request.State != FlipRequestState.Completed && - (oldest is null || request.RequestId < oldest.RequestId)) - { - oldest = request; - } - } - - if (oldest is null || !oldest.AheadRecorded || !oldest.GpuQueued || oldest.State != FlipRequestState.Reserved) - { - return null; - } - - var previous = oldest.AheadPrevious; - if (previous is not null && previous.Outcome != FlipOutcome.Cancelled && - !(previous.State == FlipRequestState.Completed && previous.GpuCompleted && previous.EventsTriggered)) - { - return null; - } - - return oldest; - } - - // At most one line every two seconds, and only while flips go ahead. - private static void ReportFlipAhead() - { - var now = Stopwatch.GetTimestamp(); - var last = Interlocked.Read(ref _flipAheadReportedAt); - if (now - last < 2 * Stopwatch.Frequency || - Interlocked.CompareExchange(ref _flipAheadReportedAt, now, last) != last) - { - return; - } - - var atRecord = Interlocked.Exchange(ref _flipAheadAtRecord, 0); - var atPrevious = Interlocked.Exchange(ref _flipAheadAtPrevious, 0); - var late = Interlocked.Exchange(ref _flipAheadLateNotices, 0); - var leadTicks = Interlocked.Exchange(ref _flipAheadLeadTicks, 0); - var leadCount = Interlocked.Exchange(ref _flipAheadLeadCount, 0); - if (last == 0 || atRecord + atPrevious + late == 0) - { - return; - } - - var leadMs = leadCount == 0 ? 0 : leadTicks * 1000.0 / Stopwatch.Frequency / leadCount; - Console.Error.WriteLine( - $"[VIDEOOUT][FLIP-AHEAD] ahead_at_record={atRecord} ahead_at_previous_completion={atPrevious} " + - $"late_notices={late} lead_ms_mean={leadMs.ToString("F1", System.Globalization.CultureInfo.InvariantCulture)} " + - $"lead_samples={leadCount} seconds={((now - last) / (double)Stopwatch.Frequency).ToString("F1", System.Globalization.CultureInfo.InvariantCulture)}"); - } - - internal readonly record struct FlipAheadCounters(long AtRecord, long AtPrevious, long LateNotices, long LeadSamples); - - internal static FlipAheadCounters PeekFlipAheadCountersForTests() => new( - Interlocked.Read(ref _flipAheadAtRecord), - Interlocked.Read(ref _flipAheadAtPrevious), - Interlocked.Read(ref _flipAheadLateNotices), - Interlocked.Read(ref _flipAheadLeadCount)); - - internal static void ResetFlipAheadForTests(bool enabled) - { - lock (_stateGate) - { - _lastGpuQueuedFlip.Clear(); - } - - FlipAheadEnabled = enabled; - // Keep the report from consuming the counters while a test reads them. - Interlocked.Exchange(ref _flipAheadReportedAt, Stopwatch.GetTimestamp() + 3600 * Stopwatch.Frequency); - Interlocked.Exchange(ref _flipAheadAtRecord, 0); - Interlocked.Exchange(ref _flipAheadAtPrevious, 0); - Interlocked.Exchange(ref _flipAheadLateNotices, 0); - Interlocked.Exchange(ref _flipAheadLeadTicks, 0); - Interlocked.Exchange(ref _flipAheadLeadCount, 0); - } - - internal static int GetGpuQueueCountForTests(int handle) - { - lock (_stateGate) - { - return _ports.TryGetValue(handle, out var port) ? port.GpuQueueCount : -1; - } - } -} diff --git a/src/SharpEmu.Libs/VideoOut/VideoOutExports.FlipRequests.cs b/src/SharpEmu.Libs/VideoOut/VideoOutExports.FlipRequests.cs index 9a5484e92..a2d0c0fc3 100644 --- a/src/SharpEmu.Libs/VideoOut/VideoOutExports.FlipRequests.cs +++ b/src/SharpEmu.Libs/VideoOut/VideoOutExports.FlipRequests.cs @@ -47,18 +47,6 @@ private sealed class FlipRequest public int FlipEventCount; public FlipRequestState State; public FlipOutcome Outcome; - - // SHARPEMU_FLIP_AHEAD (see VideoOutExports.FlipAhead.cs). The GPU host recorded the flip, - // committed the buffer carrying it and handed the presenter a copy of its frame. - public bool AheadRecorded; - // The GPU really finished the submission carrying the flip (CompleteFlipOnGpu ran). - public bool GpuCompleted; - // The flip events of the published flip have been triggered. - public bool EventsTriggered; - // When the guest-visible completion was published ahead of the GPU; zero otherwise. - public long AheadPublishedAt; - // The GPU-queued flip reserved before this one on the same handle, until this one is published. - public FlipRequest? AheadPrevious; } private static readonly Dictionary _flipRequests = new(); @@ -158,10 +146,6 @@ internal static int TryReserveFlipRequest( } _flipRequests.Add(request.RequestId, request); - if (gpuQueued && FlipAheadEnabled) - { - NoteGpuQueuedFlipLocked(request); - } } if (bufferIndex >= 0 && TryGetDisplayBufferInfo(handle, bufferIndex, out var displayBuffer)) @@ -253,11 +237,10 @@ internal static void CompleteFlip(ulong requestId) } ReleaseGpuQueueSlotLocked(request); - request.GpuCompleted = true; PublishFlipLocked(request); } - TriggerPublishedFlip(request); + TriggerFlipEvents(request); } /// @@ -270,49 +253,25 @@ internal static void CompleteFlip(ulong requestId) internal static void CompleteFlipOnGpu(ulong requestId) { FlipRequest request; - var aheadAlready = false; lock (_stateGate) { - if (!_flipRequests.TryGetValue(requestId, out request!)) + if (!_flipRequests.TryGetValue(requestId, out request!) || request.State != FlipRequestState.Reserved) { return; } - if (request.State != FlipRequestState.Reserved) - { - // A flip published ahead still owes its GPU-side state; the guest was told already, - // so neither the counters nor the events are published again. - if (request.AheadPublishedAt == 0 || request.GpuCompleted) - { - return; - } - - CompleteAheadFlipOnGpuLocked(request); - aheadAlready = true; - } - else + ReleaseGpuQueueSlotLocked(request); + if (request.Outcome == FlipOutcome.Pending) { - ReleaseGpuQueueSlotLocked(request); - request.GpuCompleted = true; - if (request.Outcome == FlipOutcome.Pending) - { - request.State = FlipRequestState.GpuDone; - Monitor.PulseAll(_stateGate); - return; - } - - PublishFlipLocked(request); + request.State = FlipRequestState.GpuDone; + Monitor.PulseAll(_stateGate); + return; } - } - if (aheadAlready) - { - // The flip after this one may be waiting for this real completion. - DrainFlipAhead(request.Handle, noticed: 0); - return; + PublishFlipLocked(request); } - TriggerPublishedFlip(request); + TriggerFlipEvents(request); } // Caller holds the state gate. The GPU no longer holds the request. @@ -329,7 +288,6 @@ private static void ReleaseGpuQueueSlotLocked(FlipRequest request) private static void PublishFlipLocked(FlipRequest request) { request.State = FlipRequestState.Completed; - request.AheadPrevious = null; if (_ports.TryGetValue(request.Handle, out var port)) { port.FlipCount++; @@ -427,7 +385,7 @@ private static bool SetFlipOutcome(ulong requestId, FlipOutcome outcome) if (published is not null) { - TriggerPublishedFlip(published); + TriggerFlipEvents(published); } return true; @@ -436,9 +394,7 @@ private static bool SetFlipOutcome(ulong requestId, FlipOutcome outcome) // Both responsibilities are done: the retirement ran and the presenter released the frame. private static void RemoveIfFinishedLocked(FlipRequest request) { - // A flip published ahead of the GPU stays until its real completion has released its GPU slot. - if (request.State == FlipRequestState.Completed && request.Outcome != FlipOutcome.Pending && - (request.AheadPublishedAt == 0 || request.GpuCompleted)) + if (request.State == FlipRequestState.Completed && request.Outcome != FlipOutcome.Pending) { _flipRequests.Remove(request.RequestId); } @@ -505,14 +461,6 @@ private static void CancelFlipLocked(FlipRequest request) request.FlipEvents = null; } } - else if (request.AheadPublishedAt != 0 && !request.GpuCompleted && request.GpuQueued && - _ports.TryGetValue(request.Handle, out var aheadPort)) - { - // Published ahead of the GPU: the guest was told, the GPU slot was still held. - aheadPort.GpuQueueCount = Math.Max(0, aheadPort.GpuQueueCount - 1); - } - - request.AheadPrevious = null; // Completed requests leave event-array ownership with the completion caller. request.Outcome = FlipOutcome.Cancelled; _flipRequests.Remove(request.RequestId); diff --git a/tests/SharpEmu.Libs.Tests/Gpu/Split/SplitHookTests.cs b/tests/SharpEmu.Libs.Tests/Gpu/Split/SplitHookTests.cs index d9a34ea7e..e1d52c3f9 100644 --- a/tests/SharpEmu.Libs.Tests/Gpu/Split/SplitHookTests.cs +++ b/tests/SharpEmu.Libs.Tests/Gpu/Split/SplitHookTests.cs @@ -310,8 +310,6 @@ public long NextFlipPresentTimestamp(ulong requestId, long timestamp) public void CompleteFlipOnGpu(ulong requestId) => Calls.Add($"gpu {requestId}"); - public void NoteFlipRecorded(ulong requestId) => Calls.Add($"recorded {requestId}"); - public void DiscardFlip(ulong requestId) => Calls.Add($"discard {requestId}"); public string GetApplicationTitleId() diff --git a/tests/SharpEmu.Libs.Tests/VideoOut/VideoOutFlipAheadTests.cs b/tests/SharpEmu.Libs.Tests/VideoOut/VideoOutFlipAheadTests.cs deleted file mode 100644 index 8b806cb8f..000000000 --- a/tests/SharpEmu.Libs.Tests/VideoOut/VideoOutFlipAheadTests.cs +++ /dev/null @@ -1,292 +0,0 @@ -// Copyright (C) 2026 SharpEmu Emulator Project -// SPDX-License-Identifier: GPL-2.0-or-later - -using System.Buffers.Binary; -using System.Diagnostics; -using SharpEmu.HLE; -using SharpEmu.Libs.Kernel; -using SharpEmu.Libs.Tests.Gpu.Scheduling; -using SharpEmu.Libs.VideoOut; -using Xunit; - -namespace SharpEmu.Libs.Tests.VideoOut; - -// SHARPEMU_FLIP_AHEAD: a flip the GPU host recorded (NoteFlipRecorded) is published to the guest -// once the flip before it really completed on the GPU; the request stays for the pacer and its -// real completion releases the GPU slot without publishing again. -[Collection(SchedulingStateCollection.Name)] -public sealed class VideoOutFlipAheadTests : IDisposable -{ - private const ulong MemoryBase = 0x1_0000_0000; - private const ulong StatusAddress = MemoryBase + 0x100; - private const ulong ScratchAddress = MemoryBase + 0x200; - private const ulong EventAddress = MemoryBase + 0x300; - private const ulong OutCountAddress = MemoryBase + 0x400; - private const ulong TimeoutAddress = MemoryBase + 0x480; - private const int TimedOut = unchecked((int)0x8002003C); - - private readonly FakeCpuMemory _memory = new(MemoryBase, 0x1000); - private readonly CpuContext _context; - private readonly int _handle; - private ulong _queue; - - public VideoOutFlipAheadTests() - { - _context = new CpuContext(_memory, Generation.Gen5); - _context[CpuRegister.Rdi] = 0; - _context[CpuRegister.Rsi] = 0; - _context[CpuRegister.Rdx] = 0; - _context[CpuRegister.Rcx] = 0; - _handle = VideoOutExports.VideoOutOpen(_context); - Assert.True(_handle > 0); - VideoOutExports.ResetFlipAheadForTests(enabled: true); - } - - public void Dispose() - { - if (_queue != 0) - { - _context[CpuRegister.Rdi] = _queue; - _ = KernelEventQueueCompatExports.KernelDeleteEqueue(_context); - } - - _context[CpuRegister.Rdi] = unchecked((ulong)_handle); - _ = VideoOutExports.VideoOutClose(_context); - VideoOutExports.ResetFlipAheadForTests(enabled: false); - } - - private ulong Reserve(long flipArg, bool gpuQueued = true) - { - Assert.Equal(0, VideoOutExports.TryReserveFlipRequest(_handle, -1, 2, flipArg, gpuQueued, out var requestId)); - return requestId; - } - - private (ulong Count, long FlipArg, int GpuQueue, int Pending) Status() - { - _context[CpuRegister.Rdi] = unchecked((ulong)_handle); - _context[CpuRegister.Rsi] = StatusAddress; - Assert.Equal(0, VideoOutExports.VideoOutGetFlipStatus(_context)); - Span status = stackalloc byte[0x40]; - Assert.True(_memory.TryRead(StatusAddress, status)); - return (BinaryPrimitives.ReadUInt64LittleEndian(status), - BinaryPrimitives.ReadInt64LittleEndian(status[0x18..]), - BinaryPrimitives.ReadInt32LittleEndian(status[0x30..]), - BinaryPrimitives.ReadInt32LittleEndian(status[0x34..])); - } - - private void AddFlipEvent() - { - _context[CpuRegister.Rdi] = ScratchAddress; - _context[CpuRegister.Rsi] = 0; - Assert.Equal(0, KernelEventQueueCompatExports.KernelCreateEqueue(_context)); - Assert.True(_context.TryReadUInt64(ScratchAddress, out _queue)); - _context[CpuRegister.Rdi] = _queue; - _context[CpuRegister.Rsi] = unchecked((ulong)_handle); - _context[CpuRegister.Rdx] = 0x55; - Assert.Equal(0, VideoOutExports.VideoOutAddFlipEvent(_context)); - } - - private int WaitOne(uint timeoutUsec) - { - Assert.True(_memory.TryWrite(TimeoutAddress, BitConverter.GetBytes(timeoutUsec))); - _context[CpuRegister.Rdi] = _queue; - _context[CpuRegister.Rsi] = EventAddress; - _context[CpuRegister.Rdx] = 1; - _context[CpuRegister.Rcx] = OutCountAddress; - _context[CpuRegister.R8] = TimeoutAddress; - return KernelEventQueueCompatExports.KernelWaitEqueue(_context); - } - - [Fact] - public void AheadPublicationPublishesOnceAndTheRealCompletionOnlyReleasesTheGpuSlot() - { - AddFlipEvent(); - var before = Status(); - var request = Reserve(101); - Assert.Equal(before.GpuQueue + 1, Status().GpuQueue); - - VideoOutExports.NoteFlipRecorded(request); - var ahead = Status(); - Assert.Equal(before.Count + 1, ahead.Count); - Assert.Equal(101, ahead.FlipArg); - Assert.Equal(before.Pending, ahead.Pending); - // The GPU still holds the flip. - Assert.Equal(before.GpuQueue + 1, ahead.GpuQueue); - Assert.Equal(0, WaitOne(100_000)); - // The pacer still has the request. - Assert.True(VideoOutExports.IsFlipPresentationPending(request)); - Assert.Equal(VideoOutExports.FlipOutcome.Pending, VideoOutExports.GetFlipOutcomeForTests(request)); - - VideoOutExports.CompleteFlipOnGpu(request); - VideoOutExports.CompleteFlipOnGpu(request); - var done = Status(); - Assert.Equal(ahead.Count, done.Count); - Assert.Equal(before.GpuQueue, done.GpuQueue); - Assert.Equal(TimedOut, WaitOne(1_000)); - Assert.True(VideoOutExports.CanPresentFlip(request, Stopwatch.GetTimestamp())); - - VideoOutExports.MarkFlipPresented(request); - Assert.Equal(ahead.Count, Status().Count); - Assert.Equal(TimedOut, WaitOne(1_000)); - Assert.Null(VideoOutExports.GetFlipOutcomeForTests(request)); - - var counters = VideoOutExports.PeekFlipAheadCountersForTests(); - Assert.Equal(1, counters.AtRecord); - Assert.Equal(0, counters.AtPrevious); - Assert.Equal(1, counters.LeadSamples); - } - - [Fact] - public void TheNextFlipWaitsForThePreviousRealCompletion() - { - var before = Status(); - var first = Reserve(111); - var second = Reserve(112); - - VideoOutExports.NoteFlipRecorded(first); - VideoOutExports.NoteFlipRecorded(second); - Assert.Equal(before.Count + 1, Status().Count); - Assert.Equal(111, Status().FlipArg); - - VideoOutExports.CompleteFlipOnGpu(first); - Assert.Equal(before.Count + 2, Status().Count); - Assert.Equal(112, Status().FlipArg); - - var counters = VideoOutExports.PeekFlipAheadCountersForTests(); - Assert.Equal(1, counters.AtRecord); - Assert.Equal(1, counters.AtPrevious); - - VideoOutExports.CompleteFlipOnGpu(second); - VideoOutExports.MarkFlipPresented(first); - VideoOutExports.MarkFlipPresented(second); - Assert.Equal(before.Count + 2, Status().Count); - Assert.Equal(before.GpuQueue, Status().GpuQueue); - Assert.Equal(before.Pending, Status().Pending); - Assert.Null(VideoOutExports.GetFlipOutcomeForTests(first)); - Assert.Null(VideoOutExports.GetFlipOutcomeForTests(second)); - } - - // A flip whose predecessor was not published ahead goes no later than today: when the - // predecessor is shown, never before it. - [Fact] - public void AFlipIsNeverPublishedBeforeTheOneBeforeIt() - { - var before = Status(); - var first = Reserve(121); - var second = Reserve(122); - - VideoOutExports.NoteFlipRecorded(second); - Assert.Equal(before.Count, Status().Count); - - VideoOutExports.CompleteFlipOnGpu(first); - Assert.Equal(before.Count, Status().Count); - - VideoOutExports.MarkFlipPresented(first); - Assert.Equal(before.Count + 2, Status().Count); - Assert.Equal(122, Status().FlipArg); - - VideoOutExports.CompleteFlipOnGpu(second); - VideoOutExports.MarkFlipPresented(second); - Assert.Equal(before.Count + 2, Status().Count); - Assert.Equal(before.GpuQueue, Status().GpuQueue); - } - - [Fact] - public void ThePacerStillPresentsAFlipPublishedAheadInOrder() - { - var before = Status(); - var first = Reserve(131); - VideoOutExports.NoteFlipRecorded(first); - var second = Reserve(132); - // The guest's next flip arrives before the first was shown; both stay with the pacer. - Assert.False(VideoOutExports.IsFlipDone(_handle, -1)); - Assert.True(VideoOutExports.IsFlipPresentationPending(first)); - Assert.True(VideoOutExports.IsFlipPresentationPending(second)); - - // Shown before its real completion: the request outlives the presentation until then. - VideoOutExports.MarkFlipPresented(first); - Assert.Equal(VideoOutExports.FlipOutcome.Presented, VideoOutExports.GetFlipOutcomeForTests(first)); - Assert.Equal(before.GpuQueue + 2, Status().GpuQueue); - VideoOutExports.CompleteFlipOnGpu(first); - Assert.Null(VideoOutExports.GetFlipOutcomeForTests(first)); - Assert.Equal(before.GpuQueue + 1, Status().GpuQueue); - - VideoOutExports.NoteFlipRecorded(second); - Assert.Equal(before.Count + 2, Status().Count); - VideoOutExports.CompleteFlipOnGpu(second); - VideoOutExports.DiscardFlip(second); - Assert.Equal(before.Count + 2, Status().Count); - Assert.True(VideoOutExports.IsFlipDone(_handle, -1)); - Assert.Null(VideoOutExports.GetFlipOutcomeForTests(second)); - Assert.Equal(before.GpuQueue, Status().GpuQueue); - Assert.Equal(before.Pending, Status().Pending); - } - - [Fact] - public void ALateNoticeAndCancelledOrCpuFlipsKeepTodaysTiming() - { - var before = Status(); - - // Real completion first: the notice is ignored and presentation publishes. - var late = Reserve(141); - VideoOutExports.CompleteFlipOnGpu(late); - VideoOutExports.NoteFlipRecorded(late); - Assert.Equal(before.Count, Status().Count); - VideoOutExports.MarkFlipPresented(late); - Assert.Equal(before.Count + 1, Status().Count); - - // Cancelled: nothing is published. - var cancelled = Reserve(142); - VideoOutExports.CancelFlip(cancelled); - VideoOutExports.NoteFlipRecorded(cancelled); - Assert.Equal(before.Count + 1, Status().Count); - - // A CPU flip is not GPU-queued: a notice for it is ignored. - var cpu = Reserve(143, gpuQueued: false); - VideoOutExports.NoteFlipRecorded(cpu); - Assert.Equal(before.Count + 1, Status().Count); - - // An unpublished CPU flip before a GPU flip holds the GPU flip back. - var gpu = Reserve(144); - VideoOutExports.NoteFlipRecorded(gpu); - Assert.Equal(before.Count + 1, Status().Count); - VideoOutExports.CompleteFlip(cpu); - Assert.Equal(before.Count + 3, Status().Count); - Assert.Equal(144, Status().FlipArg); - VideoOutExports.MarkFlipPresented(cpu); - - // Cancelling a flip published ahead gives its GPU slot back. - Assert.Equal(before.GpuQueue + 1, Status().GpuQueue); - VideoOutExports.CancelFlip(gpu); - Assert.Equal(before.GpuQueue, Status().GpuQueue); - Assert.Equal(before.Pending, Status().Pending); - Assert.Equal(before.Count + 3, Status().Count); - - Assert.Equal(3, VideoOutExports.PeekFlipAheadCountersForTests().LateNotices); - } - - [Fact] - public void WithTheSwitchOffTheNoticeChangesNothing() - { - VideoOutExports.ResetFlipAheadForTests(enabled: false); - AddFlipEvent(); - var before = Status(); - var request = Reserve(151); - - VideoOutExports.NoteFlipRecorded(request); - Assert.Equal(before.Count, Status().Count); - Assert.Equal(TimedOut, WaitOne(1_000)); - - VideoOutExports.CompleteFlipOnGpu(request); - Assert.Equal(before.Count, Status().Count); - Assert.Equal(before.GpuQueue, Status().GpuQueue); - Assert.Equal(before.Pending + 1, Status().Pending); - - VideoOutExports.MarkFlipPresented(request); - Assert.Equal(before.Count + 1, Status().Count); - Assert.Equal(before.Pending, Status().Pending); - Assert.Equal(0, WaitOne(100_000)); - Assert.Null(VideoOutExports.GetFlipOutcomeForTests(request)); - Assert.Equal(default, VideoOutExports.PeekFlipAheadCountersForTests()); - } -} From 6f5eef6f588ac6b3c68a2c542dd6c20ae4ae79c9 Mon Sep 17 00:00:00 2001 From: kuba Date: Mon, 16 Nov 2026 02:28:27 +0000 Subject: [PATCH 113/178] [Diag] CP reuse history: submissions, slices and landings in one ring, dumped before a command-stream fatal SHARPEMU_CP_HISTORY=reuse (default off): a 256 Ki-entry write history that also records each submission's admission and the slices that walk it, tags interpreter writes with their packet, and prints the fatal buffer's history plus the last 800 events (whole ring to SHARPEMU_CP_HISTORY_DUMP). With SHARPEMU_DCB_HASH=1 it also notes a DCB of <= 8 Ki dwords the guest changed between slices. Used to trace the early-label probe fatals in Demon's Souls. --- .../CommandProcessorWriteHistory.cs | 78 ++++++++++++++++++- .../Gpu/GpuCommands/CommandStreamQueue.cs | 39 +++++++++- ...GpuCommandInterpreter.StreamDiagnostics.cs | 6 ++ .../Gpu/GpuCommands/GpuCommandInterpreter.cs | 5 ++ .../Gpu/GpuCommands/GpuStreamDiagnostics.cs | 6 ++ 5 files changed, 129 insertions(+), 5 deletions(-) diff --git a/src/SharpEmu.Libs/Gpu/GpuCommands/CommandProcessorWriteHistory.cs b/src/SharpEmu.Libs/Gpu/GpuCommands/CommandProcessorWriteHistory.cs index 3a080bb96..bc03291f7 100644 --- a/src/SharpEmu.Libs/Gpu/GpuCommands/CommandProcessorWriteHistory.cs +++ b/src/SharpEmu.Libs/Gpu/GpuCommands/CommandProcessorWriteHistory.cs @@ -15,18 +15,26 @@ namespace SharpEmu.Libs.Gpu.GpuCommands; public static class CommandProcessorWriteHistory { public readonly record struct Entry( - long Ticks, int QueueId, ulong Address, int Size, ulong Value, string Kind, bool Deferred); + long Ticks, int QueueId, ulong Address, int Size, ulong Value, string Kind, bool Deferred, ulong Packet = 0); // Off by default: a record costs a timestamp, an interlocked add and, at some call sites, a // formatted string or a guest read made only for the record. Tests set it directly. public static bool Enabled { get; set; } = EnabledByEnvironment(Environment.GetEnvironmentVariable); internal static bool EnabledByEnvironment(Func getEnvironmentVariable) => - getEnvironmentVariable("SHARPEMU_CP_HISTORY") == "1" || + getEnvironmentVariable("SHARPEMU_CP_HISTORY") is "1" or "reuse" || !string.IsNullOrWhiteSpace(getEnvironmentVariable("SHARPEMU_CP_WATCH")) || getEnvironmentVariable("SHARPEMU_GPU_CLOBBER_DIAG") == "1"; - private const int Capacity = 4096; + // SHARPEMU_CP_HISTORY=reuse (diagnostic): a 64 Ki-entry history that also holds each submission's admission and the + // slices that walk it, every command-processor write tagged with the packet that made it, and is printed whole for + // the last ~800 events before a command-stream fatal: which landed write let the guest recycle the buffer being walked. + public static readonly bool Reuse = Environment.GetEnvironmentVariable("SHARPEMU_CP_HISTORY") == "reuse"; + + // The packet the interpreter on this thread is executing (reuse mode); a worker thread's records carry none. + [ThreadStatic] public static ulong CurrentPacket; + + private static readonly int Capacity = Reuse ? 1 << 18 : 4096; private static readonly Entry[] _entries = new Entry[Capacity]; private static long _next; @@ -62,7 +70,69 @@ public static void Record(int queueId, ulong address, int size, ulong value, str var slot = Interlocked.Increment(ref _next) - 1; _entries[(int)(slot % Capacity)] = new Entry( - System.Diagnostics.Stopwatch.GetTimestamp(), queueId, address, size, value, kind, deferred); + System.Diagnostics.Stopwatch.GetTimestamp(), queueId, address, size, value, kind, deferred, + Reuse && queueId >= 0 ? CurrentPacket : 0); + } + + /// Reuse mode: a submission admitted or a slice of it started or ended (packet = the walk position). + public static void RecordStream(string kind, int queueId, ulong buffer, uint dwords, ulong submissionId, ulong packet) + { + var slot = Interlocked.Increment(ref _next) - 1; + _entries[(int)(slot % Capacity)] = new Entry( + System.Diagnostics.Stopwatch.GetTimestamp(), queueId, buffer, (int)Math.Min(dwords * 4UL, int.MaxValue), + submissionId, kind, false, packet); + } + + /// Reuse mode: the history of one buffer and the last events before a fatal, oldest first. + public static void DumpForReuse(ulong buffer, uint dwords, int recent) + { + var now = System.Diagnostics.Stopwatch.GetTimestamp(); + var end = Interlocked.Read(ref _next); + var start = Math.Max(0, end - Capacity); + var bytes = (ulong)dwords * 4; + Console.Error.WriteLine($"[GPU][REUSE] buffer=0x{buffer:X16} dwords={dwords} events={end - start}"); + var shown = 0; + for (var index = start; index < end && shown < 400; index++) + { + var entry = _entries[(int)(index % Capacity)]; + if (entry.Size != 0 && entry.Address < buffer + bytes && buffer < entry.Address + (ulong)entry.Size) + { + Print("buf", entry, now); + shown++; + } + } + + for (var index = Math.Max(start, end - recent); index < end; index++) + { + Print("all", _entries[(int)(index % Capacity)], now); + } + + // SHARPEMU_CP_HISTORY_DUMP=: the whole history, for reading offline. + var path = Environment.GetEnvironmentVariable("SHARPEMU_CP_HISTORY_DUMP"); + if (!string.IsNullOrWhiteSpace(path)) + { + try + { + using var writer = new StreamWriter(path); + for (var index = start; index < end; index++) + { + writer.WriteLine(Format("all", _entries[(int)(index % Capacity)], now)); + } + + Console.Error.WriteLine($"[GPU][REUSE] history written: {path} events={end - start}"); + } + catch (Exception exception) + { + Console.Error.WriteLine($"[GPU][REUSE] history dump failed: {exception.Message}"); + } + } + + static void Print(string tag, in Entry entry, long now) => Console.Error.WriteLine(Format(tag, entry, now)); + + static string Format(string tag, in Entry entry, long now) => + $"[GPU][REUSE] {tag} t_ms={(entry.Ticks - now) * 1000.0 / System.Diagnostics.Stopwatch.Frequency:F3} " + + $"q={entry.QueueId} kind={entry.Kind} addr=0x{entry.Address:X} size={entry.Size} value=0x{entry.Value:X} " + + $"packet=0x{entry.Packet:X}"; } /// The recorded writes overlapping a range, oldest first. diff --git a/src/SharpEmu.Libs/Gpu/GpuCommands/CommandStreamQueue.cs b/src/SharpEmu.Libs/Gpu/GpuCommands/CommandStreamQueue.cs index 0cb578563..6311d92f1 100644 --- a/src/SharpEmu.Libs/Gpu/GpuCommands/CommandStreamQueue.cs +++ b/src/SharpEmu.Libs/Gpu/GpuCommands/CommandStreamQueue.cs @@ -140,7 +140,7 @@ public CommandStreamQueue(ICommandStreamHost host, int boundariesInFlight) { _host = host; _boundariesInFlight = Math.Max(0, boundariesInFlight); - if (GpuStreamDiagnostics.DcbHashEnabled || GpuClobberDiagnostics.Enabled) + if (GpuStreamDiagnostics.DcbHashEnabled || GpuClobberDiagnostics.Enabled || CommandProcessorWriteHistory.Reuse) { _beforeFatal = ReportBeforeFatal; } @@ -382,6 +382,14 @@ private void ReportBeforeFatal() { _fatalProcessor?.ReportClobber(submission, DescribeQueuesForClobber()); } + + if (CommandProcessorWriteHistory.Reuse) + { + Console.Error.WriteLine( + $"[GPU][REUSE] fatal queue={submission.QueueId} submission={submission.SubmissionId} " + + $"walk=0x{_fatalProcessor?.ReuseWalkPosition() ?? 0:X} {DescribeQueuesForClobber()}"); + CommandProcessorWriteHistory.DumpForReuse(submission.Address, submission.DwordCount, 800); + } } private string DescribeQueuesForClobber() @@ -497,6 +505,12 @@ submission.Kind is CommandSubmissionKind.Graphics or CommandSubmissionKind.Compu if (submission.Kind is not (CommandSubmissionKind.FlipPreparation or CommandSubmissionKind.FrameBoundary)) SubmissionFlowProfile.Record(SubmissionFlowProfile.EventKind.Enqueued, submission.QueueId, submission.SubmissionId, submission.Address, submission.DwordCount, _submissionCount); + if (CommandProcessorWriteHistory.Reuse) + { + CommandProcessorWriteHistory.RecordStream("enq", submission.QueueId, submission.Address, submission.DwordCount, + submission.SubmissionId, (ulong)submission.Kind); + } + if (DsTrace.Gpu && DsTrace.Armed) { DsTrace.Emit(DsEv.QENQ, (ulong)submission.QueueId, submission.SubmissionId, @@ -1858,10 +1872,33 @@ private bool RunSlice(CommandSubmission submission) GpuFatal.BeforeFatal = _beforeFatal; } + if (CommandProcessorWriteHistory.Reuse) + { + CommandProcessorWriteHistory.RecordStream(firstSlice ? "slice-first" : "slice-resume", submission.QueueId, + submission.Address, submission.DwordCount, submission.SubmissionId, processor.ReuseWalkPosition()); + if (!firstSlice && GpuStreamDiagnostics.ChangedSinceSubmit(_host, submission)) + { + CommandProcessorWriteHistory.RecordStream("rewritten-by-slice-start", submission.QueueId, submission.Address, + submission.DwordCount, submission.SubmissionId, 0); + } + } + try { complete = processor.Process(submission.Commands, submission.Address, submission.DwordCount, submission.CommandBytes, submission.RegisterTables) == SubmissionProgress.Complete; + if (CommandProcessorWriteHistory.Reuse && GpuStreamDiagnostics.ChangedSinceSubmit(_host, submission)) + { + CommandProcessorWriteHistory.RecordStream("rewritten-by-slice-end", submission.QueueId, submission.Address, + submission.DwordCount, submission.SubmissionId, 0); + } + + if (CommandProcessorWriteHistory.Reuse) + { + CommandProcessorWriteHistory.RecordStream( + complete ? "slice-done" : $"slice-stop:{submission.Commands.SuspendCondition.Kind}@0x{submission.Commands.SuspendCondition.Address:X}", + submission.QueueId, submission.Address, submission.DwordCount, submission.SubmissionId, processor.ReuseWalkPosition()); + } } finally { diff --git a/src/SharpEmu.Libs/Gpu/GpuCommands/GpuCommandInterpreter.StreamDiagnostics.cs b/src/SharpEmu.Libs/Gpu/GpuCommands/GpuCommandInterpreter.StreamDiagnostics.cs index 908587022..75e8f58ec 100644 --- a/src/SharpEmu.Libs/Gpu/GpuCommands/GpuCommandInterpreter.StreamDiagnostics.cs +++ b/src/SharpEmu.Libs/Gpu/GpuCommands/GpuCommandInterpreter.StreamDiagnostics.cs @@ -98,6 +98,12 @@ private void NoteClobberRegisterTable(ulong tableAddress, uint count) /// address that differs from the packet now, or a landed label at the packet's bytes, /// is the clobber; the same bad words at submit mean the guest wrote them. /// + /// Where the walk stands (SHARPEMU_CP_HISTORY=reuse): the next packet of the innermost buffer, 0 when idle. + internal ulong ReuseWalkPosition() => + _execution is { IsEmpty: false } execution + ? execution.Top.Address + ((ulong)execution.Top.Offset * sizeof(uint)) + : 0; + internal void ReportClobber(CommandSubmission submission, string queues) { var now = System.Diagnostics.Stopwatch.GetTimestamp(); diff --git a/src/SharpEmu.Libs/Gpu/GpuCommands/GpuCommandInterpreter.cs b/src/SharpEmu.Libs/Gpu/GpuCommands/GpuCommandInterpreter.cs index ca9600860..4a0fcbb02 100644 --- a/src/SharpEmu.Libs/Gpu/GpuCommands/GpuCommandInterpreter.cs +++ b/src/SharpEmu.Libs/Gpu/GpuCommands/GpuCommandInterpreter.cs @@ -611,6 +611,11 @@ private void RunPackets(PacketCursorStack execution, int stopDepth) } var packetAddress = cursor.Address + ((ulong)cursor.Offset * sizeof(uint)); + if (CommandProcessorWriteHistory.Reuse) + { + CommandProcessorWriteHistory.CurrentPacket = packetAddress; + } + if (CommandStreamQueue.TraceBoundaryWaits) { LastPacketAddress = packetAddress; diff --git a/src/SharpEmu.Libs/Gpu/GpuCommands/GpuStreamDiagnostics.cs b/src/SharpEmu.Libs/Gpu/GpuCommands/GpuStreamDiagnostics.cs index 0ff86d14b..cff90d60e 100644 --- a/src/SharpEmu.Libs/Gpu/GpuCommands/GpuStreamDiagnostics.cs +++ b/src/SharpEmu.Libs/Gpu/GpuCommands/GpuStreamDiagnostics.cs @@ -76,6 +76,12 @@ public static bool TryHashGuest(ICommandStreamHost host, ulong address, uint dwo return true; } + // SHARPEMU_CP_HISTORY=reuse: whether the guest has changed the submission's top-level DCB since submit. + // Small DCBs only (<= 8 Ki dwords): hashing every slice of a gameplay frame's large DCBs stalls the stream. + internal static bool ChangedSinceSubmit(ICommandStreamHost host, CommandSubmission submission) => + DcbHashEnabled && submission.DcbHashed && submission.DwordCount <= 8192 && + TryHashGuest(host, submission.Address, submission.DwordCount, out var now) && now != submission.DcbHash; + // Re-hashes the submission's top-level DCB and reports a difference from the submit-time hash. public static void Verify(ICommandStreamHost host, CommandSubmission submission, string at) { From 815e9803ee09c11af2f8ad107cbb4d5ee23e1b94 Mon Sep 17 00:00:00 2001 From: kuba Date: Mon, 16 Nov 2026 03:36:09 +0000 Subject: [PATCH 114/178] [Diag] Follow a refused alias-run reload: refusal reason, reads of the kept texels, how the mark ends alias_run_refresh_refused_by names the TryRefreshDirtyRun exit behind each refusal. The refusal marks the image; refused_stale_reads counts later sampled, storage, attachment-load, writeback and transfer reads of its texture (warned once per role and shape), refused_marks how marks end: whole rewrite with or without a read before it, partial write (mark kept), whole reload, release, and those still outstanding. Diagnostics only. --- .../V2/MetalCommandStream.cs | 2 +- .../V2/MetalImageCache.AliasTransitions.cs | 3 +- .../V2/MetalImageCache.DeferredRefresh.cs | 6 + .../V2/MetalImageCache.KernelFills.cs | 1 + .../V2/MetalImageCache.RefusedStale.cs | 316 ++++++++++++++++++ .../V2/MetalImageCache.Tracking.cs | 5 + .../SharpEmu.Gpu.Metal/V2/MetalImageCache.cs | 28 +- .../V2/MetalRenderHost.Images.cs | 2 +- .../V2/MetalRenderHost.Rendering.cs | 10 + 9 files changed, 368 insertions(+), 5 deletions(-) create mode 100644 src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.RefusedStale.cs diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalCommandStream.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalCommandStream.cs index 4ebfb6185..bddc15265 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalCommandStream.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalCommandStream.cs @@ -3010,7 +3010,7 @@ private void CaptureFlip(int handle, int index, ulong requestId, int flipMode, l // Before and after, so an upload that replaces a composited frame with the bytes // that were in guest memory before it shows up as the two differing. if (_dumpThisFlip) { DumpTexture(image.Texture, "flip-before-refresh"); } - _imageCache.RefreshImage(imageIdentifier); + _imageCache.RefreshImage(imageIdentifier, readRole: "present"); if (_dumpThisFlip) { DumpTexture(image.Texture, "flip-after-refresh"); } SampleFlipLuma(image.Texture); var texture = PresentationViewOf(imageIdentifier, image, in request); diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.AliasTransitions.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.AliasTransitions.cs index be1487295..dba64eeb9 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.AliasTransitions.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.AliasTransitions.cs @@ -74,7 +74,8 @@ internal string TakeAliasTransitionText() $"round-trip:{Mb(counts.RoundTripBytes)}] " + $"alias_moved_mib=[wb:{Mb(Interlocked.Exchange(ref _aliasMovedWritebackBytes, 0))}," + $"blit:{Mb(Interlocked.Exchange(ref _aliasMovedBlitBytes, 0))}] " + - $"alias_run_refresh_refused={Interlocked.Exchange(ref _aliasRunRefreshRefused, 0)} {TakeAliasRunText()} " + + $"alias_run_refresh_refused={Interlocked.Exchange(ref _aliasRunRefreshRefused, 0)} {TakeRefusedStaleText()} " + + $"{TakeAliasRunText()} " + $"layer_refresh_skipped=[{layerSkips.Layers},{Mb(layerSkips.Bytes)}] layer_stale_kept={TakeLayerStaleKept()} " + $"alias_subset_verify=[checked:{Interlocked.Exchange(ref _aliasSubsetVerified, 0)}," + $"mismatch:{Interlocked.Read(ref _aliasSubsetMismatches)},unverified:{Interlocked.Exchange(ref _aliasSubsetUnverified, 0)}] " + diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.DeferredRefresh.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.DeferredRefresh.cs index 895919215..cd88a1736 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.DeferredRefresh.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.DeferredRefresh.cs @@ -254,6 +254,12 @@ private void CompleteDeferredLocked(in DeferredRefresh entry, bool overwritten, { SynchronizeAliases(entry.Identifier, takesGpuOwnership: true, role: overwritten ? "rt-overwrite" : "rt-load"); } + if (overwritten) + { + // The pass overwrites what it binds; every texel only for a one-subresource image. + NoteRefusedRewrite(image, whole: SingleSubresource(image)); + } + if (overwritten && image.IsCpuDirty) { Interlocked.Increment(ref _refreshesSkipped); diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.KernelFills.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.KernelFills.cs index c1e2c4f25..6d25419dd 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.KernelFills.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.KernelFills.cs @@ -300,6 +300,7 @@ private bool TakeKernelWriteOwnershipLocked(ResourceSlotIdentifier imageIdentifi // owed to the texture, and guest memory is owed a writeback. Caller holds the lock. private void CompleteKernelWriteLocked(MetalCachedImage image) { + NoteRefusedRewrite(image, whole: true); image.RefreshComplete(); image.MarkGpuModified(); NoteLinearGpuWrite(image); diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.RefusedStale.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.RefusedStale.cs new file mode 100644 index 000000000..c3ed1cb6f --- /dev/null +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.RefusedStale.cs @@ -0,0 +1,316 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using System.Text; + +namespace SharpEmu.Gpu.Metal.V2; + +// Why TryRefreshDirtyRun gave up on a run, for alias_run_refresh_refused_by. +internal enum MetalRunRefusal : byte +{ + None, + SubRangeOff, + Stencil, + NoResidentRun, + OverHalf, + NoCoveringRun, + SourceInvalid, + NotMoved, +} + +// Diagnostics only: what becomes of the texels a GPU-written image keeps when RefreshFromGuestCore refuses its +// stale run (alias_run_refresh_refused). The refusal marks the image; the mark records every later read of the +// texture (sampled, storage, a render pass that loads it, a writeback that retiles it into guest memory) and ends +// at a whole rewrite (a clear, an elided load, a kernel or deferred pass that overwrites it), a whole reload or a +// release. A rewrite of one subresource of a multi-subresource image is counted on its own and keeps the mark. +internal sealed partial class MetalImageCache +{ + private static readonly string[] RunRefusalNames = + ["none", "subrange-off", "stencil", "no-run", "over-half", "no-cover", "source", "not-moved"]; + + private sealed class RefusedMark + { + public ulong Start, End; + public string Runs = string.Empty; + public MetalRunRefusal Reason; + public bool Read; + } + + private enum RefusedRead + { + Sampled, + SampledConservative, + Storage, + AttachmentLoad, + Writeback, + Transfer, + } + + // Set by TryRefreshDirtyRun before each false return; read by the refusal that follows it. + private MetalRunRefusal _runRefusal; + private readonly long[] _runRefusedBy = new long[RunRefusalNames.Length]; + private readonly Dictionary _refusedMarks = new(ReferenceEqualityComparer.Instance); + private int _refusedMarkCount; + private readonly long[] _refusedReads = new long[6]; + private long _refusedDeadWhole, _refusedReadThenWhole, _refusedPartialWrite, _refusedReloaded, _refusedReleased; + + private static bool SingleSubresource(MetalCachedImage image) => + image.Description.Resources.Levels <= 1 && image.Description.TransferLayers <= 1 && !image.Description.IsVolume; + + private MetalRunRefusal NoteRunRefusal(MetalCachedImage image) + { + var reason = _runRefusal; + _runRefusal = MetalRunRefusal.None; + Interlocked.Increment(ref _runRefusedBy[(int)reason]); + var builder = new StringBuilder(); + foreach (var (start, end) in image.StaleRuns) + { + builder.Append(builder.Length == 0 ? "" : ",").Append($"0x{start:X}..0x{end:X}"); + } + + lock (_refusedMarks) + { + if (!_refusedMarks.TryGetValue(image, out var mark)) + { + mark = new RefusedMark(); + _refusedMarks[image] = mark; + _refusedMarkCount = _refusedMarks.Count; + } + + mark.Start = image.DirtyStart; + mark.End = image.DirtyEnd; + mark.Runs = builder.ToString(); + mark.Reason = reason; + } + + return reason; + } + + // A read of a marked image's texture over [start, end) of its bytes (whole image when end is 0). + private void NoteRefusedRead(MetalCachedImage image, RefusedRead role, string detail, ulong start = 0, ulong end = 0) + { + if (Volatile.Read(ref _refusedMarkCount) == 0) + { + return; + } + + RefusedMark? mark; + lock (_refusedMarks) + { + if (!_refusedMarks.TryGetValue(image, out mark) || (end > start && (end <= mark.Start || start >= mark.End))) + { + return; + } + + mark.Read = true; + } + + Interlocked.Increment(ref _refusedReads[(int)role]); + ref readonly var description = ref image.Description; + MetalV2Diagnostics.WarnOnce( + $"refused-stale-read:{role}:{detail}:{description.PixelFormat}:{description.Extent.Width}x{description.Extent.Height}", + $"A GPU-written image whose stale run was refused a reload is read ({role} {detail}): " + + $"{description.PixelFormat} {description.Extent.Width}x{description.Extent.Height} " + + $"levels={description.Resources.Levels} layers={description.TransferLayers} " + + $"0x{description.Data.Address:X16}+0x{description.Data.Size:X} reason={RunRefusalNames[(int)mark.Reason]} " + + $"stale=[{mark.Runs}]."); + } + + // An alias-run writeback condition that reads the run out of the texture: noted, never changes the outcome. + private bool NoteRefusedReadThrough(MetalCachedImage image, ulong start, ulong end) + { + NoteRefusedRead(image, RefusedRead.Writeback, "alias-run", start, end); + return true; + } + + // A run reload over [start, end): the mark ends when it covers every byte the refusal left stale. + private void NoteRefusedReloadedRun(MetalCachedImage image, ulong start, ulong end) + { + if (Volatile.Read(ref _refusedMarkCount) == 0) + { + return; + } + + bool covers; + lock (_refusedMarks) + { + covers = _refusedMarks.TryGetValue(image, out var mark) && start <= mark.Start && end >= mark.End; + } + + if (covers) + { + NoteRefusedEnded(image, released: false); + } + } + + // A sampled bind: exact for a one-subresource image, counted conservatively (as reading the stale run) otherwise. + private void NoteRefusedSampled(MetalCachedImage image) + { + if (Volatile.Read(ref _refusedMarkCount) != 0) + { + NoteRefusedRead( + image, SingleSubresource(image) ? RefusedRead.Sampled : RefusedRead.SampledConservative, "bind"); + } + } + + // The GPU rewrote the image: whole (every texel of every subresource), or only part of it (the mark stays). + private void NoteRefusedRewrite(MetalCachedImage image, bool whole) + { + if (Volatile.Read(ref _refusedMarkCount) == 0) + { + return; + } + + lock (_refusedMarks) + { + if (!_refusedMarks.TryGetValue(image, out var mark)) + { + return; + } + + if (!whole) + { + _refusedPartialWrite++; + return; + } + + if (mark.Read) + { + _refusedReadThenWhole++; + } + else + { + _refusedDeadWhole++; + } + + _refusedMarks.Remove(image); + _refusedMarkCount = _refusedMarks.Count; + } + } + + // The texture took the guest's bytes again over all of the resident image, or the image went. + private void NoteRefusedEnded(MetalCachedImage image, bool released) + { + if (Volatile.Read(ref _refusedMarkCount) == 0) + { + return; + } + + lock (_refusedMarks) + { + if (!_refusedMarks.Remove(image)) + { + return; + } + + if (released) + { + _refusedReleased++; + } + else + { + _refusedReloaded++; + } + + _refusedMarkCount = _refusedMarks.Count; + } + } + + /// + /// A render pass opened over an image texture's subresource with its load action final: Load reads whatever + /// the texture holds; Clear or an elided load (DontCare under a full-cover draw) rewrites that subresource. + /// + internal void NoteRefusedAttachmentOpened(nint texture, uint level, uint layer, bool loads, bool depth) + { + if (texture == 0 || Volatile.Read(ref _refusedMarkCount) == 0) + { + return; + } + + MetalCachedImage? image = null; + lock (_refusedMarks) + { + foreach (var marked in _refusedMarks.Keys) + { + if (marked.Texture == texture) + { + image = marked; + break; + } + } + } + + if (image is null) + { + return; + } + + if (loads) + { + NoteRefusedRead(image, RefusedRead.AttachmentLoad, $"{(depth ? "depth" : "color")}-l{level}-s{layer}"); + } + else + { + NoteRefusedRewrite(image, whole: SingleSubresource(image)); + } + } + + private string TakeRefusedStaleText() + { + var by = new StringBuilder(); + for (var index = 1; index < _runRefusedBy.Length; index++) + { + by.Append(index == 1 ? "" : ",").Append(RunRefusalNames[index]).Append(':') + .Append(Interlocked.Exchange(ref _runRefusedBy[index], 0)); + } + + var none = Interlocked.Exchange(ref _runRefusedBy[0], 0); + if (none != 0) + { + by.Append(",unset:").Append(none); + } + + long deadWhole, readThenWhole, partial, reloaded, released; + int outstanding; + lock (_refusedMarks) + { + // An image disposed without passing ReleaseImage leaves no texture behind: its mark goes as released. + List? gone = null; + foreach (var marked in _refusedMarks.Keys) + { + if (marked.Texture == 0) + { + (gone ??= new List()).Add(marked); + } + } + + if (gone is not null) + { + foreach (var marked in gone) + { + _refusedMarks.Remove(marked); + _refusedReleased++; + } + } + + _refusedMarkCount = _refusedMarks.Count; + deadWhole = _refusedDeadWhole; + readThenWhole = _refusedReadThenWhole; + partial = _refusedPartialWrite; + reloaded = _refusedReloaded; + released = _refusedReleased; + _refusedDeadWhole = _refusedReadThenWhole = _refusedPartialWrite = _refusedReloaded = _refusedReleased = 0; + outstanding = _refusedMarks.Count; + } + + return $"alias_run_refresh_refused_by=[{by}] " + + $"refused_stale_reads=[sampled:{Interlocked.Exchange(ref _refusedReads[(int)RefusedRead.Sampled], 0)}," + + $"sampled-conservative:{Interlocked.Exchange(ref _refusedReads[(int)RefusedRead.SampledConservative], 0)}," + + $"storage:{Interlocked.Exchange(ref _refusedReads[(int)RefusedRead.Storage], 0)}," + + $"load:{Interlocked.Exchange(ref _refusedReads[(int)RefusedRead.AttachmentLoad], 0)}," + + $"writeback:{Interlocked.Exchange(ref _refusedReads[(int)RefusedRead.Writeback], 0)}," + + $"transfer:{Interlocked.Exchange(ref _refusedReads[(int)RefusedRead.Transfer], 0)}] " + + $"refused_marks=[dead-whole:{deadWhole},read-then-whole:{readThenWhole},partial-write:{partial}," + + $"reloaded:{reloaded},released:{released},outstanding:{outstanding}]"; + } +} diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.Tracking.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.Tracking.cs index 5158b2882..7f5c839bf 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.Tracking.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.Tracking.cs @@ -118,6 +118,8 @@ private void ReleaseImage(ResourceSlotIdentifier imageIdentifier, MetalImageRele image.NoteUse(_owner.CurrentSerial); } + NoteRefusedEnded(image, released: true); + if (image.Description.HasMetadata) { var metadataAddress = image.Description.Metadata.Range.Address; @@ -2490,6 +2492,7 @@ private void ClearImageRange( var width = Math.Max(image.Description.Extent.Width >> (int)range.BaseLevel, 1); var height = Math.Max(image.Description.Extent.Height >> (int)range.BaseLevel, 1); _owner.ClearTextureColor(texture, image.Shape.PixelFormat, in clearRange, width, height, in clear); + NoteRefusedRewrite(image, fullImage); image.RefreshComplete(); image.MarkGpuModified(); NoteLinearGpuWrite(image); @@ -2573,6 +2576,8 @@ public bool TryClearImageFromBuffer(ulong address, ulong size, uint packedClear) in color); } + // Every level and layer (the range above). + NoteRefusedRewrite(image, whole: true); image.RefreshComplete(); image.MarkGpuModified(); NoteLinearGpuWrite(image); diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.cs index b5adb2c7a..9a747f9a2 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.cs @@ -1363,6 +1363,7 @@ private bool TryHandOverAliasRun( } if (!other.IsPublished(start, end) && + NoteRefusedReadThrough(other, start, end) && !TryWriteBackRun(other, start, end, MetalWritebackCause.ImageOverlap, out declined)) { return false; @@ -1561,6 +1562,8 @@ private nint AcquireTextureViewLocked(ResourceSlotIdentifier imageIdentifier, in WatchImage(imageIdentifier); SynchronizeAliases(imageIdentifier, takesGpuOwnership: true, role: "storage"); RefreshFromGuest(image); + // Read or written is not known here: counted as a read (conservative). + NoteRefusedRead(image, RefusedRead.Storage, "bind"); image.Uses.Storage = true; image.MarkGpuModified(); NoteLinearGpuWrite(image); @@ -1591,6 +1594,7 @@ private nint AcquireTextureViewLocked(ResourceSlotIdentifier imageIdentifier, in WatchImage(imageIdentifier); SynchronizeAliases(imageIdentifier, takesGpuOwnership: false, role: "texture"); RefreshFromGuest(image); + NoteRefusedSampled(image); image.Uses.Texture = true; image.NoteUse(_owner.CurrentSerial); } @@ -2035,6 +2039,8 @@ public void MarkGpuWritten(ResourceSlotIdentifier imageIdentifier) // alone keeps whatever the texture held before. SynchronizeAliases(imageIdentifier, takesGpuOwnership: true); RefreshFromGuest(image); + // A resolve or depth copy writes one subresource, perhaps not all of it. + NoteRefusedRewrite(image, whole: false); image.MarkGpuModified(); NoteLinearGpuWrite(image); image.GpuWriteSerial = _owner.CurrentSerial; @@ -2057,7 +2063,7 @@ public void PrepareImageWrite(MetalCachedImage image) EnsureSparseBacked(image); } - public void RefreshImage(ResourceSlotIdentifier imageIdentifier) + public void RefreshImage(ResourceSlotIdentifier imageIdentifier, string? readRole = null) { using var held = _lock.Hold(); DrainDeferredRefreshesLocked(); @@ -2066,6 +2072,10 @@ public void RefreshImage(ResourceSlotIdentifier imageIdentifier) WatchImage(imageIdentifier); SynchronizeAliases(imageIdentifier, takesGpuOwnership: false); RefreshFromGuest(image); + if (readRole is not null) + { + NoteRefusedRead(image, RefusedRead.Transfer, readRole); + } } } @@ -2353,6 +2363,7 @@ private MetalAliasFallbackReason PublishAliasRange(MetalCachedImage other, ulong return MetalAliasFallbackReason.None; } + NoteRefusedRead(other, RefusedRead.Writeback, "alias-run", start, end); if (!TryWriteBackRun(other, start, end, MetalWritebackCause.ImageOverlap, out var failure)) { WriteBackToGuest(other, MetalWritebackCause.ImageOverlap); @@ -2971,12 +2982,15 @@ private void RefreshFromGuestCore(MetalCachedImage image) // stays stale rather than costing them - which serves the texture's older // bytes there, so it is counted (alias_run_refresh_refused) and warned about. Interlocked.Increment(ref _aliasRunRefreshRefused); + var refusal = NoteRunRefusal(image); MetalV2Diagnostics.WarnOnce( $"alias-run-refresh:{description.PixelFormat}:{description.Extent.Width}x{description.Extent.Height}", "A GPU-written image stale over an alias run could not reload just that run, so it keeps " + $"its texture there: {description.PixelFormat} {description.Extent.Width}x{description.Extent.Height} " + $"0x{description.Data.Address:X16}+0x{description.Data.Size:X} " + - $"dirty=0x{image.DirtyStart:X}..0x{image.DirtyEnd:X}."); + $"dirty=0x{image.DirtyStart:X}..0x{image.DirtyEnd:X} runs={image.StaleRuns.Length} " + + $"reason={RunRefusalNames[(int)refusal]} levels={description.Resources.Levels} " + + $"layers={description.TransferLayers}."); return; } @@ -3042,6 +3056,8 @@ private void RefreshFromGuestCore(MetalCachedImage image) { context.ProfileEncoded(ProfileLabel("upload", in description)); } + + NoteRefusedEnded(image, released: false); image.RefreshComplete(); Interlocked.Increment(ref _uploads); } @@ -3063,6 +3079,7 @@ private bool TryRefreshDirtyRun(MetalCachedImage image) var residentEnd = image.ResidentEnd; if (!SubRangeTransfersEnabled || description.HasStencil) { + _runRefusal = !SubRangeTransfersEnabled ? MetalRunRefusal.SubRangeOff : MetalRunRefusal.Stencil; return false; } @@ -3083,6 +3100,7 @@ private bool TryRefreshDirtyRun(MetalCachedImage image) var overHalf = stale > (residentEnd - residentStart) / 2; if (count == 0 || (overHalf && !NarrowRefreshPastHalf(image))) { + _runRefusal = count == 0 ? MetalRunRefusal.NoResidentRun : MetalRunRefusal.OverHalf; return false; } @@ -3090,6 +3108,7 @@ private bool TryRefreshDirtyRun(MetalCachedImage image) { if (!TryCoveringRun(in description, runs[index].Start, runs[index].End, out var start, out var end)) { + _runRefusal = MetalRunRefusal.NoCoveringRun; return false; } @@ -3137,6 +3156,7 @@ private bool TryRefreshDirtyRun(MetalCachedImage image) var source = ResolveUploadSource(description.Data.Address + start, end - start); if (!source.IsValid || source.Size < end - start) { + _runRefusal = MetalRunRefusal.SourceInvalid; NoteHoistedUse(image, anyHoisted); return false; } @@ -3152,6 +3172,7 @@ private bool TryRefreshDirtyRun(MetalCachedImage image) if (!moved) { // Nothing of this run reached the texture; the whole refresh decides what becomes of the image. + _runRefusal = MetalRunRefusal.NotMoved; NoteHoistedUse(image, anyHoisted); return false; } @@ -3175,6 +3196,8 @@ private bool TryRefreshDirtyRun(MetalCachedImage image) image.RefreshComplete(start, end); } + NoteRefusedReloadedRun(image, start, end); + Interlocked.Increment(ref _uploads); } @@ -3475,6 +3498,7 @@ private MetalWritebackOutcome WriteBackToGuest(MetalCachedImage image, MetalWrit } RefreshBeforeWriteback(image); + NoteRefusedRead(image, RefusedRead.Writeback, cause.ToString()); ref readonly var description = ref image.Description; if (TraceBigWritebackBytes != 0 && description.Data.Size >= TraceBigWritebackBytes) { diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Images.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Images.cs index 2469387b8..923205c30 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Images.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Images.cs @@ -374,7 +374,7 @@ public void CopyDepthStencilImage( GpuImageAspect aspects) { _ = aspects; - _imageCache.RefreshImage(source); + _imageCache.RefreshImage(source, readRole: "copy-source"); _imageCache.RefreshImage(destination); if (!_imageCache.TryGetImage(source, out var sourceImage) || !_imageCache.TryGetImage(destination, out var destinationImage) || diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Rendering.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Rendering.cs index 98bd4f3b1..7f61094f0 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Rendering.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Rendering.cs @@ -1121,6 +1121,13 @@ public void BeginRendering(in RenderingState state) NoteColorTargetRebuilt(index); } + if (index < _attachmentCount) + { + _imageCache.NoteRefusedAttachmentOpened( + _attachmentTextures[index], _attachmentRealLevels[index], _attachmentRealLayers[index], + loads: !clears && !elided, depth: false); + } + if (index < ownAttachments) { NoteColorTargetDrawn(index); @@ -1151,6 +1158,9 @@ public void BeginRendering(in RenderingState state) if (depthStencil.HasDepth && depthStencil.View.Handle != 0) { + _imageCache.NoteRefusedAttachmentOpened( + _depthAttachmentTexture, _depthAttachmentRealLevel, _depthAttachmentRealLayer, + loads: !depthStencil.DepthClear, depth: true); attached = true; var depth = MetalNative.Send(descriptor, SelDepthAttachment); MetalNative.SendVoid(depth, SelSetTexture, depthTexture); From 0ccb17fcbe049dd33633adbe91bb07148c17d69d Mon Sep 17 00:00:00 2001 From: kuba Date: Mon, 16 Nov 2026 03:42:36 +0000 Subject: [PATCH 115/178] [Diag] Refused alias-run reads: per layer, clean or after a write, by image A pass that clears or overwrites a layer of a one-level image takes that layer out of the refused run; every refusal starts the mark afresh. Reads are split into clean (no GPU write of unknown extent since the refusal: certain to see the kept texels) and after-write, and refused_reads_by_image names the image, role and count. Diagnostics only. --- .../V2/MetalImageCache.RefusedStale.cs | 210 ++++++++++++++---- .../SharpEmu.Gpu.Metal/V2/MetalImageCache.cs | 9 +- 2 files changed, 170 insertions(+), 49 deletions(-) diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.RefusedStale.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.RefusedStale.cs index c3ed1cb6f..4c5f1cdb4 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.RefusedStale.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.RefusedStale.cs @@ -19,21 +19,30 @@ internal enum MetalRunRefusal : byte } // Diagnostics only: what becomes of the texels a GPU-written image keeps when RefreshFromGuestCore refuses its -// stale run (alias_run_refresh_refused). The refusal marks the image; the mark records every later read of the -// texture (sampled, storage, a render pass that loads it, a writeback that retiles it into guest memory) and ends -// at a whole rewrite (a clear, an elided load, a kernel or deferred pass that overwrites it), a whole reload or a -// release. A rewrite of one subresource of a multi-subresource image is counted on its own and keeps the mark. +// stale run (alias_run_refresh_refused). The refusal marks the image (afresh at every refusal); the mark records +// every later read of the texture that reaches a layer of the refused run no pass has rewritten since (sampled, +// storage, a render pass that loads it, a writeback that retiles it into guest memory, a copy or present source), +// split by whether any GPU write of uncertain extent (a storage bind, a resolve, a partial clear) came between - +// "clean" reads are certain to see the kept texels. The mark ends at a whole rewrite (every layer cleared or +// overwritten by a pass, a whole clear or kernel fill), a whole reload or a release. internal sealed partial class MetalImageCache { private static readonly string[] RunRefusalNames = ["none", "subrange-off", "stencil", "no-run", "over-half", "no-cover", "source", "not-moved"]; + private static readonly string[] RefusedReadNames = + ["sampled", "sampled-conservative", "storage", "load", "writeback", "transfer"]; + private sealed class RefusedMark { public ulong Start, End; public string Runs = string.Empty; public MetalRunRefusal Reason; public bool Read; + // A GPU write of unknown extent since the refusal: later reads may see its texels, not the kept ones. + public bool Written; + // Layers (of a one-level image of at most 64 layers) a pass cleared or overwrote whole since the refusal. + public ulong LayersRewritten; } private enum RefusedRead @@ -51,12 +60,32 @@ private enum RefusedRead private readonly long[] _runRefusedBy = new long[RunRefusalNames.Length]; private readonly Dictionary _refusedMarks = new(ReferenceEqualityComparer.Instance); private int _refusedMarkCount; - private readonly long[] _refusedReads = new long[6]; + // [role * 2 + (written ? 1 : 0)] + private readonly long[] _refusedReads = new long[RefusedReadNames.Length * 2]; + private readonly Dictionary _refusedReadsByImage = new(StringComparer.Ordinal); private long _refusedDeadWhole, _refusedReadThenWhole, _refusedPartialWrite, _refusedReloaded, _refusedReleased; private static bool SingleSubresource(MetalCachedImage image) => image.Description.Resources.Levels <= 1 && image.Description.TransferLayers <= 1 && !image.Description.IsVolume; + // Layers are tracked one by one only for a one-level, non-volume image of at most 64 of them. + private static bool TracksLayers(MetalCachedImage image) => + image.Description.Resources.Levels <= 1 && !image.Description.IsVolume && image.Description.TransferLayers <= 64; + + private static ulong LayerMask(uint baseLayer, uint count) + { + if (count == 0 || baseLayer >= 64) + { + return 0; + } + + count = Math.Min(count, 64 - baseLayer); + var bits = count >= 64 ? ulong.MaxValue : (1UL << (int)count) - 1; + return bits << (int)baseLayer; + } + + private static ulong AllLayers(MetalCachedImage image) => LayerMask(0, Math.Max(image.Description.TransferLayers, 1)); + private MetalRunRefusal NoteRunRefusal(MetalCachedImage image) { var reason = _runRefusal; @@ -77,17 +106,55 @@ private MetalRunRefusal NoteRunRefusal(MetalCachedImage image) _refusedMarkCount = _refusedMarks.Count; } + // Every refusal finds the run stale again: what passes rewrote before it is stale once more. mark.Start = image.DirtyStart; mark.End = image.DirtyEnd; mark.Runs = builder.ToString(); mark.Reason = reason; + mark.Written = false; + mark.LayersRewritten = 0; } return reason; } - // A read of a marked image's texture over [start, end) of its bytes (whole image when end is 0). - private void NoteRefusedRead(MetalCachedImage image, RefusedRead role, string detail, ulong start = 0, ulong end = 0) + // The layers of the refused run a read of [start, end) of the image's bytes (all of them when end is 0) reaches. + private static ulong StaleLayersOf(MetalCachedImage image, RefusedMark mark, ulong start, ulong end) + { + if (end <= start) + { + start = 0; + end = image.Description.Data.Size; + } + + start = Math.Max(start, mark.Start); + end = Math.Min(end, mark.End); + if (end <= start) + { + return 0; + } + + if (!TracksLayers(image)) + { + return ulong.MaxValue; + } + + var layers = Math.Max(image.Description.TransferLayers, 1); + var layerBytes = image.Description.Data.Size / layers; + if (layerBytes == 0) + { + return ulong.MaxValue; + } + + var first = (uint)Math.Min(start / layerBytes, layers - 1); + var last = (uint)Math.Min((end - 1) / layerBytes, layers - 1); + return LayerMask(first, last - first + 1) & ~mark.LayersRewritten; + } + + // A read of a marked image's texture over [start, end) of its bytes (all of them when end is 0), or over the + // layers in layerMask when it is not 0. + private void NoteRefusedRead( + MetalCachedImage image, RefusedRead role, string detail, ulong start = 0, ulong end = 0, ulong layerMask = 0) { if (Volatile.Read(ref _refusedMarkCount) == 0) { @@ -95,25 +162,43 @@ private void NoteRefusedRead(MetalCachedImage image, RefusedRead role, string de } RefusedMark? mark; + bool written; lock (_refusedMarks) { - if (!_refusedMarks.TryGetValue(image, out mark) || (end > start && (end <= mark.Start || start >= mark.End))) + if (!_refusedMarks.TryGetValue(image, out mark)) + { + return; + } + + var stale = StaleLayersOf(image, mark, start, end); + if (layerMask != 0 && TracksLayers(image)) + { + stale &= layerMask; + } + + if (stale == 0) { return; } mark.Read = true; + written = mark.Written; + ref readonly var shape = ref image.Description; + var key = $"{shape.PixelFormat}/{shape.Extent.Width}x{shape.Extent.Height}x{shape.TransferLayers}" + + $"@{shape.Data.Address:X}:{RefusedReadNames[(int)role]}{(written ? "/after-write" : "")}"; + _refusedReadsByImage[key] = _refusedReadsByImage.GetValueOrDefault(key) + 1; } - Interlocked.Increment(ref _refusedReads[(int)role]); + Interlocked.Increment(ref _refusedReads[(int)role * 2 + (written ? 1 : 0)]); ref readonly var description = ref image.Description; MetalV2Diagnostics.WarnOnce( - $"refused-stale-read:{role}:{detail}:{description.PixelFormat}:{description.Extent.Width}x{description.Extent.Height}", - $"A GPU-written image whose stale run was refused a reload is read ({role} {detail}): " + + $"refused-stale-read:{role}:{written}:{detail}:{description.PixelFormat}:{description.Extent.Width}x{description.Extent.Height}", + $"A GPU-written image whose stale run was refused a reload is read ({role} {detail}" + + $"{(written ? ", after a GPU write of unknown extent" : ", no GPU write since")}): " + $"{description.PixelFormat} {description.Extent.Width}x{description.Extent.Height} " + $"levels={description.Resources.Levels} layers={description.TransferLayers} " + $"0x{description.Data.Address:X16}+0x{description.Data.Size:X} reason={RunRefusalNames[(int)mark.Reason]} " + - $"stale=[{mark.Runs}]."); + $"stale=[{mark.Runs}] rewritten-layers=0x{mark.LayersRewritten:X}."); } // An alias-run writeback condition that reads the run out of the texture: noted, never changes the outcome. @@ -143,17 +228,19 @@ private void NoteRefusedReloadedRun(MetalCachedImage image, ulong start, ulong e } } - // A sampled bind: exact for a one-subresource image, counted conservatively (as reading the stale run) otherwise. - private void NoteRefusedSampled(MetalCachedImage image) + // A sampled bind of a view's layers: exact by layer for a one-level image, conservative (the whole run) otherwise. + private void NoteRefusedSampled(MetalCachedImage image, uint baseLayer, uint layerCount) { if (Volatile.Read(ref _refusedMarkCount) != 0) { NoteRefusedRead( - image, SingleSubresource(image) ? RefusedRead.Sampled : RefusedRead.SampledConservative, "bind"); + image, TracksLayers(image) ? RefusedRead.Sampled : RefusedRead.SampledConservative, "bind", + layerMask: LayerMask(baseLayer, Math.Max(layerCount, 1))); } } - // The GPU rewrote the image: whole (every texel of every subresource), or only part of it (the mark stays). + // The GPU rewrote the image: whole (every texel of every subresource) ends the mark; a write of unknown or partial + // extent keeps it and makes later reads "after-write". private void NoteRefusedRewrite(MetalCachedImage image, bool whole) { if (Volatile.Read(ref _refusedMarkCount) == 0) @@ -171,21 +258,27 @@ private void NoteRefusedRewrite(MetalCachedImage image, bool whole) if (!whole) { _refusedPartialWrite++; + mark.Written = true; return; } - if (mark.Read) - { - _refusedReadThenWhole++; - } - else - { - _refusedDeadWhole++; - } + EndRewrittenLocked(image, mark); + } + } - _refusedMarks.Remove(image); - _refusedMarkCount = _refusedMarks.Count; + private void EndRewrittenLocked(MetalCachedImage image, RefusedMark mark) + { + if (mark.Read) + { + _refusedReadThenWhole++; } + else + { + _refusedDeadWhole++; + } + + _refusedMarks.Remove(image); + _refusedMarkCount = _refusedMarks.Count; } // The texture took the guest's bytes again over all of the resident image, or the image went. @@ -238,21 +331,40 @@ internal void NoteRefusedAttachmentOpened(nint texture, uint level, uint layer, break; } } - } - if (image is null) - { - return; - } + if (image is null) + { + return; + } - if (loads) - { - NoteRefusedRead(image, RefusedRead.AttachmentLoad, $"{(depth ? "depth" : "color")}-l{level}-s{layer}"); - } - else - { - NoteRefusedRewrite(image, whole: SingleSubresource(image)); + if (!loads) + { + var mark = _refusedMarks[image]; + if (TracksLayers(image) && level == 0) + { + mark.LayersRewritten |= LayerMask(layer, 1); + if ((mark.LayersRewritten & AllLayers(image)) == AllLayers(image)) + { + EndRewrittenLocked(image, mark); + } + else + { + _refusedPartialWrite++; + } + } + else + { + _refusedPartialWrite++; + mark.Written = true; + } + + return; + } } + + NoteRefusedRead( + image, RefusedRead.AttachmentLoad, $"{(depth ? "depth" : "color")}-l{level}-s{layer}", + layerMask: LayerMask(layer, 1)); } private string TakeRefusedStaleText() @@ -270,8 +382,17 @@ private string TakeRefusedStaleText() by.Append(",unset:").Append(none); } + var reads = new StringBuilder(); + for (var role = 0; role < RefusedReadNames.Length; role++) + { + reads.Append(role == 0 ? "" : ",").Append(RefusedReadNames[role]).Append(':') + .Append(Interlocked.Exchange(ref _refusedReads[role * 2], 0)).Append('/') + .Append(Interlocked.Exchange(ref _refusedReads[role * 2 + 1], 0)); + } + long deadWhole, readThenWhole, partial, reloaded, released; int outstanding; + string byImage; lock (_refusedMarks) { // An image disposed without passing ReleaseImage leaves no texture behind: its mark goes as released. @@ -301,16 +422,13 @@ private string TakeRefusedStaleText() released = _refusedReleased; _refusedDeadWhole = _refusedReadThenWhole = _refusedPartialWrite = _refusedReloaded = _refusedReleased = 0; outstanding = _refusedMarks.Count; + byImage = string.Join(',', _refusedReadsByImage.OrderBy(p => p.Key, StringComparer.Ordinal) + .Select(p => $"{p.Key}={p.Value}")); + _refusedReadsByImage.Clear(); } - return $"alias_run_refresh_refused_by=[{by}] " + - $"refused_stale_reads=[sampled:{Interlocked.Exchange(ref _refusedReads[(int)RefusedRead.Sampled], 0)}," + - $"sampled-conservative:{Interlocked.Exchange(ref _refusedReads[(int)RefusedRead.SampledConservative], 0)}," + - $"storage:{Interlocked.Exchange(ref _refusedReads[(int)RefusedRead.Storage], 0)}," + - $"load:{Interlocked.Exchange(ref _refusedReads[(int)RefusedRead.AttachmentLoad], 0)}," + - $"writeback:{Interlocked.Exchange(ref _refusedReads[(int)RefusedRead.Writeback], 0)}," + - $"transfer:{Interlocked.Exchange(ref _refusedReads[(int)RefusedRead.Transfer], 0)}] " + + return $"alias_run_refresh_refused_by=[{by}] refused_stale_reads(clean/after-write)=[{reads}] " + $"refused_marks=[dead-whole:{deadWhole},read-then-whole:{readThenWhole},partial-write:{partial}," + - $"reloaded:{reloaded},released:{released},outstanding:{outstanding}]"; + $"reloaded:{reloaded},released:{released},outstanding:{outstanding}] refused_reads_by_image=[{byImage}]"; } } diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.cs index 9a747f9a2..27ff2b715 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.cs @@ -1562,8 +1562,11 @@ private nint AcquireTextureViewLocked(ResourceSlotIdentifier imageIdentifier, in WatchImage(imageIdentifier); SynchronizeAliases(imageIdentifier, takesGpuOwnership: true, role: "storage"); RefreshFromGuest(image); - // Read or written is not known here: counted as a read (conservative). - NoteRefusedRead(image, RefusedRead.Storage, "bind"); + // Read or written is not known here: counted as a read (conservative), and as a write of unknown extent. + NoteRefusedRead( + image, RefusedRead.Storage, "bind", + layerMask: LayerMask(request.View.BaseLayer, Math.Max(request.View.LayerCount, 1))); + NoteRefusedRewrite(image, whole: false); image.Uses.Storage = true; image.MarkGpuModified(); NoteLinearGpuWrite(image); @@ -1594,7 +1597,7 @@ private nint AcquireTextureViewLocked(ResourceSlotIdentifier imageIdentifier, in WatchImage(imageIdentifier); SynchronizeAliases(imageIdentifier, takesGpuOwnership: false, role: "texture"); RefreshFromGuest(image); - NoteRefusedSampled(image); + NoteRefusedSampled(image, request.View.BaseLayer, request.View.LayerCount); image.Uses.Texture = true; image.NoteUse(_owner.CurrentSerial); } From ed653ff9e7563d1f308d3b31d596df42e4171fc3 Mon Sep 17 00:00:00 2001 From: kuba Date: Mon, 16 Nov 2026 04:05:37 +0000 Subject: [PATCH 116/178] [Metal] Reload a GPU-written image stale over all of its bytes, and write none of them back A GPU-written image whose stale runs cover its whole resident range was refused every reload: TryCoveringRun refuses a run that widens to the whole image (the caller is meant to go whole), and RefreshFromGuestCore refuses the whole upload for a GPU-written image. Its texture kept older texels; they were sampled and, at a release or flush, retiled over the bytes the alias had published (Demon's Souls: an RGBA16F 960x540 written back every frame, an RGBA8 960x540 bound and sampled, a D32 1024x1024x4 sampled during load-in; alias_run_refresh_refused ~45/2 s). Every path that leaves a GPU-written image stale (alias read/write publication, narrow hand-over, layout skip, device-subset copy, CPU and GPU buffer writes) means its newer bytes are in guest memory, or in an alias that SynchronizeAliases publishes before any acquire refreshes it - the invariant the run reload already relies on. So the whole resident range goes through TryRefreshDirtyRun as one run rather than through the whole-upload path: same ResolveUploadSource (staged ranges gathered behind pending GPU writes), same LandHeldCopies, and PreludeBlocks with whole=true, so an alias-caused reload is never hoisted ahead of the publication encoded before it and a device copy into the texture since its refresh orders before it. Afterwards the texture equals guest memory, so the image stops being GPU-modified; a writeback (whole or run) of such an image writes nothing and only clears it. Not covered, still a counted refusal: stencil-carrying images, a whole range past TransferPieceBytes (whole-large), sub-range transfers off. GPU-written images always hold level 0 on (MarkGpuModified), so the resident range is the whole image. SHARPEMU_METAL_V2_WHOLE_STALE_RELOAD=0 restores the refusal for an A/B. The device test that pinned the old overwrite now pins the corrected result, with the switch off reproducing the old one. --- docs/macos/configuration.md | 1 + .../V2/MetalImageCache.AliasTransitions.cs | 2 +- .../V2/MetalImageCache.RefusedStale.cs | 18 +++- .../V2/MetalImageCache.WholeStale.cs | 82 ++++++++++++++++ .../SharpEmu.Gpu.Metal/V2/MetalImageCache.cs | 43 +++++++- .../MetalImageAliasTests.RunSetHardening.cs | 28 ++++-- .../MetalImageAliasTests.WholeStale.cs | 97 +++++++++++++++++++ 7 files changed, 257 insertions(+), 14 deletions(-) create mode 100644 src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.WholeStale.cs create mode 100644 tests/SharpEmu.Gpu.Metal.Tests/MetalImageAliasTests.WholeStale.cs diff --git a/docs/macos/configuration.md b/docs/macos/configuration.md index 8920bbf6c..1ce39a3cb 100644 --- a/docs/macos/configuration.md +++ b/docs/macos/configuration.md @@ -50,6 +50,7 @@ them for measurements or to isolate a problem. | `SHARPEMU_METAL_V2_WINDOW_MB` | `1024` | Largest a window grows to hold one binding. 512 to 4096. | | `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_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`. | diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.AliasTransitions.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.AliasTransitions.cs index dba64eeb9..1a5099f82 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.AliasTransitions.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.AliasTransitions.cs @@ -74,7 +74,7 @@ internal string TakeAliasTransitionText() $"round-trip:{Mb(counts.RoundTripBytes)}] " + $"alias_moved_mib=[wb:{Mb(Interlocked.Exchange(ref _aliasMovedWritebackBytes, 0))}," + $"blit:{Mb(Interlocked.Exchange(ref _aliasMovedBlitBytes, 0))}] " + - $"alias_run_refresh_refused={Interlocked.Exchange(ref _aliasRunRefreshRefused, 0)} {TakeRefusedStaleText()} " + + $"alias_run_refresh_refused={Interlocked.Exchange(ref _aliasRunRefreshRefused, 0)} {TakeRefusedStaleText()} {TakeWholeStaleText()} " + $"{TakeAliasRunText()} " + $"layer_refresh_skipped=[{layerSkips.Layers},{Mb(layerSkips.Bytes)}] layer_stale_kept={TakeLayerStaleKept()} " + $"alias_subset_verify=[checked:{Interlocked.Exchange(ref _aliasSubsetVerified, 0)}," + diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.RefusedStale.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.RefusedStale.cs index 4c5f1cdb4..7294ae672 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.RefusedStale.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.RefusedStale.cs @@ -16,6 +16,7 @@ internal enum MetalRunRefusal : byte NoCoveringRun, SourceInvalid, NotMoved, + WholeTooLarge, } // Diagnostics only: what becomes of the texels a GPU-written image keeps when RefreshFromGuestCore refuses its @@ -28,7 +29,7 @@ internal enum MetalRunRefusal : byte internal sealed partial class MetalImageCache { private static readonly string[] RunRefusalNames = - ["none", "subrange-off", "stencil", "no-run", "over-half", "no-cover", "source", "not-moved"]; + ["none", "subrange-off", "stencil", "no-run", "over-half", "no-cover", "source", "not-moved", "whole-large"]; private static readonly string[] RefusedReadNames = ["sampled", "sampled-conservative", "storage", "load", "writeback", "transfer"]; @@ -65,6 +66,21 @@ private enum RefusedRead private readonly Dictionary _refusedReadsByImage = new(StringComparer.Ordinal); private long _refusedDeadWhole, _refusedReadThenWhole, _refusedPartialWrite, _refusedReloaded, _refusedReleased; + /// Test hook: refused-stale reads of every role, clean and after a write, not yet reported. + internal long RefusedStaleReads + { + get + { + long total = 0; + foreach (ref var count in _refusedReads.AsSpan()) + { + total += Interlocked.Read(ref count); + } + + return total; + } + } + private static bool SingleSubresource(MetalCachedImage image) => image.Description.Resources.Levels <= 1 && image.Description.TransferLayers <= 1 && !image.Description.IsVolume; diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.WholeStale.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.WholeStale.cs new file mode 100644 index 000000000..38455c5dd --- /dev/null +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.WholeStale.cs @@ -0,0 +1,82 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using SharpEmu.Libs.Gpu.Images; + +namespace SharpEmu.Gpu.Metal.V2; + +// A GPU-written image whose stale runs cover every byte it holds: guest memory (once the aliases that wrote them +// have published, as SynchronizeAliases does before every acquire's refresh) holds all of its bytes, and the texture +// owns none. TryRefreshDirtyRun used to refuse such a run for widening to the whole image, and RefreshFromGuestCore +// then refused the whole upload because the image is GPU-written (alias_run_refresh_refused), so the texture kept +// its older texels - sampled, and retiled back over the alias's bytes at its writeback. Now the run is the whole +// resident range, reloaded through the run path, and the image stops being GPU-modified; a writeback of such an +// image writes nothing. Not for a stencil-carrying image (its stencil plane is not in the runs: the refusal stays, +// logged and counted), nor past TransferPieceBytes (refused as whole-large), nor with sub-range transfers off. +// SHARPEMU_METAL_V2_WHOLE_STALE_RELOAD=0 restores the refusal, for an A/B. +internal sealed partial class MetalImageCache +{ + private static readonly bool WholeStaleReloadDefault = + Environment.GetEnvironmentVariable("SHARPEMU_METAL_V2_WHOLE_STALE_RELOAD") != "0"; + + /// Whether a GPU-written image stale over all of its bytes reloads them whole. + internal bool WholeStaleReloadEnabled { get; set; } = WholeStaleReloadDefault; + + private long _wholeStaleReloads, _wholeStaleWritebacksSkipped; + + /// Test hook: whole-stale reloads, and writebacks of whole-stale images that wrote nothing. + internal (long Reloads, long WritebacksSkipped) WholeStaleCounters => + (Interlocked.Read(ref _wholeStaleReloads), Interlocked.Read(ref _wholeStaleWritebacksSkipped)); + + // Whether the stale runs, clipped to [start, end), leave no byte of it out. + private static bool RunsCover(ReadOnlySpan<(ulong Start, ulong End)> runs, ulong start, ulong end) + { + var at = start; + foreach (var run in runs) + { + if (run.Start > at) + { + return false; + } + + at = Math.Max(at, run.End); + if (at >= end) + { + return true; + } + } + + return at >= end; + } + + private bool IsWholeStale(MetalCachedImage image, ReadOnlySpan<(ulong Start, ulong End)> runs, ulong start, ulong end) => + WholeStaleReloadEnabled && image.IsGpuModified && image.FirstLevel == 0 && !image.Description.HasStencil && + end > start && RunsCover(runs, start, end); + + // The texture now equals guest memory over every byte: it owes guest memory nothing, so a later release or alias + // publication must not retile it back. + private void NoteWholeStaleReloaded(MetalCachedImage image) + { + image.ClearGpuModified(); + Interlocked.Increment(ref _wholeStaleReloads); + } + + // A writeback of a GPU-written image stale over all of its bytes: guest memory is newer everywhere, so there is + // nothing to write. The image stays stale (its next use reloads it) and stops being GPU-modified. + private bool TrySkipWholeStaleWriteback(MetalCachedImage image) + { + if (!image.IsCpuDirty || ImageDescription.IsEmptyRange(image.Description.Data) || + !IsWholeStale(image, image.StaleRuns, 0, image.Description.Data.Size)) + { + return false; + } + + image.ClearGpuModified(); + Interlocked.Increment(ref _wholeStaleWritebacksSkipped); + return true; + } + + private string TakeWholeStaleText() => + $"whole_stale=[reloaded:{Interlocked.Exchange(ref _wholeStaleReloads, 0)}," + + $"writeback-skipped:{Interlocked.Exchange(ref _wholeStaleWritebacksSkipped, 0)}]"; +} diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.cs index 27ff2b715..afd8b038a 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.cs @@ -2393,6 +2393,13 @@ private bool TryWriteBackRun( return false; } + if (TrySkipWholeStaleWriteback(image)) + { + // Guest memory holds every byte of the run already; the image owns none of them. + failure = MetalAliasFallbackReason.None; + return true; + } + if (!TryCoveringRun(in description, start, end, out var aligned, out var alignedEnd)) { failure = MetalAliasFallbackReason.CoveringRunRefused; @@ -3101,7 +3108,23 @@ private bool TryRefreshDirtyRun(MetalCachedImage image) } var overHalf = stale > (residentEnd - residentStart) / 2; - if (count == 0 || (overHalf && !NarrowRefreshPastHalf(image))) + // A GPU-written image stale over every resident byte owes guest memory none of them: the run is the whole + // resident range, reloaded through this same path (its sources, its order after the publication that made + // the bytes) rather than refused for widening to the whole image (MetalImageCache.WholeStale.cs). + var wholeStale = count != 0 && IsWholeStale(image, runs[..count], residentStart, residentEnd); + if (wholeStale) + { + if (residentEnd - residentStart > TransferPieceBytes) + { + _runRefusal = MetalRunRefusal.WholeTooLarge; + return false; + } + + runs[0] = (residentStart, residentEnd); + count = 1; + } + + if (count == 0 || (overHalf && !NarrowRefreshPastHalf(image) && !wholeStale)) { _runRefusal = count == 0 ? MetalRunRefusal.NoResidentRun : MetalRunRefusal.OverHalf; return false; @@ -3109,6 +3132,11 @@ private bool TryRefreshDirtyRun(MetalCachedImage image) for (var index = 0; index < count; index++) { + if (wholeStale) + { + break; + } + if (!TryCoveringRun(in description, runs[index].Start, runs[index].End, out var start, out var end)) { _runRefusal = MetalRunRefusal.NoCoveringRun; @@ -3146,7 +3174,8 @@ private bool TryRefreshDirtyRun(MetalCachedImage image) var moved = false; if (_owner.UploadWouldEndRenderPass) { - var blocks = PreludeBlocks(image, start, end, whole: false); + // Whole: a device copy into the texture since its last refresh orders before the reload. + var blocks = PreludeBlocks(image, start, end, whole: wholeStale); hoisted = TryUploadInPrelude(image, start, end, ref blocks, out moved); anyHoisted |= hoisted; prelude = blocks; @@ -3216,6 +3245,11 @@ private bool TryRefreshDirtyRun(MetalCachedImage image) _runStats.NoteRefreshOverHalf(); } + if (wholeStale) + { + NoteWholeStaleReloaded(image); + } + return true; } @@ -3500,6 +3534,11 @@ private MetalWritebackOutcome WriteBackToGuest(MetalCachedImage image, MetalWrit return MetalWritebackOutcome.Complete; } + if (TrySkipWholeStaleWriteback(image)) + { + return MetalWritebackOutcome.Complete; + } + RefreshBeforeWriteback(image); NoteRefusedRead(image, RefusedRead.Writeback, cause.ToString()); ref readonly var description = ref image.Description; diff --git a/tests/SharpEmu.Gpu.Metal.Tests/MetalImageAliasTests.RunSetHardening.cs b/tests/SharpEmu.Gpu.Metal.Tests/MetalImageAliasTests.RunSetHardening.cs index 470989b9c..f0d28fe10 100644 --- a/tests/SharpEmu.Gpu.Metal.Tests/MetalImageAliasTests.RunSetHardening.cs +++ b/tests/SharpEmu.Gpu.Metal.Tests/MetalImageAliasTests.RunSetHardening.cs @@ -204,10 +204,12 @@ private sealed record DeviceAliasOutcome( // The D32 plane S is GPU-written; its R32 alias T (the target) is GPU-modified too and owns a published run (the // first half of it, as a partial writeback would leave). S is then written again - its texture gets new bytes, // guest memory still holds older ones - and T is sampled: the whole range is copied S -> T. - private static DeviceAliasOutcome RunDeviceAliasIntoPublishedTarget(bool deviceOn, bool targetOwns = true) + private static DeviceAliasOutcome RunDeviceAliasIntoPublishedTarget( + bool deviceOn, bool targetOwns = true, bool wholeStaleReload = true) { using var rig = new Rig(Device.Value); rig.Cache.DepthTwins = false; + rig.Cache.WholeStaleReloadEnabled = wholeStaleReload; rig.Cache.DeviceAliasPublishEnabled = deviceOn; var depthRequest = Depth32Request(ImageRole.DepthTarget); var textureRequest = Depth32Request(ImageRole.Texture); @@ -306,13 +308,14 @@ public void ADeviceCopyIntoAGpuModifiedTargetLeavesNoPublishedRunOverTheCopiedBy } } - // Looks wrong, pinned: with the device copy off, a target that is GPU-modified with older texels and a - // published first half, sampled over a source that is GPU-modified with newer ones (a state the cache's own - // transitions do not reach: taking GPU ownership clears the other image's), is not reloaded from the guest bytes - // the source was just published into, and its flush writes its older texels over them. The device copy leaves - // no such state (the test above). + // With the device copy off, a target that is GPU-modified with older texels and a published first half, sampled + // over a source that is GPU-modified with newer ones (a state the cache's own transitions do not reach: taking + // GPU ownership clears the other image's), is stale over all of itself once the sync publishes the source: it + // reloads the newer guest bytes whole and owes guest memory nothing, so its flush writes none of its older texels + // over them (MetalImageCache.WholeStale.cs). SHARPEMU_METAL_V2_WHOLE_STALE_RELOAD=0 pins the old refusal: no + // reload, and the flush puts the older texels back over the newer bytes. [Fact] - public void WithTheDeviceCopyOffATargetOwningOlderTexelsOverwritesTheNewerGuestBytesAtTheFlush() + public void WithTheDeviceCopyOffATargetOwningOlderTexelsReloadsTheNewerGuestBytesWholeInsteadOfOverwritingThem() { if (!RequireDevice()) return; var off = RunDeviceAliasIntoPublishedTarget(deviceOn: false); @@ -320,8 +323,13 @@ public void WithTheDeviceCopyOffATargetOwningOlderTexelsOverwritesTheNewerGuestB Assert.Equal(0, off.DevicePublishes); // Published into guest memory by the sync, before the flush. Assert.Equal(0, Differing(texels, off.Newer, off.GuestBeforeFlush)); - // Then the target's older texels replace them. - Assert.True(Differing(texels, off.Newer, off.GuestAfterFlush) > texels.Length / 2); - Assert.Equal(0, Differing(texels, off.Target, off.GuestAfterFlush)); + // The target took them whole, and the flush kept them. + Assert.Equal(0, Differing(texels, off.Newer, off.Target)); + Assert.Equal(0, Differing(texels, off.Newer, off.GuestAfterFlush)); + + var refused = RunDeviceAliasIntoPublishedTarget(deviceOn: false, wholeStaleReload: false); + Assert.Equal(0, Differing(texels, refused.Newer, refused.GuestBeforeFlush)); + Assert.True(Differing(texels, refused.Newer, refused.GuestAfterFlush) > texels.Length / 2); + Assert.Equal(0, Differing(texels, refused.Target, refused.GuestAfterFlush)); } } diff --git a/tests/SharpEmu.Gpu.Metal.Tests/MetalImageAliasTests.WholeStale.cs b/tests/SharpEmu.Gpu.Metal.Tests/MetalImageAliasTests.WholeStale.cs new file mode 100644 index 000000000..23e9648a2 --- /dev/null +++ b/tests/SharpEmu.Gpu.Metal.Tests/MetalImageAliasTests.WholeStale.cs @@ -0,0 +1,97 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using SharpEmu.Gpu.Metal.V2; +using SharpEmu.Libs.Gpu.Images; +using Xunit; + +namespace SharpEmu.Gpu.Metal.Tests; + +// A GPU-written image whose every byte an alias has since written (four aliases of whole rows, one after another, +// each taking its run while the large image stays GPU-modified): stale over all of itself, it owes guest memory +// nothing. Its read must give the aliases' bytes, whether or not a CPU read published everything first, and its +// writeback must not put its older texels back over theirs. SHARPEMU_METAL_V2_WHOLE_STALE_RELOAD=0 (the property +// here) restores the old refusal, which kept those older texels. +public sealed unsafe partial class MetalImageAliasTests +{ + private sealed record WholeStaleOutcome( + byte[] Large, byte[] Guest, byte[]? GuestBefore, bool GpuAfterRead, long Refused, long Reads, + (long Reloads, long WritebacksSkipped) Whole, string Text); + + private static readonly (ulong Offset, uint Rows)[] WholeCoverDraws = + [(0, AliasRows), (0x1000, AliasRows), (0x2000, AliasRows), (0x3000, AliasRows)]; + + private static WholeStaleOutcome WholeStaleRead(bool reloadWhole, bool cpuReadFirst) + { + using var rig = new Rig(Device.Value); + rig.Cache.AliasRunSetsEnabled = true; + rig.Cache.WholeStaleReloadEnabled = reloadWhole; + var (image, _, _) = GpuWrittenLarge(rig); + byte seed = 0x11; + foreach (var (offset, rows) in WholeCoverDraws) + { + DrawAlias(rig, offset, rows, seed); + seed += 0x22; + } + + var text = $"large_dirty={image.IsCpuDirty}:0x{image.DirtyStart:X}-0x{image.DirtyEnd:X} " + + $"runs={image.StaleRunCount} gpu={image.IsGpuModified}"; + byte[]? before = null; + if (cpuReadFirst) + { + rig.Cache.FlushGpuWrites(ImageAddress, LargeSize, MetalWritebackCause.HostRead); + rig.Harness.Submit(); + rig.Harness.Begin(); + before = rig.ReadGuest(ImageAddress, LargeSize); + } + + rig.Acquire(ImageAddress, LargeSide, ImageRole.Texture); + rig.Harness.Submit(); + rig.Harness.Begin(); + var large = ReadTexture(rig, image); + var gpuAfter = image.IsGpuModified; + rig.Cache.FlushGpuWrites(ImageAddress, LargeSize, MetalWritebackCause.HostRead); + rig.Harness.Submit(); + rig.Harness.Begin(); + return new WholeStaleOutcome( + large, rig.ReadGuest(ImageAddress, LargeSize), before, gpuAfter, rig.Cache.AliasRunRefreshRefused, + rig.Cache.RefusedStaleReads, rig.Cache.WholeStaleCounters, text + " " + rig.Cache.TakeAliasTransitionText()); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public void AGpuWrittenImageStaleOverAllOfItsBytesReadsTheAliasesBytes(bool cpuReadFirst) + { + if (!RequireDevice()) return; + var expected = ExpectedAfterDraws(WholeCoverDraws); + var on = WholeStaleRead(reloadWhole: true, cpuReadFirst); + var off = WholeStaleRead(reloadWhole: false, cpuReadFirst); + output.WriteLine($"on: refused={on.Refused} reads={on.Reads} whole={on.Whole} gpu_after={on.GpuAfterRead} {on.Text}"); + output.WriteLine($"off: refused={off.Refused} reads={off.Reads} whole={off.Whole} gpu_after={off.GpuAfterRead} {off.Text}"); + Assert.Contains("large_dirty=True:0x0-0x4000", on.Text); + Assert.Contains("gpu=True", on.Text); + Assert.Equal(expected, on.Large); + Assert.Equal(expected, on.Guest); + if (on.GuestBefore is not null) + { + Assert.Equal(expected, on.GuestBefore); + } + + Assert.False(on.GpuAfterRead); + Assert.Equal(0, on.Refused); + Assert.Equal(0, on.Reads); + // Read first: the reload. A CPU read first: the large image's writeback writes nothing (guest memory already + // holds the aliases' bytes), and the read then reloads it as an ordinary stale image. + Assert.Equal(cpuReadFirst ? (0L, 1L) : (1L, 0L), on.Whole); + // The switch off: the old refusal. Read first, it keeps the large texture's older texels; a CPU read first + // refuses inside the writeback, whose older texels the aliases' own writebacks then happen to cover again. + Assert.True(off.Refused >= 1); + if (!cpuReadFirst) + { + Assert.NotEqual(expected, off.Large); + } + + Assert.Equal((0L, 0L), off.Whole); + } +} From 4482f5115e1ce2baadbdc2cff68b734e7de8dc76 Mon Sep 17 00:00:00 2001 From: kuba Date: Mon, 16 Nov 2026 04:13:20 +0000 Subject: [PATCH 117/178] [Metal] Skip the covering-run loop for a whole-stale reload in the loop condition No behaviour change: the loop left at its first statement for a whole-stale run; the condition says so now. --- src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.cs | 8 ++------ 1 file changed, 2 insertions(+), 6 deletions(-) diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.cs index afd8b038a..9ef9e0a2a 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.cs @@ -3130,13 +3130,9 @@ private bool TryRefreshDirtyRun(MetalCachedImage image) return false; } - for (var index = 0; index < count; index++) + // A whole-stale run is the resident range already: nothing to widen, and no byte around it to protect. + for (var index = 0; index < count && !wholeStale; index++) { - if (wholeStale) - { - break; - } - if (!TryCoveringRun(in description, runs[index].Start, runs[index].End, out var start, out var end)) { _runRefusal = MetalRunRefusal.NoCoveringRun; From 5eb7f9b86358047bcee223f48e88db22e26dfe8d Mon Sep 17 00:00:00 2001 From: kuba Date: Mon, 16 Nov 2026 05:39:08 +0000 Subject: [PATCH 118/178] [Shader] Opt-in fused legacy multiply-add for compute and non-depth pixel programs V_MAD_F32, V_MADAK/MADMK_F32 and V_MAC_F32 round the product before the add on the guest, so they are emitted as two operations. The heavy Demon's Souls compute kernels are mostly V_MAD_F32 (137 of ~300 float ops in the light loop kernel, 334 in another, against 3-8 V_FMA each). SHARPEMU_MSL_FUSE_MAD=1 emits them as one fma() where no position or depth comes out of the program (compute without tessellation, pixel without depth export). Off by default because it is not bit-exact: with it on, Rdna2AluConformanceTests fails 70 of 1603 float forms, all MAD/MAC (half an ULP of the product in the sum; a result just under the smallest normal flushes to zero where the guest kept the addend). Unlike SHARPEMU_MSL_CONTRACT=1, which fails 165 forms including compares and invents NaNs, nothing else changes. Measured on Demon's Souls spawn-idle, same build: 77.8 ms median (fmad1) against 82.5 (fmadctl); GPU busy 58.9 against 63.3 ms per frame. CONTRACT=1 alone gave 77.4, so the fused MADs are where its gain came from. --- docs/macos/configuration.md | 1 + .../Gen5MslCodegenOptions.cs | 15 +++++++++-- .../Gen5MslTranslator.Alu.cs | 6 +++++ .../Gen5MslTranslator.cs | 6 +++++ .../Gen5MslFloatSemanticsTests.cs | 25 +++++++++++++++++-- 5 files changed, 49 insertions(+), 4 deletions(-) diff --git a/docs/macos/configuration.md b/docs/macos/configuration.md index 1ce39a3cb..d09a4ea15 100644 --- a/docs/macos/configuration.md +++ b/docs/macos/configuration.md @@ -102,6 +102,7 @@ undoes an optimization to isolate a miscompile: | `SHARPEMU_MSL_PERSISTENT_FENCES` | on | Leaves `S_WAITCNT` a no-op in persistent-thread kernels. | | `SHARPEMU_MSL_PERSISTENT_RECORDS` | on | Accesses multi-dword records of persistent-thread kernels dword by dword. | | `SHARPEMU_MSL_BYTEBIAS` | off | `1` keeps the per-buffer byte bias. | +| `SHARPEMU_MSL_FUSE_MAD` | off | `1` emits the guest's legacy multiply-adds (`V_MAD_F32`, `V_MAC_F32`) as one fused operation in compute programs and pixel programs without depth export. Faster (about 5 ms of an 82 ms Demon's Souls frame) but not bit-exact: the guest rounds the product first. | | `SHARPEMU_LOD_STATS` | guarded | `always` compiles the LOD statistics counters into every pixel pipeline. | ## Diagnostics diff --git a/src/SharpEmu.ShaderCompiler.Metal/Gen5MslCodegenOptions.cs b/src/SharpEmu.ShaderCompiler.Metal/Gen5MslCodegenOptions.cs index 10fd2a613..175ea007d 100644 --- a/src/SharpEmu.ShaderCompiler.Metal/Gen5MslCodegenOptions.cs +++ b/src/SharpEmu.ShaderCompiler.Metal/Gen5MslCodegenOptions.cs @@ -125,6 +125,15 @@ namespace SharpEmu.ShaderCompiler.Metal; /// reduction idiom reads lane 31 and lane 63 back to back. A pair whose second lane is not an /// inline constant keeps one exchange each. SHARPEMU_MSL_READLANE_FUSE=0 keeps one /// exchange per read. +/// Emit V_MAD_F32, V_MADAK/MADMK_F32 and V_MAC_F32 as one fused +/// multiply-add in compute programs and in pixel programs that export no depth. The guest rounds the +/// product before the add, so the fused result differs wherever that rounding mattered: by at most half +/// an ULP of the product in the sum, and a result just under the smallest normal flushes to zero where +/// the guest kept the addend (Rdna2AluConformanceTests fails the MAD/MAC forms with this on). It never +/// touches compares, NaN ordering or any other instruction, unlike . +/// Vertex, mesh and depth-exporting pixel programs, which feed positions and depth, never fuse. The heavy +/// Demon's Souls kernels are mostly V_MAD_F32, each two operations unfused: about 5 ms of an 82 ms frame. +/// Off by default; SHARPEMU_MSL_FUSE_MAD=1 turns it on. public sealed record Gen5MslCodegenOptions( bool StructuredControlFlow = true, bool RegisterAllocation = true, @@ -150,7 +159,8 @@ public sealed record Gen5MslCodegenOptions( bool FastReciprocals = true, bool ContractPixelCompute = false, bool RuntimeDwordFormatLoads = true, - bool FusedLaneReads = true) + bool FusedLaneReads = true, + bool FuseLegacyMultiplyAdd = false) { /// Diagnostic threshold for moving mesh LDS from threadgroup memory to the /// device pool, in bytes. The supported mesh allocation is at most 16 KiB. Zero @@ -337,7 +347,8 @@ public sealed record Gen5MslCodegenOptions( FastReciprocals: Environment.GetEnvironmentVariable("SHARPEMU_MSL_FASTRCP") != "0", ContractPixelCompute: Environment.GetEnvironmentVariable("SHARPEMU_MSL_CONTRACT") == "1", RuntimeDwordFormatLoads: Environment.GetEnvironmentVariable("SHARPEMU_MSL_RUNTIME_DWORD_FORMAT") != "0", - FusedLaneReads: Environment.GetEnvironmentVariable("SHARPEMU_MSL_READLANE_FUSE") != "0") + FusedLaneReads: Environment.GetEnvironmentVariable("SHARPEMU_MSL_READLANE_FUSE") != "0", + FuseLegacyMultiplyAdd: Environment.GetEnvironmentVariable("SHARPEMU_MSL_FUSE_MAD") == "1") { UnobservedAluWrites = Environment.GetEnvironmentVariable("SHARPEMU_MSL_UNOBSERVED_ALU") is "1" or "all", UnobservedAluAllStages = Environment.GetEnvironmentVariable("SHARPEMU_MSL_UNOBSERVED_ALU") == "all", diff --git a/src/SharpEmu.ShaderCompiler.Metal/Gen5MslTranslator.Alu.cs b/src/SharpEmu.ShaderCompiler.Metal/Gen5MslTranslator.Alu.cs index 5dcfb9dff..7f986e27e 100644 --- a/src/SharpEmu.ShaderCompiler.Metal/Gen5MslTranslator.Alu.cs +++ b/src/SharpEmu.ShaderCompiler.Metal/Gen5MslTranslator.Alu.cs @@ -276,6 +276,12 @@ private bool TryEmitVectorValue( // and V_MAC_F32 (gfx10.1) round the product before the add. "VFmaF32" or "VFmaAkF32" or "VFmaMkF32" => FloatResult(instruction, $"fma({F(instruction, 0)}, {F(instruction, 1)}, {F(instruction, 2)})"), + // Gen5MslCodegenOptions.FuseLegacyMultiplyAdd: one fused operation where no position or + // depth comes out of the program, at the price of the guest's product rounding. + "VMadF32" or "VMadAkF32" or "VMadMkF32" when FusesLegacyMultiplyAdd => + FloatResult(instruction, $"fma({F(instruction, 0)}, {F(instruction, 1)}, {F(instruction, 2)})"), + "VMacF32" when FusesLegacyMultiplyAdd => + FloatResult(instruction, $"fma({F(instruction, 0)}, {F(instruction, 1)}, as_type(v[{destination}]))"), "VMadF32" or "VMadAkF32" or "VMadMkF32" => EmitUnfusedMultiplyAdd(instruction, F(instruction, 2)), "VFmaF16" or "VFmaMkF16" or "VFmaAkF16" => Float16Result( instruction, diff --git a/src/SharpEmu.ShaderCompiler.Metal/Gen5MslTranslator.cs b/src/SharpEmu.ShaderCompiler.Metal/Gen5MslTranslator.cs index b4c077195..3f318b0e8 100644 --- a/src/SharpEmu.ShaderCompiler.Metal/Gen5MslTranslator.cs +++ b/src/SharpEmu.ShaderCompiler.Metal/Gen5MslTranslator.cs @@ -344,6 +344,12 @@ private string StepCapReportCode private HashSet? _entryMaskExports; private bool _validMaskFromExec; private readonly bool _pixelDepthExport; + + // Where a program may trade the guest's rounding for speed: nothing it computes is a position or a + // depth that another program must reproduce bit for bit. + private bool FusesLegacyMultiplyAdd => _options.FuseLegacyMultiplyAdd && + ((_stage == Gen5MslStage.Compute && _request.Tessellation is null) || + (_stage == Gen5MslStage.Pixel && !_pixelDepthExport)); private readonly bool _pixelStencilExport; private readonly bool _pixelSampleMaskExport; private readonly Gen5ColorExportFormat? _mrtzFormat; diff --git a/tests/SharpEmu.ShaderCompiler.Metal.Tests/Gen5MslFloatSemanticsTests.cs b/tests/SharpEmu.ShaderCompiler.Metal.Tests/Gen5MslFloatSemanticsTests.cs index 9704ed4e7..2fa48a101 100644 --- a/tests/SharpEmu.ShaderCompiler.Metal.Tests/Gen5MslFloatSemanticsTests.cs +++ b/tests/SharpEmu.ShaderCompiler.Metal.Tests/Gen5MslFloatSemanticsTests.cs @@ -135,6 +135,26 @@ public void MadFormsRoundTheProductBeforeTheAdd(string opcode, Gen5ShaderEncodin Assert.Equal(expected, Execute(shader)); } + // Gen5MslCodegenOptions.FuseLegacyMultiplyAdd trades that rounding for one operation in a compute + // program: the same inputs keep the 2^-46 a fused multiply-add keeps. Off, the default, it is lost. + [Theory] + [InlineData("VMadF32", Gen5ShaderEncoding.Vop3)] + [InlineData("VMacF32", Gen5ShaderEncoding.Vop2)] + public void FusedLegacyMultiplyAddKeepsTheProductUnrounded(string opcode, Gen5ShaderEncoding encoding) + { + const uint Factor = 0x3F800001u, Addend = 0xBF800002u; + var instruction = encoding == Gen5ShaderEncoding.Vop3 + ? Vop3(opcode, V012) + : new Gen5ShaderInstruction(28, encoding, opcode, [], [Gen5Operand.Vector(0), Gen5Operand.Vector(1)], [Gen5Operand.Vector(3)], null); + var options = Gen5MslCodegenOptions.FromEnvironment with { FuseLegacyMultiplyAdd = true }; + Assert.True(TryCompile([instruction], Factor, Factor, Addend, Addend, out var fused, out var error, options: options), error); + Assert.Contains("fma(", fused!.Source); + var unfused = Compile([instruction], Factor, Factor, Addend, Addend); + if (!RequireDevice()) return; + Assert.Equal(0x28800000u, Execute(fused)); + Assert.Equal(0u, Execute(unfused)); + } + // V_MAD_LEGACY_F32 flushes its denormal sources, so a denormal factor takes the DX9 zero // rule: denormal * inf + -0 is +0, not the NaN of 0 * inf. [Fact] @@ -283,7 +303,8 @@ private static Gen5MslShader Compile(Gen5ShaderInstruction[] inserted, uint a, u // v0 = a, v1 = b, v2 = c, v3 = old; the inserted instructions run before v3 is stored. private static bool TryCompile(Gen5ShaderInstruction[] inserted, uint a, uint b, uint c, uint old, out Gen5MslShader? shader, out string error, bool ieee = false, - uint floatMode = ShaderCompileRequest.DefaultFloatMode, bool dx10Clamp = true) + uint floatMode = ShaderCompileRequest.DefaultFloatMode, bool dx10Clamp = true, + Gen5MslCodegenOptions? options = null) { var fixture = new Gen5ComputeFixture("float-semantics", [ 0x7E0002FF, a, 0x7E0202FF, b, 0x7E0402FF, c, 0x7E0602FF, old, @@ -293,7 +314,7 @@ private static bool TryCompile(Gen5ShaderInstruction[] inserted, uint a, uint b, instructions.InsertRange(4, inserted); var request = Gen5ComputeFixtures.RequestOrThrow(program with { Instructions = instructions }, ShaderStage.Compute, ieeeMode: ieee, floatMode: floatMode, dx10Clamp: dx10Clamp); - var compiled = Gen5MslTranslator.TryCompileProgram(request, out var result, out error); + var compiled = Gen5MslTranslator.TryCompileProgram(request, out var result, out error, options); shader = compiled ? result : null; return compiled; } From 175736e35d53040ebe3a55c8377d20f49ddc1b01 Mon Sep 17 00:00:00 2001 From: kuba Date: Mon, 16 Nov 2026 07:01:34 +0000 Subject: [PATCH 119/178] [Diag] Frame-overlap stage 0: measure what overlapping the next frame would meet SHARPEMU_DIAG_FRAME_OVERLAP=1 (default off; off, every hook is a static readonly check). Measurement only: nothing rendered or guest-visible changes except the cost of the counters and of the sampled page watches. One [METAL-V2][OVERLAP-DIAG] line per stats window after [METAL-V2][PERF], and every 15th window [METAL-V2][OVERLAP-DIAG-TOP]. A frame is what the GPU worker records between two frame boundaries (FlushFrame); its last serial is the one committed there. Per window, p50/p90 or mean/max per frame: - read: inplace_pages/inplace_mb = distinct 4 KiB pages the frame's GPU work reads in place (census Binding marks: window-resolved bindings, and image upload sources); staged_mb = bytes copied into the ring at record time; upload_mb = upload sources; da_pages = pages of evaluated device-address ranges; da_enc planned/unplanned = encoders running device-address programs with every handle evaluated / not; huge_ranges = single ranges >256 MiB counted, not walked. - write: pages = distinct pages the GPU work writes; per origin mean pages (storage, binding, device_address, fill, copy, writeback, eop_label, unbounded from MetalGpuWriteRanges.Note before folding; cp_write, eop_dest from the packets); labels_in_cb = CP/EOP destinations inside the frame's own submitted command buffers. - refuse: frames with any of gds (EOP GDS stores), gpu_valued (clock labels), unbounded writes, atomic_in_ws (EOP atomic adds whose target the frame writes). - boundary: unfinished/blocked_frames = submissions still queued or running when the guest's frame boundary is admitted; drain_ms = admission to the walk reaching it. - overlap_ms = commit of the frame's last serial to its completion (the time an overlap could win); complete_to_admit_ms = completion to the guest's first submission of the next frame. - trap (every SHARPEMU_DIAG_FRAME_OVERLAP_EVERY frames, default 4): at completion the frame's in-place read pages get a write watch and its written pages a read watch (write watch where single-copy holds the read bit: skipped_read_watched), at most SHARPEMU_DIAG_FRAME_OVERLAP_MAX_PAGES (65536, cap_frames + a WARN line when hit); dropped at the next frame's boundary. Each page's first fault is counted and the page let go. rs_written = read-set pages the guest wrote (detach_mb = bytes of the bound ranges covering them); ws_read / ws_written = written pages the guest read or wrote (would wait); label_touched / cb_touched = of those, CP/EOP label pages and pages inside the frame's command buffers; da_only_written = pages reached only by evaluated device-address ranges that the guest wrote; managed = managed (HLE) writes to armed pages (they do not fault); first_fault_ms = completion to first fault; trap_before_submit_frames = first fault before the guest's first submission; late_arms = watches in place only after that first submission. Split: the GPU process holds the watches; the guest process now forwards read faults to it while the switch is on (RemoteImageStore.MarkCpuRead), write faults already go. Managed reads are not observable. --- src/SharpEmu.GpuSplit/RemoteImageStore.cs | 34 + src/SharpEmu.GpuSplit/SplitGpuHost.cs | 9 +- src/SharpEmu.GpuSplit/SplitGpuSession.cs | 7 + .../GpuMemory/FrameOverlapDiagnostic.cs | 1144 +++++++++++++++++ src/SharpEmu.HLE/GpuMemory/GuestGpuMemory.cs | 27 + .../Gpu/GpuCommands/CommandStreamQueue.cs | 40 + .../V2/MetalCommandStream.cs | 45 + .../V2/MetalGpuReferenceCensus.cs | 28 +- .../SharpEmu.Gpu.Metal/V2/MetalGpuWorker.cs | 5 + .../V2/MetalGpuWriteRanges.cs | 11 + .../V2/MetalRenderHost.Descriptors.cs | 17 + .../SharpEmu.Gpu.Metal/V2/MetalRenderHost.cs | 7 + .../HLE/FrameOverlapTrackerTests.cs | 196 +++ 13 files changed, 1565 insertions(+), 5 deletions(-) create mode 100644 src/SharpEmu.HLE/GpuMemory/FrameOverlapDiagnostic.cs create mode 100644 tests/SharpEmu.Libs.Tests/HLE/FrameOverlapTrackerTests.cs diff --git a/src/SharpEmu.GpuSplit/RemoteImageStore.cs b/src/SharpEmu.GpuSplit/RemoteImageStore.cs index 13c3eb309..bde7cc784 100644 --- a/src/SharpEmu.GpuSplit/RemoteImageStore.cs +++ b/src/SharpEmu.GpuSplit/RemoteImageStore.cs @@ -107,6 +107,35 @@ public bool MarkCpuWrite(ulong address, ulong size) return true; } + /// + /// SHARPEMU_DIAG_FRAME_OVERLAP=1 only: a read fault on a page the GPU process's diagnostic + /// read-watched. Same call as a write fault, from the signal handler: allocation-free, lock-free. + /// + [MethodImpl(MethodImplOptions.AggressiveOptimization)] + public bool MarkCpuRead(ulong address) + { + FaultRequest request; + request.Kind = (uint)FaultKind.Read; + request.Reserved = 0; + request.Address = address; + request.Size = 8; + HandledResponse response; + response.Handled = 0; + response.Reserved = 0; + response.RestorationVersion = 0; + var result = _calls.Call( + (uint)GpuRemoteSyncOpcode.Fault, + (byte*)&request, + sizeof(FaultRequest), + (byte*)&response, + sizeof(HandledResponse), + out var length, + out var status, + FaultTimeoutNanoseconds); + return result == SyncCallStatus.Completed && status == GpuSplitStatus.Ok && + length >= sizeof(HandledResponse) && response.Handled != 0; + } + public bool MarkPreciseCpuWrite(ulong address, ulong size) { if (!_state.MayInterest(address, size)) @@ -187,6 +216,11 @@ public void PrepareForSignalContext() RuntimeHelpers.PrepareMethod(typeof(RemoteImageStore).GetMethod(nameof(MarkCpuWrite))!.MethodHandle); // An address no store holds: the GPU process answers "not handled". _ = ((IGuestImageStore)this).MarkCpuWrite(0, 8); + if (FrameOverlapDiagnostic.Enabled) + { + RuntimeHelpers.PrepareMethod(typeof(RemoteImageStore).GetMethod(nameof(MarkCpuRead))!.MethodHandle); + _ = MarkCpuRead(0); + } } private bool SendLanded(ulong address, ulong size) => diff --git a/src/SharpEmu.GpuSplit/SplitGpuHost.cs b/src/SharpEmu.GpuSplit/SplitGpuHost.cs index 2978372cb..56a97e9df 100644 --- a/src/SharpEmu.GpuSplit/SplitGpuHost.cs +++ b/src/SharpEmu.GpuSplit/SplitGpuHost.cs @@ -509,9 +509,14 @@ public int HandleCall(uint opcode, ReadOnlySpan request, Span respon { var call = GpuSplitWire.Read(request); var memory = _memory!; - var handled = call.Kind == (uint)FaultKind.Write + // SHARPEMU_DIAG_FRAME_OVERLAP=1: a page the diagnostic armed is counted and let go + // first; the stores run as well only when another watcher still holds it. + var overlapBlocked = false; + var overlap = SharpEmu.HLE.GpuMemory.FrameOverlapDiagnostic.Enabled && + SharpEmu.HLE.GpuMemory.FrameOverlapDiagnostic.TryHandleFault((FaultKind)call.Kind, call.Address, out overlapBlocked); + var handled = (overlap && !overlapBlocked) || (call.Kind == (uint)FaultKind.Write ? memory.Images?.MarkCpuWrite(call.Address, call.Size) ?? false - : memory.Buffers?.DownloadToCpu(call.Address, call.Size) ?? false; + : memory.Buffers?.DownloadToCpu(call.Address, call.Size) ?? false) || overlap; // The store may have dropped watches: the guest retries the access as soon as // this answers, so their protections must be in place first. _ = WaitApplied(LastRequested); diff --git a/src/SharpEmu.GpuSplit/SplitGpuSession.cs b/src/SharpEmu.GpuSplit/SplitGpuSession.cs index 13d5b8077..79cb28b06 100644 --- a/src/SharpEmu.GpuSplit/SplitGpuSession.cs +++ b/src/SharpEmu.GpuSplit/SplitGpuSession.cs @@ -220,6 +220,12 @@ internal void Begin(string serviceName, HostVideoOptions? videoOptions, string t ImageStore.PrepareForSignalContext(); _memory.AttachStores(null, ImageStore); + if (FrameOverlapDiagnostic.Enabled) + { + // The GPU process holds the diagnostic's watches: its read faults go there (write faults already do). + FrameOverlapDiagnostic.RemoteReadFault = ImageStore.MarkCpuRead; + } + _memory.AttachGpuQueue(Relay, null); _memory.AttachSpanObserver(ImageStore); if (installGlobals) @@ -751,6 +757,7 @@ private void Detach() _memory.AttachSpanObserver(null); _memory.AttachGpuQueue(null, null); _memory.AttachStores(null, null); + FrameOverlapDiagnostic.RemoteReadFault = null; if (_globalsInstalled) { AgcBackendServices.ShaderHeaderObserver = null; diff --git a/src/SharpEmu.HLE/GpuMemory/FrameOverlapDiagnostic.cs b/src/SharpEmu.HLE/GpuMemory/FrameOverlapDiagnostic.cs new file mode 100644 index 000000000..f659ae226 --- /dev/null +++ b/src/SharpEmu.HLE/GpuMemory/FrameOverlapDiagnostic.cs @@ -0,0 +1,1144 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using System.Diagnostics; +using System.Globalization; +using System.Text; + +namespace SharpEmu.HLE.GpuMemory; + +/// How the GPU work of a frame reads a guest range. +public enum OverlapRead +{ + /// A binding resolved in a window: the GPU reads (or writes) the guest bytes when it runs. + InPlace, + + /// Copied into the upload ring at record time: the guest may rewrite it at once. + Staged, + + /// The guest source of an image upload, read from its window when the blit runs. + Upload, + + /// An evaluated range of a device-address program (the program may reach further). + DeviceAddress, +} + +/// +/// Who writes a guest range for the frame: the first eight are MetalGpuWriteOrigin in its order +/// (taken where each write is recorded, before any folding), then the command-processor and +/// end-of-pipe destinations as their packets are recorded. +/// +public enum OverlapWrite +{ + Storage, + Binding, + DeviceAddress, + Fill, + Copy, + Writeback, + EopLabel, + Unbounded, + CpWrite, + EopDestination, +} + +/// The page watches the diagnostic arms; a seam so the bookkeeping runs without a guard. +public interface IFrameOverlapWatches +{ + /// True when something already holds the page's one read-watch bit. + bool IsReadWatched(ulong page); + + void Add(ulong blockBase, in PageMask pages, bool blockReads); + + void Remove(ulong blockBase, in PageMask pages, bool blockReads); + + /// True when the page still stops this access after the diagnostic let go of it. + bool StillBlocks(ulong page, FaultKind kind); +} + +/// The watches of a real page guard. +public sealed class PageGuardOverlapWatches(PageGuard guard) : IFrameOverlapWatches +{ + // Only a read watch takes read access away (PageGuard.PageCounts.GetAllowedAccess). + public bool IsReadWatched(ulong page) => !guard.Allows(page, FaultKind.Read); + + public void Add(ulong blockBase, in PageMask pages, bool blockReads) => guard.AddWatchMask(blockBase, pages, blockReads); + + public void Remove(ulong blockBase, in PageMask pages, bool blockReads) => guard.RemoveWatchMask(blockBase, pages, blockReads); + + public bool StillBlocks(ulong page, FaultKind kind) => !guard.Allows(page, kind); +} + +/// +/// SHARPEMU_DIAG_FRAME_OVERLAP=1 (diagnostic, measurement only): what would stand in the way of +/// letting the guest build frame N+1 while the GPU still runs frame N. Per frame it records the +/// guest pages N's GPU work reads in place and writes, the time from "N walked and committed" to +/// "N completed" (the overlap there is to win), the submissions still unfinished at N's boundary, +/// the packets an overlapped frame would have to refuse, and, on every Kth frame, which of those +/// pages the guest touches while it builds N+1: it arms page watches when N completes and drops +/// them at N+1's boundary, counts each page's first fault and lets it go at once. Off, every +/// entry point is a static readonly check. +/// +public static class FrameOverlapDiagnostic +{ + public static readonly bool Enabled = + Environment.GetEnvironmentVariable("SHARPEMU_DIAG_FRAME_OVERLAP") == "1"; + + /// SHARPEMU_DIAG_FRAME_OVERLAP_EVERY: arm the watches on every Kth frame (default 4). + public static readonly int SampleEvery = + int.TryParse(Environment.GetEnvironmentVariable("SHARPEMU_DIAG_FRAME_OVERLAP_EVERY"), out var every) && every >= 1 ? every : 4; + + /// SHARPEMU_DIAG_FRAME_OVERLAP_MAX_PAGES: pages armed per sampled frame at most (default 65536 = 256 MiB). + public static readonly int MaxArmedPages = + int.TryParse(Environment.GetEnvironmentVariable("SHARPEMU_DIAG_FRAME_OVERLAP_MAX_PAGES"), out var cap) && cap >= 1 ? cap : 65536; + + /// SHARPEMU_DIAG_FRAME_OVERLAP_READS=0: arm write watches only (no read traps on the write set). + public static readonly bool ArmReads = + Environment.GetEnvironmentVariable("SHARPEMU_DIAG_FRAME_OVERLAP_READS") != "0"; + + private static FrameOverlapTracker? _tracker; + + /// + /// The guest process of the two-process split: its read faults go to the GPU process, which + /// holds the watches. Set only while the diagnostic is on; must not allocate or lock. + /// + public static Func? RemoteReadFault { get; set; } + + public static FrameOverlapTracker? Tracker => Volatile.Read(ref _tracker); + + /// The GPU host that records frames attaches its page guard (null detaches). + public static void Attach(PageGuard? guard, bool readWatchesShared) + { + if (!Enabled) + { + return; + } + + var previous = Interlocked.Exchange(ref _tracker, guard is null + ? null + : new FrameOverlapTracker(new PageGuardOverlapWatches(guard), Stopwatch.GetTimestamp, SampleEvery, MaxArmedPages, + ArmReads && !readWatchesShared, startThread: true)); + previous?.Dispose(); + if (guard is not null) + { + Console.Error.WriteLine( + $"[METAL-V2][OVERLAP-DIAG] on: every={SampleEvery} max_pages={MaxArmedPages} " + + $"read_watches={(ArmReads && !readWatchesShared ? 1 : 0)}" + + (ArmReads && readWatchesShared ? " (off: single-copy holds the read-watch bit)" : string.Empty)); + } + } + + public static void MarkGpuRead(ulong address, ulong size, OverlapRead kind) => Tracker?.MarkRead(address, size, kind); + + public static void NoteGpuWrite(ulong address, ulong size, OverlapWrite origin) => Tracker?.NoteWrite(address, size, origin); + + public static void NoteDeviceAddressProgram(bool planned) => Tracker?.NoteDeviceAddressProgram(planned); + + /// A packet an overlapped frame could not publish early: GDS end-of-pipe store or a GPU-valued (clock) label. + public static void NoteRefusal(bool gds) => Tracker?.NoteRefusal(gds); + + public static void NoteEndOfPipeAtomicAdd(ulong address) => Tracker?.NoteAtomicAdd(address); + + public static void OnAdmission(ulong address, ulong bytes) => Tracker?.OnAdmission(address, bytes); + + public static void OnBoundaryAdmitted(int unfinished, int blocked) => Tracker?.OnBoundaryAdmitted(unfinished, blocked); + + public static void OnBoundaryWalked() => Tracker?.OnBoundaryWalked(); + + public static void OnFrameCommitted(ulong lastSerial) => Tracker?.OnFrameCommitted(lastSerial); + + public static void OnCompleted(ulong serial) => Tracker?.OnCompleted(serial); + + public static void NoteManagedWrite(ulong address, ulong size) => Tracker?.NoteManagedWrite(address, size); + + /// + /// A fault on a page the diagnostic armed: counted and released. + /// says another watcher still stops the access, whose own path must then run as well. + /// + public static bool TryHandleFault(FaultKind kind, ulong address, out bool stillBlocked) + { + stillBlocked = false; + return Tracker is { } tracker && tracker.TryHandleFault(kind, address, out stillBlocked); + } + + public static string? TakeWindowLine() => Tracker?.TakeWindowLine(); +} + +/// The guest pages of one frame, one bit per 4 KiB page in 4 MiB blocks. +internal sealed class OverlapPageSet +{ + private const int BlockShift = 22; + private const int PageShift = 12; + private const int WordsPerBlock = TrackerLayout.PagesPerBlock / 64; + private readonly Dictionary _blocks = new(); + + public long Count { get; private set; } + + public IEnumerable> Blocks => _blocks; + + /// Sets the pages of the range; returns how many were new. + public long Add(ulong address, ulong size) + { + if (size == 0 || size > ulong.MaxValue - address) + { + return 0; + } + + long added = 0; + var first = address >> PageShift; + var last = (address + size - 1) >> PageShift; + for (var page = first; page <= last; page++) + { + var block = page >> (BlockShift - PageShift); + if (!_blocks.TryGetValue(block, out var words)) + { + words = new ulong[WordsPerBlock]; + _blocks.Add(block, words); + } + + var index = (int)(page & ((1UL << (BlockShift - PageShift)) - 1)); + var bit = 1UL << (index & 63); + if ((words[index >> 6] & bit) == 0) + { + words[index >> 6] |= bit; + added++; + } + } + + Count += added; + return added; + } + + /// The block's page bits (block = address >> 22), or null when none is set. + public ulong[]? Words(ulong block) => _blocks.TryGetValue(block, out var words) ? words : null; + + public bool Contains(ulong address) + { + var page = address >> PageShift; + if (!_blocks.TryGetValue(page >> (BlockShift - PageShift), out var words)) + { + return false; + } + + var index = (int)(page & ((1UL << (BlockShift - PageShift)) - 1)); + return (words[index >> 6] & (1UL << (index & 63))) != 0; + } + + public bool ContainsAny(ulong address, ulong size) + { + if (size == 0 || size > ulong.MaxValue - address) + { + return false; + } + + for (var page = address & ~0xFFFUL; page < address + size; page += 0x1000) + { + if (Contains(page)) + { + return true; + } + } + + return false; + } +} + +/// The state of the diagnostic; separate from the static switch so a test can drive it. +public sealed class FrameOverlapTracker : IDisposable +{ + // A single range above this is counted, not walked page by page (a whole window or table). + internal const ulong HugeRangeBytes = 256UL << 20; + private const ulong PageBytes = TrackerLayout.PageBytes; + private const int OriginCount = (int)OverlapWrite.EopDestination + 1; + private static readonly string[] OriginNames = + ["storage", "binding", "device_address", "fill", "copy", "writeback", "eop_label", "unbounded", "cp_write", "eop_dest"]; + + // Page flags of an armed frame. + private const byte InRead = 1; + private const byte InWrite = 2; + private const byte DeviceAddressOnly = 4; + private const byte InCommandBuffer = 8; + private const byte ReadArmed = 16; + private const byte Armed = 32; + private const byte ManagedSeen = 64; + + private readonly IFrameOverlapWatches _watches; + private readonly Func _clock; + private readonly int _sampleEvery; + private readonly int _maxArmedPages; + private readonly bool _armReads; + private readonly object _gate = new(); + private readonly object _watchGate = new(); + private readonly Queue<(bool Arm, Frame Frame)> _requests = new(); + private readonly Thread? _thread; + private bool _stopping; + + // Recording side (worker). + private Frame _recording; + private long _recordedFrames; + + // Admission side (guest threads, under the command stream's lock). + private Admission _admitting = new(); + private readonly Dictionary _admissions = new(); + private long _admittedFrames; + + // Committed, not yet finalized, oldest first. + private readonly List _inFlight = new(); + private ulong _completedSerial; + + // The frame whose pages are armed. + private Frame? _armed; + + private readonly Window _window = new(); + private readonly Dictionary _topDetach = new(); + private readonly Dictionary _topWaits = new(); + private long _windows; + + public FrameOverlapTracker(IFrameOverlapWatches watches, Func clock, int sampleEvery, int maxArmedPages, bool armReads, bool startThread) + { + _watches = watches; + _clock = clock; + _sampleEvery = Math.Max(1, sampleEvery); + _maxArmedPages = Math.Max(1, maxArmedPages); + _armReads = armReads; + _recording = new Frame(0); + if (startThread) + { + _thread = new Thread(Run) { IsBackground = true, Name = "SharpEmu overlap diagnostic" }; + _thread.Start(); + } + } + + internal sealed class Frame(long index) + { + public readonly long Index = index; + public readonly OverlapPageSet ReadInPlace = new(); + public readonly OverlapPageSet Staged = new(); + public readonly OverlapPageSet DeviceAddress = new(); + public readonly OverlapPageSet Written = new(); + public readonly OverlapPageSet[] ByOrigin = Enumerable.Range(0, OriginCount).Select(_ => new OverlapPageSet()).ToArray(); + public readonly long[] OriginBytes = new long[OriginCount]; + public readonly List<(ulong Address, ulong Size)> ReadRanges = new(); + public readonly List Labels = new(); + public readonly List AtomicTargets = new(); + public long InPlaceBytes, StagedBytes, UploadBytes, DeviceAddressBytes, HugeRanges; + public int DaPlanned, DaUnplanned, GdsStores, GpuValued, Unbounded; + public ulong LastSerial; + public long CommittedTicks, CompletedTicks, FirstAdmitTicks, ArmStartTicks, ArmedTicks, FirstFaultTicks; + public bool Sampled, Finalized; + + // Trap results (under the watch gate). + public readonly Dictionary Pages = new(); + public readonly OverlapPageSet ReadWrittenPages = new(); + public int ArmedPages, ReadArmedPages, SkippedReadWatched, CapSkipped; + public int ReadSetWritten, WriteSetRead, WriteSetWritten, LabelTouched, CommandBufferTouched, DeviceAddressOnlyWritten, ManagedRead, ManagedWrite; + } + + private sealed class Admission + { + public readonly List<(ulong Address, ulong Bytes)> Submissions = new(); + public long BoundaryTicks, WalkedTicks; + public int Unfinished, Blocked; + } + + private sealed class Window + { + public int Frames, Sampled, CapFrames, UnfinishedFrames, BlockedFrames, RefusedFrames, TrapBeforeSubmitFrames, WriteSetReadFrames, LateArms; + public readonly List InPlacePages = new(), InPlaceMb = new(), StagedMb = new(), UploadMb = new(), DaPages = new(), + WrittenPages = new(), LabelsInCb = new(), DrainMs = new(), OverlapMs = new(), CompleteToAdmitMs = new(), ArmMs = new(), + ArmedPages = new(), RsWritten = new(), DetachMb = new(), WsRead = new(), WsWritten = new(), LabelTouched = new(), CbTouched = new(), + DaOnly = new(), Managed = new(), FirstFaultMs = new(); + public readonly double[] OriginPages = new double[OriginCount]; + public long DaPlanned, DaUnplanned, Gds, GpuValued, Unbounded, AtomicInWrites, Huge, Skipped, Faults; + } + + // ---- recording side ----------------------------------------------------------------- + + public void MarkRead(ulong address, ulong size, OverlapRead kind) + { + if (size == 0 || size > ulong.MaxValue - address) + { + return; + } + + lock (_gate) + { + var frame = _recording; + if (size > HugeRangeBytes) + { + frame.HugeRanges++; + return; + } + + switch (kind) + { + case OverlapRead.Staged: + frame.StagedBytes += (long)size; + frame.Staged.Add(address, size); + break; + case OverlapRead.DeviceAddress: + frame.DeviceAddressBytes += (long)size; + frame.DeviceAddress.Add(address, size); + break; + default: + if (kind == OverlapRead.Upload) + { + frame.UploadBytes += (long)size; + } + + frame.InPlaceBytes += (long)size; + frame.ReadInPlace.Add(address, size); + frame.ReadRanges.Add((address, size)); + break; + } + } + } + + public void NoteWrite(ulong address, ulong size, OverlapWrite origin) + { + lock (_gate) + { + var frame = _recording; + if (origin == OverlapWrite.Unbounded) + { + frame.Unbounded++; + return; + } + + if (size == 0 || size > ulong.MaxValue - address) + { + return; + } + + if (size > HugeRangeBytes) + { + frame.HugeRanges++; + return; + } + + frame.OriginBytes[(int)origin] += (long)size; + frame.ByOrigin[(int)origin].Add(address, size); + frame.Written.Add(address, size); + if (origin is OverlapWrite.CpWrite or OverlapWrite.EopDestination) + { + frame.Labels.Add(address); + } + } + } + + public void NoteDeviceAddressProgram(bool planned) + { + lock (_gate) + { + if (planned) _recording.DaPlanned++; + else _recording.DaUnplanned++; + } + } + + public void NoteRefusal(bool gds) + { + lock (_gate) + { + if (gds) _recording.GdsStores++; + else _recording.GpuValued++; + } + } + + public void NoteAtomicAdd(ulong address) + { + lock (_gate) + { + _recording.AtomicTargets.Add(address); + } + } + + /// The worker committed everything the frame recorded; finishes it. + public void OnFrameCommitted(ulong lastSerial) + { + var now = _clock(); + lock (_gate) + { + var frame = _recording; + frame.LastSerial = lastSerial; + frame.CommittedTicks = now; + frame.Sampled = frame.Index % _sampleEvery == 0; + _inFlight.Add(frame); + _recording = new Frame(++_recordedFrames); + CompleteLocked(now); + } + } + + public void OnCompleted(ulong serial) + { + if (serial <= Volatile.Read(ref _completedSerial)) + { + return; + } + + var now = _clock(); + lock (_gate) + { + if (serial <= _completedSerial) + { + return; + } + + _completedSerial = serial; + CompleteLocked(now); + } + } + + private void CompleteLocked(long now) + { + foreach (var frame in _inFlight) + { + if (frame.CompletedTicks != 0 || frame.LastSerial > _completedSerial) + { + continue; + } + + frame.CompletedTicks = now; + if (frame.Sampled) + { + Post(arm: true, frame); + } + } + } + + // ---- admission side ----------------------------------------------------------------- + + public void OnAdmission(ulong address, ulong bytes) + { + var now = _clock(); + lock (_gate) + { + _admitting.Submissions.Add((address, bytes)); + foreach (var frame in _inFlight) + { + if (frame.CompletedTicks != 0 && frame.FirstAdmitTicks == 0) + { + frame.FirstAdmitTicks = now; + } + } + } + } + + /// The guest ended a frame (its boundary was admitted) with these submissions still to walk. + public void OnBoundaryAdmitted(int unfinished, int blocked) + { + var now = _clock(); + lock (_gate) + { + var admission = _admitting; + admission.BoundaryTicks = now; + admission.Unfinished = unfinished; + admission.Blocked = blocked; + _admissions[_admittedFrames] = admission; + _admissions.Remove(_admittedFrames - 8); + _admittedFrames++; + _admitting = new Admission(); + + // The frames that completed before this boundary: the guest's build of the next one is over. + for (var index = 0; index < _inFlight.Count;) + { + var frame = _inFlight[index]; + if (frame.CompletedTicks != 0 && frame.CompletedTicks <= now && frame.Index < _admittedFrames - 1) + { + _inFlight.RemoveAt(index); + Post(arm: false, frame); + continue; + } + + index++; + } + } + } + + /// The command stream reached the boundary: everything admitted before it has been walked. + public void OnBoundaryWalked() + { + var now = _clock(); + lock (_gate) + { + // The oldest admitted boundary not yet walked. + foreach (var pair in _admissions.OrderBy(pair => pair.Key)) + { + if (pair.Value.WalkedTicks == 0) + { + pair.Value.WalkedTicks = now; + break; + } + } + } + } + + // ---- arming ------------------------------------------------------------------------- + + private void Post(bool arm, Frame frame) + { + if (_thread is null) + { + // Synchronous (tests): run it after the caller's lock is released by queueing and draining. + _requests.Enqueue((arm, frame)); + return; + } + + lock (_requests) + { + _requests.Enqueue((arm, frame)); + Monitor.Pulse(_requests); + } + } + + /// Runs the queued arm and disarm requests on the calling thread (tests, no thread). + internal void DrainRequests() + { + while (true) + { + (bool Arm, Frame Frame) request; + lock (_gate) + { + if (_requests.Count == 0) + { + return; + } + + request = _requests.Dequeue(); + } + + Process(request.Arm, request.Frame); + } + } + + private void Run() + { + while (true) + { + (bool Arm, Frame Frame) request; + lock (_requests) + { + while (_requests.Count == 0 && !_stopping) + { + Monitor.Wait(_requests); + } + + if (_stopping) + { + return; + } + + request = _requests.Dequeue(); + } + + try + { + Process(request.Arm, request.Frame); + } + catch (Exception exception) + { + Console.Error.WriteLine($"[METAL-V2][OVERLAP-DIAG][ERROR] {(request.Arm ? "arm" : "disarm")} frame {request.Frame.Index}: {exception}"); + } + } + } + + private void Process(bool arm, Frame frame) + { + if (arm) + { + if (Volatile.Read(ref _armed) is { } previous) + { + // A frame armed past the next frame's completion: no boundary came between. + Disarm(previous); + } + + Arm(frame); + return; + } + + if (ReferenceEquals(Volatile.Read(ref _armed), frame)) + { + Disarm(frame); + } + + FinalizeFrame(frame); + } + + internal void Arm(Frame frame) + { + frame.ArmStartTicks = _clock(); + Admission? admission; + lock (_gate) + { + _admissions.TryGetValue(frame.Index, out admission); + } + + var submissions = admission?.Submissions.ToArray() ?? []; + var blocks = new SortedSet(); + foreach (var set in new[] { frame.ReadInPlace, frame.DeviceAddress, frame.Written }) + { + foreach (var pair in set.Blocks) + { + blocks.Add(pair.Key); + } + } + + lock (_watchGate) + { + Volatile.Write(ref _armed, frame); + foreach (var block in blocks) + { + var blockBase = block << 22; + var writeMask = default(PageMask); + var readMask = default(PageMask); + var anyWrite = false; + var anyRead = false; + var readWords = frame.ReadInPlace.Words(block); + var writtenWords = frame.Written.Words(block); + var deviceWords = frame.DeviceAddress.Words(block); + for (var index = 0; index < TrackerLayout.PagesPerBlock; index++) + { + var word = index >> 6; + var bit = 1UL << (index & 63); + byte flags = 0; + if (readWords is not null && (readWords[word] & bit) != 0) flags |= InRead; + if (writtenWords is not null && (writtenWords[word] & bit) != 0) flags |= InWrite; + if ((flags & InRead) == 0 && deviceWords is not null && (deviceWords[word] & bit) != 0) flags |= DeviceAddressOnly; + if (flags == 0) + { + continue; + } + + var page = blockBase + (ulong)index * PageBytes; + if ((flags & InWrite) != 0 && InSubmissions(submissions, page)) + { + flags |= InCommandBuffer; + } + + if (frame.ArmedPages >= _maxArmedPages) + { + frame.CapSkipped++; + continue; + } + + var reads = (flags & InWrite) != 0 && _armReads; + if (reads && _watches.IsReadWatched(page)) + { + frame.SkippedReadWatched++; + reads = false; + } + + if (reads) + { + readMask.Set(index); + anyRead = true; + flags |= ReadArmed; + frame.ReadArmedPages++; + } + else + { + writeMask.Set(index); + anyWrite = true; + } + + frame.Pages[page] = (byte)(flags | Armed); + frame.ArmedPages++; + } + + if (anyWrite) _watches.Add(blockBase, writeMask, blockReads: false); + if (anyRead) _watches.Add(blockBase, readMask, blockReads: true); + } + + frame.ArmedTicks = _clock(); + } + + if (frame.CapSkipped != 0) + { + Console.Error.WriteLine( + $"[METAL-V2][OVERLAP-DIAG][WARN] frame {frame.Index}: page cap {_maxArmedPages} hit, {frame.CapSkipped} pages not armed " + + "(SHARPEMU_DIAG_FRAME_OVERLAP_MAX_PAGES)"); + } + } + + private static bool InSubmissions((ulong Address, ulong Bytes)[] submissions, ulong page) + { + foreach (var submission in submissions) + { + if (page < submission.Address + submission.Bytes && submission.Address < page + PageBytes) + { + return true; + } + } + + return false; + } + + internal void Disarm(Frame frame) + { + lock (_watchGate) + { + var byBlock = new Dictionary<(ulong Block, bool Reads), PageMask>(); + foreach (var pair in frame.Pages) + { + if ((pair.Value & Armed) == 0) + { + continue; + } + + var key = (pair.Key & ~(TrackerLayout.BlockBytes - 1), (pair.Value & ReadArmed) != 0); + byBlock.TryGetValue(key, out var mask); + mask.Set((int)((pair.Key & (TrackerLayout.BlockBytes - 1)) / PageBytes)); + byBlock[key] = mask; + } + + foreach (var pair in byBlock) + { + var mask = pair.Value; + _watches.Remove(pair.Key.Block, mask, pair.Key.Reads); + } + + foreach (var page in frame.Pages.Keys.ToArray()) + { + frame.Pages[page] = (byte)(frame.Pages[page] & ~Armed); + } + + if (ReferenceEquals(_armed, frame)) + { + Volatile.Write(ref _armed, null); + } + } + } + + public bool TryHandleFault(FaultKind kind, ulong address, out bool stillBlocked) + { + stillBlocked = false; + if (Volatile.Read(ref _armed) is null) + { + return false; + } + + var page = address & ~(PageBytes - 1); + lock (_watchGate) + { + if (_armed is not { } frame || !frame.Pages.TryGetValue(page, out var flags) || (flags & Armed) == 0) + { + return false; + } + + var reads = (flags & ReadArmed) != 0; + var mask = default(PageMask); + mask.Set((int)((page & (TrackerLayout.BlockBytes - 1)) / PageBytes)); + frame.Pages[page] = (byte)(flags & ~Armed); + Count(frame, page, flags, write: kind != FaultKind.Read); + _watches.Remove(page & ~(TrackerLayout.BlockBytes - 1), mask, reads); + stillBlocked = _watches.StillBlocks(page, kind); + return true; + } + } + + /// A managed (HLE) write the GPU process heard of: it does not fault, so it is counted here. + public void NoteManagedWrite(ulong address, ulong size) + { + if (Volatile.Read(ref _armed) is null || size == 0 || size > ulong.MaxValue - address) + { + return; + } + + lock (_watchGate) + { + if (_armed is not { } frame) + { + return; + } + + var end = address + size; + var pages = 0; + for (var page = address & ~(PageBytes - 1); page < end && pages < 4096; page += PageBytes, pages++) + { + if (frame.Pages.TryGetValue(page, out var flags) && (flags & ManagedSeen) == 0) + { + frame.Pages[page] = (byte)(flags | ManagedSeen); + if ((flags & InWrite) != 0) frame.ManagedWrite++; + else frame.ManagedRead++; + } + } + } + } + + private void Count(Frame frame, ulong page, byte flags, bool write) + { + if (frame.FirstFaultTicks == 0) + { + frame.FirstFaultTicks = _clock(); + } + + if ((flags & InWrite) != 0) + { + if (write) frame.WriteSetWritten++; + else frame.WriteSetRead++; + if (frame.ByOrigin[(int)OverlapWrite.CpWrite].Contains(page) || frame.ByOrigin[(int)OverlapWrite.EopDestination].Contains(page)) + { + frame.LabelTouched++; + } + + if ((flags & InCommandBuffer) != 0) + { + frame.CommandBufferTouched++; + } + + lock (_topWaits) + { + var origin = 0; + for (var index = 0; index < OriginCount; index++) + { + if (frame.ByOrigin[index].Contains(page)) + { + origin = index; + break; + } + } + + _topWaits[page] = (origin, (_topWaits.TryGetValue(page, out var entry) ? entry.Hits : 0) + 1); + } + } + + if ((flags & InRead) != 0 && write) + { + frame.ReadSetWritten++; + frame.ReadWrittenPages.Add(page, PageBytes); + } + + if ((flags & DeviceAddressOnly) != 0 && write) + { + frame.DeviceAddressOnlyWritten++; + } + } + + // ---- per-frame results -------------------------------------------------------------- + + internal void FinalizeFrame(Frame frame) + { + if (frame.Finalized) + { + return; + } + + frame.Finalized = true; + var frequency = (double)Stopwatch.Frequency; + double Ms(long from, long to) => from == 0 || to == 0 ? double.NaN : (to - from) * 1000.0 / frequency; + + Admission? admission; + lock (_gate) + { + _admissions.TryGetValue(frame.Index, out admission); + } + + // Labels and command-processor writes into the frame's own submitted command buffers. + var labelsInCb = 0; + if (admission is not null) + { + foreach (var label in frame.Labels) + { + foreach (var submission in admission.Submissions) + { + if (label >= submission.Address && label - submission.Address < submission.Bytes) + { + labelsInCb++; + break; + } + } + } + } + + // Bytes of the bound ranges the guest wrote while it built the next frame: what would be detached. + long detachBytes = 0; + if (frame.ReadWrittenPages.Count != 0) + { + foreach (var range in frame.ReadRanges) + { + if (frame.ReadWrittenPages.ContainsAny(range.Address, range.Size)) + { + detachBytes += (long)range.Size; + lock (_topDetach) + { + _topDetach[range.Address] = (range.Size, (_topDetach.TryGetValue(range.Address, out var entry) ? entry.Hits : 0) + 1); + } + } + } + } + + var atomicInWrites = 0; + foreach (var target in frame.AtomicTargets) + { + if (frame.Written.Contains(target)) atomicInWrites++; + } + + lock (_window) + { + var window = _window; + window.Frames++; + window.InPlacePages.Add(frame.ReadInPlace.Count); + window.InPlaceMb.Add(frame.ReadInPlace.Count * 4096.0 / 1048576.0); + window.StagedMb.Add(frame.StagedBytes / 1048576.0); + window.UploadMb.Add(frame.UploadBytes / 1048576.0); + window.DaPages.Add(frame.DeviceAddress.Count); + window.WrittenPages.Add(frame.Written.Count); + window.LabelsInCb.Add(labelsInCb); + for (var index = 0; index < OriginCount; index++) + { + window.OriginPages[index] += frame.ByOrigin[index].Count; + } + + window.DaPlanned += frame.DaPlanned; + window.DaUnplanned += frame.DaUnplanned; + window.Gds += frame.GdsStores; + window.GpuValued += frame.GpuValued; + window.Unbounded += frame.Unbounded; + window.AtomicInWrites += atomicInWrites; + window.Huge += frame.HugeRanges; + if (frame.GdsStores + frame.GpuValued + frame.Unbounded + atomicInWrites != 0) window.RefusedFrames++; + if (admission is not null) + { + if (admission.Unfinished != 0) window.UnfinishedFrames++; + if (admission.Blocked != 0) window.BlockedFrames++; + window.DrainMs.Add(Ms(admission.BoundaryTicks, admission.WalkedTicks)); + } + + window.OverlapMs.Add(Ms(frame.CommittedTicks, frame.CompletedTicks)); + window.CompleteToAdmitMs.Add(Ms(frame.CompletedTicks, frame.FirstAdmitTicks)); + if (frame.Sampled && frame.ArmedTicks != 0) + { + window.Sampled++; + if (frame.CapSkipped != 0) window.CapFrames++; + if (frame.FirstAdmitTicks != 0 && frame.ArmedTicks > frame.FirstAdmitTicks) window.LateArms++; + window.Skipped += frame.SkippedReadWatched; + window.ArmMs.Add(Ms(frame.ArmStartTicks, frame.ArmedTicks)); + window.ArmedPages.Add(frame.ArmedPages); + window.RsWritten.Add(frame.ReadSetWritten); + window.DetachMb.Add(detachBytes / 1048576.0); + window.WsRead.Add(frame.WriteSetRead); + window.WsWritten.Add(frame.WriteSetWritten); + window.LabelTouched.Add(frame.LabelTouched); + window.CbTouched.Add(frame.CommandBufferTouched); + window.DaOnly.Add(frame.DeviceAddressOnlyWritten); + window.Managed.Add(frame.ManagedRead + frame.ManagedWrite); + window.Faults += frame.ReadSetWritten + frame.WriteSetRead + frame.WriteSetWritten; + if (frame.WriteSetRead != 0) window.WriteSetReadFrames++; + if (frame.FirstFaultTicks != 0) + { + window.FirstFaultMs.Add(Ms(frame.CompletedTicks, frame.FirstFaultTicks)); + if (frame.FirstAdmitTicks == 0 || frame.FirstFaultTicks < frame.FirstAdmitTicks) window.TrapBeforeSubmitFrames++; + } + } + } + } + + /// One window's line, and every 15th window the run's top ranges so far. + public string TakeWindowLine() + { + var culture = CultureInfo.InvariantCulture; + var builder = new StringBuilder("[METAL-V2][OVERLAP-DIAG] "); + lock (_window) + { + var w = _window; + string P(List values) => Percentiles(values, culture); + string Mx(List values) => Mean(values, culture) + "/" + Max(values, culture); + builder.Append(culture, $"frames={w.Frames} sampled={w.Sampled} every={_sampleEvery} "); + builder.Append($"read: inplace_pages={P(w.InPlacePages)} inplace_mb={P(w.InPlaceMb)} staged_mb={P(w.StagedMb)} upload_mb={P(w.UploadMb)} da_pages={P(w.DaPages)} "); + builder.Append(culture, $"da_enc planned={w.DaPlanned} unplanned={w.DaUnplanned} huge_ranges={w.Huge} | "); + builder.Append($"write: pages={P(w.WrittenPages)}"); + for (var index = 0; index < OriginCount; index++) + { + builder.Append(' ').Append(OriginNames[index]).Append('=') + .Append(w.Frames == 0 ? "0" : (w.OriginPages[index] / w.Frames).ToString("F0", culture)); + } + + builder.Append($" labels_in_cb={P(w.LabelsInCb)} | "); + builder.Append(culture, $"refuse: frames={w.RefusedFrames} gds={w.Gds} gpu_valued={w.GpuValued} unbounded={w.Unbounded} atomic_in_ws={w.AtomicInWrites} | "); + builder.Append(culture, $"boundary: unfinished_frames={w.UnfinishedFrames} blocked_frames={w.BlockedFrames} drain_ms={P(w.DrainMs)} | "); + builder.Append($"overlap_ms={P(w.OverlapMs)} complete_to_admit_ms={P(w.CompleteToAdmitMs)} | "); + builder.Append(culture, $"trap: armed_pages={Mx(w.ArmedPages)} arm_ms={P(w.ArmMs)} late_arms={w.LateArms} cap_frames={w.CapFrames} skipped_read_watched={w.Skipped} "); + builder.Append($"rs_written={Mx(w.RsWritten)} detach_mb={Mx(w.DetachMb)} ws_read={Mx(w.WsRead)} ws_written={Mx(w.WsWritten)} "); + builder.Append($"label_touched={Mx(w.LabelTouched)} cb_touched={Mx(w.CbTouched)} da_only_written={Mx(w.DaOnly)} managed={Mx(w.Managed)} first_fault_ms={P(w.FirstFaultMs)} "); + builder.Append(culture, $"trap_before_submit_frames={w.TrapBeforeSubmitFrames} ws_read_frames={w.WriteSetReadFrames}"); + _window.Frames = 0; + ResetWindow(); + } + + if (++_windows % 15 == 0) + { + builder.Append('\n').Append(TopRanges()); + } + + return builder.ToString(); + } + + internal string TopRanges() + { + var builder = new StringBuilder("[METAL-V2][OVERLAP-DIAG-TOP] detach (bound ranges the guest wrote, run so far):"); + lock (_topDetach) + { + foreach (var pair in _topDetach.OrderByDescending(pair => pair.Value.Hits * (long)Math.Min(pair.Value.Size, long.MaxValue)).Take(10)) + { + builder.Append(CultureInfo.InvariantCulture, $" 0x{pair.Key:X}+0x{pair.Value.Size:X}x{pair.Value.Hits}"); + } + } + + builder.Append(" | wait (GPU-written pages the guest touched):"); + lock (_topWaits) + { + foreach (var pair in _topWaits.OrderByDescending(pair => pair.Value.Hits).Take(10)) + { + builder.Append(CultureInfo.InvariantCulture, $" 0x{pair.Key:X}:{OriginNames[pair.Value.Origin]}x{pair.Value.Hits}"); + } + } + + return builder.ToString(); + } + + private void ResetWindow() + { + var w = _window; + w.Frames = w.Sampled = w.CapFrames = w.UnfinishedFrames = w.BlockedFrames = w.RefusedFrames = w.TrapBeforeSubmitFrames = 0; + w.WriteSetReadFrames = w.LateArms = 0; + w.DaPlanned = w.DaUnplanned = w.Gds = w.GpuValued = w.Unbounded = w.AtomicInWrites = w.Huge = w.Skipped = w.Faults = 0; + Array.Clear(w.OriginPages); + foreach (var list in new[] { w.InPlacePages, w.InPlaceMb, w.StagedMb, w.UploadMb, w.DaPages, w.WrittenPages, w.LabelsInCb, + w.DrainMs, w.OverlapMs, w.CompleteToAdmitMs, w.ArmMs, w.ArmedPages, w.RsWritten, w.DetachMb, w.WsRead, + w.WsWritten, w.LabelTouched, w.CbTouched, w.DaOnly, w.Managed, w.FirstFaultMs }) + { + list.Clear(); + } + } + + internal static string Percentiles(List values, IFormatProvider culture) + { + var sorted = values.Where(value => !double.IsNaN(value)).OrderBy(value => value).ToArray(); + if (sorted.Length == 0) + { + return "-"; + } + + double At(double fraction) => sorted[Math.Min(sorted.Length - 1, (int)Math.Floor(fraction * sorted.Length))]; + return string.Create(culture, $"{At(0.5):0.#}/{At(0.9):0.#}"); + } + + private static string Mean(List values, IFormatProvider culture) => + values.Count == 0 ? "-" : values.Average().ToString("0.#", culture); + + private static string Max(List values, IFormatProvider culture) => + values.Count == 0 ? "-" : values.Max().ToString("0.#", culture); + + public void Dispose() + { + lock (_requests) + { + _stopping = true; + Monitor.PulseAll(_requests); + } + + if (Volatile.Read(ref _armed) is { } armed) + { + Disarm(armed); + } + } +} diff --git a/src/SharpEmu.HLE/GpuMemory/GuestGpuMemory.cs b/src/SharpEmu.HLE/GpuMemory/GuestGpuMemory.cs index 48e129eac..c02894a09 100644 --- a/src/SharpEmu.HLE/GpuMemory/GuestGpuMemory.cs +++ b/src/SharpEmu.HLE/GpuMemory/GuestGpuMemory.cs @@ -119,6 +119,23 @@ public bool TryResolveFault(FaultKind kind, ulong address) return true; } + // SHARPEMU_DIAG_FRAME_OVERLAP=1: a page the diagnostic armed is counted and let go. When another + // watcher still holds it, the retried access faults again and reaches that watcher's path. + if (FrameOverlapDiagnostic.Enabled) + { + if (FrameOverlapDiagnostic.TryHandleFault(kind, address, out _)) + { + return true; + } + + // The guest process of the split: the GPU process holds the watches, and only its + // read faults are not already sent there (write faults reach it through the image store). + if (kind == FaultKind.Read && FrameOverlapDiagnostic.RemoteReadFault is { } remoteRead && remoteRead(address)) + { + return true; + } + } + // The fault names a byte in the page whose protection stopped the access, so the range ends // with that page: a store to the last bytes of a span is still the span's, and an access // that reaches into the next page faults again there. @@ -228,6 +245,11 @@ public bool MarkCpuWrite(ulong address, ulong size) } SplitCrossingStats.Count(SplitCrossing.ManagedWrite); + if (FrameOverlapDiagnostic.Enabled) + { + FrameOverlapDiagnostic.NoteManagedWrite(address, size); + } + if (!Covers(address, size)) { Interlocked.Increment(ref _lazyCoveredWrites); @@ -249,6 +271,11 @@ public void MarkCpuWriteLanded(ulong address, ulong size) } SplitCrossingStats.Count(SplitCrossing.ManagedWriteLanded); + if (FrameOverlapDiagnostic.Enabled) + { + FrameOverlapDiagnostic.NoteManagedWrite(address, size); + } + // The new bytes must be visible before the store reads its page state. Interlocked.MemoryBarrier(); Buffers?.MarkCpuWriteLanded(address, size); diff --git a/src/SharpEmu.Libs/Gpu/GpuCommands/CommandStreamQueue.cs b/src/SharpEmu.Libs/Gpu/GpuCommands/CommandStreamQueue.cs index 6311d92f1..efb55c3df 100644 --- a/src/SharpEmu.Libs/Gpu/GpuCommands/CommandStreamQueue.cs +++ b/src/SharpEmu.Libs/Gpu/GpuCommands/CommandStreamQueue.cs @@ -470,6 +470,36 @@ private string DescribePackets(ulong address, uint dwordCount, int depth = 0) return $"packets={packets} end={index}/{words.Length} ops=[{string.Join(' ', counts.Select(pair => $"{pair.Key:X2}x{pair.Value}"))}]{writes}"; } + // SHARPEMU_DIAG_FRAME_OVERLAP=1: the guest's submissions per frame, and at its boundary how + // many submissions of the frame are still to walk (queued, or the one running) and how many wait. + private void NoteAdmissionForOverlapDiagnostic(CommandSubmission submission) + { + if (submission.Kind == CommandSubmissionKind.FrameBoundary) + { + var unfinished = _processing ? 1 : 0; + var blocked = 0; + foreach (var queue in _queues) + { + foreach (var pending in queue) + { + if (pending.Kind is CommandSubmissionKind.FlipPreparation or CommandSubmissionKind.FrameBoundary) + { + continue; + } + + unfinished++; + blocked += pending.Blocked ? 1 : 0; + } + } + + SharpEmu.HLE.GpuMemory.FrameOverlapDiagnostic.OnBoundaryAdmitted(unfinished, blocked); + } + else if (submission.Kind != CommandSubmissionKind.FlipPreparation) + { + SharpEmu.HLE.GpuMemory.FrameOverlapDiagnostic.OnAdmission(submission.Address, (ulong)submission.DwordCount * sizeof(uint)); + } + } + private void EnqueueLocked(CommandSubmission submission) { if (!_accepting) @@ -483,6 +513,11 @@ private void EnqueueLocked(CommandSubmission submission) } submission.AdmissionOrdinal = ++_admissionOrdinal; + if (SharpEmu.HLE.GpuMemory.FrameOverlapDiagnostic.Enabled) + { + NoteAdmissionForOverlapDiagnostic(submission); + } + if (submission.QueueId == TraceQueueId) Console.Error.WriteLine( $"[GPU][QTRACE] admit q={submission.QueueId} sub={submission.SubmissionId} kind={submission.Kind} " + @@ -1830,6 +1865,11 @@ private bool RunSlice(CommandSubmission submission) if (submission.Kind == CommandSubmissionKind.FrameBoundary) { SlicesRun++; + if (SharpEmu.HLE.GpuMemory.FrameOverlapDiagnostic.Enabled) + { + SharpEmu.HLE.GpuMemory.FrameOverlapDiagnostic.OnBoundaryWalked(); + } + _host.FlushFrame(); return true; } diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalCommandStream.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalCommandStream.cs index bddc15265..ebecfb534 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalCommandStream.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalCommandStream.cs @@ -122,6 +122,11 @@ void ICommandStreamHost.FlushFrame() DrainDraws(); _frameBoundaries++; CommitStream("stream-frame"); + if (SharpEmu.HLE.GpuMemory.FrameOverlapDiagnostic.Enabled) + { + // Everything the frame recorded is committed: this serial finishes it. + SharpEmu.HLE.GpuMemory.FrameOverlapDiagnostic.OnFrameCommitted(Volatile.Read(ref _submittedSerial)); + } } // ---- command-buffer coalescing (SHARPEMU_METAL_V2_FLUSH_COALESCE) ---- @@ -833,6 +838,11 @@ public void RecordEndOfPipe(in EndOfPipeWrite write) DrainDraws(); using var endOfPipeScope = SharpEmu.Libs.VideoOut.RenderPhaseProfile.MeasureDetail( SharpEmu.Libs.VideoOut.RenderPhaseProfile.Phase.CommandEndOfPipe); + if (SharpEmu.HLE.GpuMemory.FrameOverlapDiagnostic.Enabled) + { + NoteEndOfPipeForOverlapDiagnostic(in write); + } + _endOfPipeRecords++; // Recorded ahead of the label, so its bytes land before the guest is told the // work is done. @@ -1001,6 +1011,36 @@ private void RecordEndOfPipeGdsWrite(in EndOfPipeWrite write) /// RELEASE_MEM data select 7: the add happens once the work before it has finished, from /// that work's completion, and like an owed label it keeps later labels behind it. /// + // SHARPEMU_DIAG_FRAME_OVERLAP=1: the destination of every end-of-pipe write, and the ones an + // overlapped frame could not publish early (GDS stores, GPU-valued clock samples, atomic adds). + private static void NoteEndOfPipeForOverlapDiagnostic(in EndOfPipeWrite write) + { + var bytes = (ulong)EndOfPipeLabelBytes(write.Kind); + switch (write.Kind) + { + case EndOfPipeWriteKind.GdsWrite32: + SharpEmu.HLE.GpuMemory.FrameOverlapDiagnostic.NoteRefusal(gds: true); + bytes = (ulong)write.GdsWordCount * sizeof(uint); + break; + case EndOfPipeWriteKind.AtomicAdd32: + SharpEmu.HLE.GpuMemory.FrameOverlapDiagnostic.NoteEndOfPipeAtomicAdd(write.Destination); + bytes = sizeof(uint); + break; + default: + if (IsClockLabel(in write)) + { + SharpEmu.HLE.GpuMemory.FrameOverlapDiagnostic.NoteRefusal(gds: false); + } + + break; + } + + if (write.Destination != 0 && bytes != 0) + { + SharpEmu.HLE.GpuMemory.FrameOverlapDiagnostic.NoteGpuWrite(write.Destination, bytes, SharpEmu.HLE.GpuMemory.OverlapWrite.EopDestination); + } + } + private void RecordEndOfPipeAtomicAdd(in EndOfPipeWrite write) { if (!DefersEndOfPipeLabel(EndOfPipeWriteKind.AtomicAdd32)) @@ -1415,6 +1455,11 @@ public void RecordCommandProcessorWrite(ulong address, ReadOnlySpan source throw Fatal($"A command-processor write has an invalid range: address=0x{address:X16} bytes={source.Length}."); } + if (SharpEmu.HLE.GpuMemory.FrameOverlapDiagnostic.Enabled) + { + SharpEmu.HLE.GpuMemory.FrameOverlapDiagnostic.NoteGpuWrite(address, (ulong)source.Length, SharpEmu.HLE.GpuMemory.OverlapWrite.CpWrite); + } + if (TryPublishEarlyLabel(address, source, kind, causal)) { return; diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalGpuReferenceCensus.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalGpuReferenceCensus.cs index 3532e3775..ec80b4679 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalGpuReferenceCensus.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalGpuReferenceCensus.cs @@ -44,7 +44,8 @@ internal static class MetalGpuReferenceCensus [ThreadStatic] private static int _scope; - public static bool Enabled => MemoryTelemetry.Enabled; + // The frame-overlap diagnostic reads the same marks (SHARPEMU_DIAG_FRAME_OVERLAP=1). + public static bool Enabled => MemoryTelemetry.Enabled || SharpEmu.HLE.GpuMemory.FrameOverlapDiagnostic.Enabled; /// Marks the blocks of a guest range; a scope (image upload or writeback) overrides the kind. public static void Mark(ulong address, ulong size, MetalRefKind kind = MetalRefKind.Binding) @@ -54,7 +55,28 @@ public static void Mark(ulong address, ulong size, MetalRefKind kind = MetalRefK return; } - Shared.Record(_scope != 0 ? (MetalRefKind)(_scope - 1) : kind, address, size); + var effective = _scope != 0 ? (MetalRefKind)(_scope - 1) : kind; + if (MemoryTelemetry.Enabled) + { + Shared.Record(effective, address, size); + } + + if (SharpEmu.HLE.GpuMemory.FrameOverlapDiagnostic.Enabled) + { + if (effective == MetalRefKind.ImageWriteback) + { + SharpEmu.HLE.GpuMemory.FrameOverlapDiagnostic.NoteGpuWrite(address, size, SharpEmu.HLE.GpuMemory.OverlapWrite.Writeback); + } + else + { + SharpEmu.HLE.GpuMemory.FrameOverlapDiagnostic.MarkGpuRead(address, size, effective switch + { + MetalRefKind.Staged => SharpEmu.HLE.GpuMemory.OverlapRead.Staged, + MetalRefKind.ImageUpload => SharpEmu.HLE.GpuMemory.OverlapRead.Upload, + _ => SharpEmu.HLE.GpuMemory.OverlapRead.InPlace, + }); + } + } } /// While alive, every mark on this thread counts as (image paths). @@ -121,7 +143,7 @@ public void Dispose() /// The spans the device-address table maps: reachable by any program, exactly named by none. public static void SetDeviceAddressSpans(IEnumerable<(ulong Address, ulong Size)> spans) { - if (Enabled) + if (MemoryTelemetry.Enabled) { Shared.SetDeviceAddressSpans(spans); } diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalGpuWorker.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalGpuWorker.cs index 661406c94..41d4bdadd 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalGpuWorker.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalGpuWorker.cs @@ -269,6 +269,11 @@ public void NoteSignaled(ulong value) var before = Interlocked.CompareExchange(ref _completedHint, value, seen); if (before == seen) { + if (SharpEmu.HLE.GpuMemory.FrameOverlapDiagnostic.Enabled) + { + SharpEmu.HLE.GpuMemory.FrameOverlapDiagnostic.OnCompleted(value); + } + return; } diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalGpuWriteRanges.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalGpuWriteRanges.cs index 464cc72f6..ec6131893 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalGpuWriteRanges.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalGpuWriteRanges.cs @@ -244,6 +244,12 @@ public ulong Note( ulong serial, MetalGpuWriteOrigin origin = MetalGpuWriteOrigin.StorageBuffer) { + // Every write as recorded, before any folding (SHARPEMU_DIAG_FRAME_OVERLAP=1). + if (SharpEmu.HLE.GpuMemory.FrameOverlapDiagnostic.Enabled) + { + SharpEmu.HLE.GpuMemory.FrameOverlapDiagnostic.NoteGpuWrite(address, size, (SharpEmu.HLE.GpuMemory.OverlapWrite)origin); + } + BeginMutation(); try { @@ -495,6 +501,11 @@ private void NoteLabel(ulong address, ulong end, ulong serial, ulong sequence) /// public void NoteUnbounded(ulong serial) { + if (SharpEmu.HLE.GpuMemory.FrameOverlapDiagnostic.Enabled) + { + SharpEmu.HLE.GpuMemory.FrameOverlapDiagnostic.NoteGpuWrite(0, 0, SharpEmu.HLE.GpuMemory.OverlapWrite.Unbounded); + } + BeginMutation(); try { diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Descriptors.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Descriptors.cs index 94d165825..c31a7ccda 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Descriptors.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Descriptors.cs @@ -1177,6 +1177,18 @@ private void BindDeviceAddressRanges( { var unplanned = false; var declaredWrite = false; + if (SharpEmu.HLE.GpuMemory.FrameOverlapDiagnostic.Enabled && (stage.Program.UsesDeviceAddresses || snapshot.DeviceAddressRanges.Length != 0)) + { + // An encoder running a device-address program: its reach is evaluated only when every handle is planned. + var planned = true; + foreach (var range in snapshot.DeviceAddressRanges) + { + planned &= range.Planned; + } + + SharpEmu.HLE.GpuMemory.FrameOverlapDiagnostic.NoteDeviceAddressProgram(planned); + } + BeginDeviceRangeOrdering(stage); if (snapshot.DeviceAddressRanges.Length != 0 && _singleCopy is { } singleCopy) { @@ -1207,6 +1219,11 @@ private void BindDeviceAddressRanges( } var size = ClampMappedSize(range.Base, range.Size); + if (SharpEmu.HLE.GpuMemory.FrameOverlapDiagnostic.Enabled) + { + SharpEmu.HLE.GpuMemory.FrameOverlapDiagnostic.MarkGpuRead(range.Base, size, SharpEmu.HLE.GpuMemory.OverlapRead.DeviceAddress); + } + if (_traceBufferUserAddress != 0) { TraceBufferUser(stage, $"device_address h{range.Handle}{(range.Written ? " written" : string.Empty)}", range.Base, size); diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.cs index fbf772771..678d36752 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.cs @@ -192,6 +192,8 @@ public MetalRenderHost( _singleCopy = new MetalSingleCopy(device, _guestMemory, backing, pages, () => CompletedSerial); _imageCache.SingleCopy = _singleCopy; } + // SHARPEMU_DIAG_FRAME_OVERLAP=1: single-copy holds the one read-watch bit, so the diagnostic then arms writes only. + SharpEmu.HLE.GpuMemory.FrameOverlapDiagnostic.Attach(pages, readWatchesShared: _singleCopy is not null); if (MetalStagedRangeCache.Enabled) { _stagedRanges = new MetalStagedRangeCache( @@ -2848,6 +2850,11 @@ public void ReportCounters() $"msl_dispatcher={ShaderCompiler.Metal.Gen5MslTranslator.Statistics.ControlFlowForms.Dispatcher} " + $"uploads={uploads} writebacks={writebacks} evictions={evictions} failed={failed} " + (_meshletCache?.TakeCounters() ?? "meshlet_draws=0") + " " + TakeIndirectCounters()); + if (SharpEmu.HLE.GpuMemory.FrameOverlapDiagnostic.TakeWindowLine() is { } overlapLine) + { + Console.Error.WriteLine(overlapLine); + } + _slowWaitReports = 0; ResetSlowCompletionReports(); if (WaitOrigins && _waitOrigins.Count != 0) diff --git a/tests/SharpEmu.Libs.Tests/HLE/FrameOverlapTrackerTests.cs b/tests/SharpEmu.Libs.Tests/HLE/FrameOverlapTrackerTests.cs new file mode 100644 index 000000000..fcd5e5f12 --- /dev/null +++ b/tests/SharpEmu.Libs.Tests/HLE/FrameOverlapTrackerTests.cs @@ -0,0 +1,196 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using System.Diagnostics; +using SharpEmu.HLE.GpuMemory; +using Xunit; + +namespace SharpEmu.Libs.Tests.HLE; + +/// +/// The frame-overlap diagnostic's bookkeeping without a page guard: which frame a mark belongs +/// to, which pages a completed frame arms and how, that each armed page counts its first fault +/// once and is let go, and that every watch it took is given back at the next boundary. +/// +public sealed class FrameOverlapTrackerTests +{ + private static readonly long Millisecond = Stopwatch.Frequency / 1000; + + private sealed class FakeWatches : IFrameOverlapWatches + { + public readonly Dictionary<(ulong Page, bool Reads), int> Counts = new(); + public readonly HashSet ReadWatchedElsewhere = new(); + + public bool IsReadWatched(ulong page) => ReadWatchedElsewhere.Contains(page); + + public void Add(ulong blockBase, in PageMask pages, bool blockReads) => Change(blockBase, pages, blockReads, 1); + + public void Remove(ulong blockBase, in PageMask pages, bool blockReads) => Change(blockBase, pages, blockReads, -1); + + public bool StillBlocks(ulong page, FaultKind kind) => + Counts.GetValueOrDefault((page, true)) != 0 || (kind != FaultKind.Read && Counts.GetValueOrDefault((page, false)) != 0); + + private void Change(ulong blockBase, PageMask pages, bool reads, int delta) + { + for (var index = 0; index < TrackerLayout.PagesPerBlock; index++) + { + if (!pages.Get(index)) + { + continue; + } + + var key = (blockBase + (ulong)index * TrackerLayout.PageBytes, reads); + var count = Counts.GetValueOrDefault(key) + delta; + Assert.True(count >= 0, $"watch count below zero at 0x{key.Item1:X}"); + Counts[key] = count; + } + } + + public int Live => Counts.Values.Sum(); + } + + private long _now = 1; + + private FrameOverlapTracker Create(FakeWatches watches, int every = 1, int maxPages = 1000) => + new(watches, () => _now, every, maxPages, armReads: true, startThread: false); + + [Fact] + public void ACompletedFrameArmsItsInPlaceReadsForWritesAndItsWritesForReads() + { + var watches = new FakeWatches(); + var tracker = Create(watches); + tracker.MarkRead(0x10000, 0x2000, OverlapRead.InPlace); + tracker.MarkRead(0x20000, 0x1000, OverlapRead.Staged); + tracker.NoteWrite(0x30000, 0x1000, OverlapWrite.Storage); + tracker.NoteWrite(0x40008, 8, OverlapWrite.EopDestination); + tracker.OnAdmission(0x40000, 0x100); + tracker.OnBoundaryAdmitted(unfinished: 0, blocked: 0); + tracker.OnBoundaryWalked(); + _now = 10 * Millisecond; + tracker.OnFrameCommitted(5); + _now = 50 * Millisecond; + tracker.OnCompleted(5); + tracker.DrainRequests(); + + Assert.Equal(1, watches.Counts[(0x10000, false)]); + Assert.Equal(1, watches.Counts[(0x11000, false)]); + Assert.Equal(1, watches.Counts[(0x30000, true)]); + Assert.Equal(1, watches.Counts[(0x40000, true)]); + Assert.False(watches.Counts.ContainsKey((0x20000, false))); + Assert.Equal(4, watches.Live); + + // The first fault on a page is counted and lets the page go; the second is someone else's. + Assert.True(tracker.TryHandleFault(FaultKind.Write, 0x10010, out var blocked)); + Assert.False(blocked); + Assert.False(tracker.TryHandleFault(FaultKind.Write, 0x10020, out _)); + _now = 52 * Millisecond; + tracker.OnAdmission(0x50000, 0x100); + Assert.True(tracker.TryHandleFault(FaultKind.Read, 0x40010, out _)); + Assert.Equal(2, watches.Live); + + // The next frame's boundary ends the build: the rest is given back and the frame is counted. + tracker.OnBoundaryAdmitted(unfinished: 1, blocked: 0); + tracker.DrainRequests(); + Assert.Equal(0, watches.Live); + + var line = tracker.TakeWindowLine(); + Assert.Contains("frames=1 sampled=1 ", line); + Assert.Contains("overlap_ms=40/40", line); + Assert.Contains("complete_to_admit_ms=2/2", line); + Assert.Contains("rs_written=1/1", line); + Assert.Contains("ws_read=1/1", line); + Assert.Contains("label_touched=1/1", line); + Assert.Contains("cb_touched=1/1", line); + Assert.Contains("labels_in_cb=1/1", line); + Assert.Contains("first_fault_ms=0/0", line); + Assert.Contains("trap_before_submit_frames=1", line); + Assert.Contains("staged_mb=0/0", line); + // The window starts over. + Assert.Contains("frames=0 ", tracker.TakeWindowLine()); + } + + [Fact] + public void MarksAfterACommitBelongToTheNextFrame() + { + var watches = new FakeWatches(); + var tracker = Create(watches, every: 2); + tracker.MarkRead(0x10000, 0x1000, OverlapRead.InPlace); + tracker.OnBoundaryAdmitted(0, 0); + tracker.OnFrameCommitted(1); + tracker.MarkRead(0x90000, 0x1000, OverlapRead.InPlace); + tracker.OnCompleted(1); + tracker.DrainRequests(); + // Frame 0 is sampled (every 2nd from 0): only its own page is armed. + Assert.Equal(1, watches.Counts[(0x10000, false)]); + Assert.False(watches.Counts.ContainsKey((0x90000, false))); + + tracker.OnBoundaryAdmitted(0, 0); + tracker.OnFrameCommitted(2); + tracker.OnCompleted(2); + tracker.DrainRequests(); + // Frame 1 is not sampled, and frame 0 was given back at frame 1's boundary. + Assert.Equal(0, watches.Live); + } + + [Fact] + public void AReadWatchedPageIsSkippedAndTheCapIsCounted() + { + var watches = new FakeWatches(); + watches.ReadWatchedElsewhere.Add(0x30000); + var tracker = Create(watches, maxPages: 2); + tracker.NoteWrite(0x30000, 0x3000, OverlapWrite.Writeback); + tracker.OnBoundaryAdmitted(0, 0); + tracker.OnFrameCommitted(1); + tracker.OnCompleted(1); + tracker.DrainRequests(); + + // The one read bit belongs to someone else: write-watched instead, and two pages fit the cap. + Assert.Equal(1, watches.Counts[(0x30000, false)]); + Assert.Equal(1, watches.Counts[(0x31000, true)]); + Assert.False(watches.Counts.ContainsKey((0x32000, true))); + tracker.OnBoundaryAdmitted(0, 0); + tracker.DrainRequests(); + Assert.Equal(0, watches.Live); + var line = tracker.TakeWindowLine(); + Assert.Contains("cap_frames=1", line); + Assert.Contains("skipped_read_watched=1", line); + } + + [Fact] + public void ManagedWritesAreCountedWithoutReleasingTheWatch() + { + var watches = new FakeWatches(); + var tracker = Create(watches); + tracker.MarkRead(0x10000, 0x1000, OverlapRead.InPlace); + tracker.OnBoundaryAdmitted(0, 0); + tracker.OnFrameCommitted(1); + tracker.OnCompleted(1); + tracker.DrainRequests(); + tracker.NoteManagedWrite(0x10100, 4); + tracker.NoteManagedWrite(0x10200, 4); + Assert.Equal(1, watches.Live); + tracker.OnBoundaryAdmitted(0, 0); + tracker.DrainRequests(); + Assert.Contains("managed=1/1", tracker.TakeWindowLine()); + } + + [Fact] + public void ThePageSetCountsDistinctPagesAcrossBlocks() + { + var set = new OverlapPageSet(); + Assert.Equal(3, set.Add(0x3FF000, 0x2001)); + Assert.Equal(0, set.Add(0x400000, 0x1000)); + Assert.True(set.Contains(0x401FFF)); + Assert.False(set.Contains(0x402000)); + Assert.True(set.ContainsAny(0x3FE000, 0x1001)); + Assert.Equal(3, set.Count); + } + + [Fact] + public void PercentilesIgnoreMissingSamples() + { + var culture = System.Globalization.CultureInfo.InvariantCulture; + Assert.Equal("-", FrameOverlapTracker.Percentiles([double.NaN], culture)); + Assert.Equal("3/5", FrameOverlapTracker.Percentiles([1, 2, 3, 4, 5, double.NaN], culture)); + } +} From 5cda54bd6399cada68a514fc9a464201987063a1 Mon Sep 17 00:00:00 2001 From: kuba Date: Mon, 16 Nov 2026 07:05:58 +0000 Subject: [PATCH 120/178] [Diag] Frame-overlap: retry a fault that raced the disarm, once per page A guest read of a page whose read watch the GPU process had just dropped, before the given-back protection reached the guest process, was declined and killed the run (r ovl1: SIGBUS reading the frame label at 31 s). The last disarmed frame now answers such a fault once per page; late_faults counts them. --- .../GpuMemory/FrameOverlapDiagnostic.cs | 22 +++++++++++++++++-- .../HLE/FrameOverlapTrackerTests.cs | 22 +++++++++++++++++++ 2 files changed, 42 insertions(+), 2 deletions(-) diff --git a/src/SharpEmu.HLE/GpuMemory/FrameOverlapDiagnostic.cs b/src/SharpEmu.HLE/GpuMemory/FrameOverlapDiagnostic.cs index f659ae226..e7d713ff9 100644 --- a/src/SharpEmu.HLE/GpuMemory/FrameOverlapDiagnostic.cs +++ b/src/SharpEmu.HLE/GpuMemory/FrameOverlapDiagnostic.cs @@ -261,6 +261,7 @@ public sealed class FrameOverlapTracker : IDisposable private const byte ReadArmed = 16; private const byte Armed = 32; private const byte ManagedSeen = 64; + private const byte Retried = 128; private readonly IFrameOverlapWatches _watches; private readonly Func _clock; @@ -289,6 +290,11 @@ public sealed class FrameOverlapTracker : IDisposable // The frame whose pages are armed. private Frame? _armed; + // The frame disarmed last: a fault that reached the guest's handler before the protection + // the disarm gave back was applied there is answered once per page (retry), not declined. + private Frame? _released; + private long _lateFaults; + private readonly Window _window = new(); private readonly Dictionary _topDetach = new(); private readonly Dictionary _topWaits = new(); @@ -805,13 +811,15 @@ internal void Disarm(Frame frame) { Volatile.Write(ref _armed, null); } + + Volatile.Write(ref _released, frame); } } public bool TryHandleFault(FaultKind kind, ulong address, out bool stillBlocked) { stillBlocked = false; - if (Volatile.Read(ref _armed) is null) + if (Volatile.Read(ref _armed) is null && Volatile.Read(ref _released) is null) { return false; } @@ -821,6 +829,16 @@ public bool TryHandleFault(FaultKind kind, ulong address, out bool stillBlocked) { if (_armed is not { } frame || !frame.Pages.TryGetValue(page, out var flags) || (flags & Armed) == 0) { + // Released already, but the access faulted on the protection the watch had: once + // the release is applied the access goes through, so it is retried, once a page. + if (_released is { } released && released.Pages.TryGetValue(page, out var old) && (old & Retried) == 0 && + !_watches.StillBlocks(page, kind)) + { + released.Pages[page] = (byte)(old | Retried); + Interlocked.Increment(ref _lateFaults); + return true; + } + return false; } @@ -1056,7 +1074,7 @@ public string TakeWindowLine() builder.Append(culture, $"refuse: frames={w.RefusedFrames} gds={w.Gds} gpu_valued={w.GpuValued} unbounded={w.Unbounded} atomic_in_ws={w.AtomicInWrites} | "); builder.Append(culture, $"boundary: unfinished_frames={w.UnfinishedFrames} blocked_frames={w.BlockedFrames} drain_ms={P(w.DrainMs)} | "); builder.Append($"overlap_ms={P(w.OverlapMs)} complete_to_admit_ms={P(w.CompleteToAdmitMs)} | "); - builder.Append(culture, $"trap: armed_pages={Mx(w.ArmedPages)} arm_ms={P(w.ArmMs)} late_arms={w.LateArms} cap_frames={w.CapFrames} skipped_read_watched={w.Skipped} "); + builder.Append(culture, $"trap: armed_pages={Mx(w.ArmedPages)} arm_ms={P(w.ArmMs)} late_arms={w.LateArms} late_faults={Interlocked.Exchange(ref _lateFaults, 0)} cap_frames={w.CapFrames} skipped_read_watched={w.Skipped} "); builder.Append($"rs_written={Mx(w.RsWritten)} detach_mb={Mx(w.DetachMb)} ws_read={Mx(w.WsRead)} ws_written={Mx(w.WsWritten)} "); builder.Append($"label_touched={Mx(w.LabelTouched)} cb_touched={Mx(w.CbTouched)} da_only_written={Mx(w.DaOnly)} managed={Mx(w.Managed)} first_fault_ms={P(w.FirstFaultMs)} "); builder.Append(culture, $"trap_before_submit_frames={w.TrapBeforeSubmitFrames} ws_read_frames={w.WriteSetReadFrames}"); diff --git a/tests/SharpEmu.Libs.Tests/HLE/FrameOverlapTrackerTests.cs b/tests/SharpEmu.Libs.Tests/HLE/FrameOverlapTrackerTests.cs index fcd5e5f12..3371a0121 100644 --- a/tests/SharpEmu.Libs.Tests/HLE/FrameOverlapTrackerTests.cs +++ b/tests/SharpEmu.Libs.Tests/HLE/FrameOverlapTrackerTests.cs @@ -174,6 +174,28 @@ public void ManagedWritesAreCountedWithoutReleasingTheWatch() Assert.Contains("managed=1/1", tracker.TakeWindowLine()); } + [Fact] + public void AFaultThatRacedTheDisarmIsRetriedOncePerPage() + { + var watches = new FakeWatches(); + var tracker = Create(watches); + tracker.NoteWrite(0x40000, 8, OverlapWrite.CpWrite); + tracker.OnBoundaryAdmitted(0, 0); + tracker.OnFrameCommitted(1); + tracker.OnCompleted(1); + tracker.DrainRequests(); + tracker.OnBoundaryAdmitted(0, 0); + tracker.DrainRequests(); + Assert.Equal(0, watches.Live); + + // The guest read the page before the given-back protection reached it. + Assert.True(tracker.TryHandleFault(FaultKind.Read, 0x40000, out var blocked)); + Assert.False(blocked); + Assert.False(tracker.TryHandleFault(FaultKind.Read, 0x40000, out _)); + Assert.False(tracker.TryHandleFault(FaultKind.Read, 0x50000, out _)); + Assert.Contains("late_faults=1", tracker.TakeWindowLine()); + } + [Fact] public void ThePageSetCountsDistinctPagesAcrossBlocks() { From c6346f261c6d9bf86958e3665fa02dd2eb8d4d4e Mon Sep 17 00:00:00 2001 From: kuba Date: Mon, 16 Nov 2026 07:13:52 +0000 Subject: [PATCH 121/178] [Diag] Frame-overlap: optional arming at commit (SHARPEMU_DIAG_FRAME_OVERLAP_ARM=commit) r ovl2 (arming at completion) armed 65536 of ~260k pages in 7-9 ms while the guest's boundary for the next frame comes ~7.5 ms after completion: late_arms on every sampled frame, so the trap counts are lower bounds over an address-ordered quarter of the pages and the tail of the build. Arming at commit uses the ~38 ms GPU tail, during which the guest waits on the fence; a fault there is counted with a negative first_fault_ms. Not run in a game yet (app build budget). Top-range lists print size*hits. --- .../GpuMemory/FrameOverlapDiagnostic.cs | 32 +++++++++++++++---- .../HLE/FrameOverlapTrackerTests.cs | 26 +++++++++++++++ 2 files changed, 52 insertions(+), 6 deletions(-) diff --git a/src/SharpEmu.HLE/GpuMemory/FrameOverlapDiagnostic.cs b/src/SharpEmu.HLE/GpuMemory/FrameOverlapDiagnostic.cs index e7d713ff9..a66f08ba1 100644 --- a/src/SharpEmu.HLE/GpuMemory/FrameOverlapDiagnostic.cs +++ b/src/SharpEmu.HLE/GpuMemory/FrameOverlapDiagnostic.cs @@ -92,6 +92,16 @@ public static class FrameOverlapDiagnostic public static readonly int MaxArmedPages = int.TryParse(Environment.GetEnvironmentVariable("SHARPEMU_DIAG_FRAME_OVERLAP_MAX_PAGES"), out var cap) && cap >= 1 ? cap : 65536; + /// + /// SHARPEMU_DIAG_FRAME_OVERLAP_ARM=commit: arm a sampled frame when its last serial is committed + /// instead of when it completes. Arming ~200k pages takes longer than the guest's build of the + /// next frame (r ovl2: 7-9 ms for 64k pages against a boundary ~7.5 ms after completion), so + /// armed at completion the watches see only the build's tail; the guest waits on the GPU fence + /// between commit and completion, which leaves the ~38 ms of the GPU tail to arm in. + /// + public static readonly bool ArmAtCommit = + Environment.GetEnvironmentVariable("SHARPEMU_DIAG_FRAME_OVERLAP_ARM") == "commit"; + /// SHARPEMU_DIAG_FRAME_OVERLAP_READS=0: arm write watches only (no read traps on the write set). public static readonly bool ArmReads = Environment.GetEnvironmentVariable("SHARPEMU_DIAG_FRAME_OVERLAP_READS") != "0"; @@ -117,13 +127,13 @@ public static void Attach(PageGuard? guard, bool readWatchesShared) var previous = Interlocked.Exchange(ref _tracker, guard is null ? null : new FrameOverlapTracker(new PageGuardOverlapWatches(guard), Stopwatch.GetTimestamp, SampleEvery, MaxArmedPages, - ArmReads && !readWatchesShared, startThread: true)); + ArmReads && !readWatchesShared, startThread: true) { ArmAtCommit = ArmAtCommit }); previous?.Dispose(); if (guard is not null) { Console.Error.WriteLine( $"[METAL-V2][OVERLAP-DIAG] on: every={SampleEvery} max_pages={MaxArmedPages} " + - $"read_watches={(ArmReads && !readWatchesShared ? 1 : 0)}" + + $"read_watches={(ArmReads && !readWatchesShared ? 1 : 0)} arm_at={(ArmAtCommit ? "commit" : "completion")}" + (ArmReads && readWatchesShared ? " (off: single-copy holds the read-watch bit)" : string.Empty)); } } @@ -315,6 +325,9 @@ public FrameOverlapTracker(IFrameOverlapWatches watches, Func clock, int s } } + /// Arm a sampled frame at its commit rather than at its completion. + public bool ArmAtCommit { get; init; } + internal sealed class Frame(long index) { public readonly long Index = index; @@ -331,7 +344,7 @@ internal sealed class Frame(long index) public int DaPlanned, DaUnplanned, GdsStores, GpuValued, Unbounded; public ulong LastSerial; public long CommittedTicks, CompletedTicks, FirstAdmitTicks, ArmStartTicks, ArmedTicks, FirstFaultTicks; - public bool Sampled, Finalized; + public bool Sampled, Finalized, ArmPosted; // Trap results (under the watch gate). public readonly Dictionary Pages = new(); @@ -470,6 +483,12 @@ public void OnFrameCommitted(ulong lastSerial) frame.Sampled = frame.Index % _sampleEvery == 0; _inFlight.Add(frame); _recording = new Frame(++_recordedFrames); + if (frame.Sampled && ArmAtCommit) + { + frame.ArmPosted = true; + Post(arm: true, frame); + } + CompleteLocked(now); } } @@ -504,8 +523,9 @@ private void CompleteLocked(long now) } frame.CompletedTicks = now; - if (frame.Sampled) + if (frame.Sampled && !frame.ArmPosted) { + frame.ArmPosted = true; Post(arm: true, frame); } } @@ -1097,7 +1117,7 @@ internal string TopRanges() { foreach (var pair in _topDetach.OrderByDescending(pair => pair.Value.Hits * (long)Math.Min(pair.Value.Size, long.MaxValue)).Take(10)) { - builder.Append(CultureInfo.InvariantCulture, $" 0x{pair.Key:X}+0x{pair.Value.Size:X}x{pair.Value.Hits}"); + builder.Append(CultureInfo.InvariantCulture, $" 0x{pair.Key:X}+0x{pair.Value.Size:X}*{pair.Value.Hits}"); } } @@ -1106,7 +1126,7 @@ internal string TopRanges() { foreach (var pair in _topWaits.OrderByDescending(pair => pair.Value.Hits).Take(10)) { - builder.Append(CultureInfo.InvariantCulture, $" 0x{pair.Key:X}:{OriginNames[pair.Value.Origin]}x{pair.Value.Hits}"); + builder.Append(CultureInfo.InvariantCulture, $" 0x{pair.Key:X}:{OriginNames[pair.Value.Origin]}*{pair.Value.Hits}"); } } diff --git a/tests/SharpEmu.Libs.Tests/HLE/FrameOverlapTrackerTests.cs b/tests/SharpEmu.Libs.Tests/HLE/FrameOverlapTrackerTests.cs index 3371a0121..a6729c8d0 100644 --- a/tests/SharpEmu.Libs.Tests/HLE/FrameOverlapTrackerTests.cs +++ b/tests/SharpEmu.Libs.Tests/HLE/FrameOverlapTrackerTests.cs @@ -132,6 +132,32 @@ public void MarksAfterACommitBelongToTheNextFrame() Assert.Equal(0, watches.Live); } + [Fact] + public void ArmedAtCommitTheWatchesCoverTheGpuTailAndAreNotArmedTwice() + { + var watches = new FakeWatches(); + var tracker = new FrameOverlapTracker(watches, () => _now, 1, 1000, armReads: true, startThread: false) { ArmAtCommit = true }; + tracker.MarkRead(0x10000, 0x1000, OverlapRead.InPlace); + tracker.OnBoundaryAdmitted(0, 0); + _now = 10 * Millisecond; + tracker.OnFrameCommitted(1); + tracker.DrainRequests(); + Assert.Equal(1, watches.Live); + + // A guest store while the GPU still runs the frame: counted before the completion. + _now = 20 * Millisecond; + Assert.True(tracker.TryHandleFault(FaultKind.Write, 0x10000, out _)); + _now = 40 * Millisecond; + tracker.OnCompleted(1); + tracker.DrainRequests(); + Assert.Equal(0, watches.Live); + tracker.OnBoundaryAdmitted(0, 0); + tracker.DrainRequests(); + var line = tracker.TakeWindowLine(); + Assert.Contains("rs_written=1/1", line); + Assert.Contains("first_fault_ms=-20/-20", line); + } + [Fact] public void AReadWatchedPageIsSkippedAndTheCapIsCounted() { From fa336d2297b31f970b6107c899ef64fe5fbe0767 Mon Sep 17 00:00:00 2001 From: kuba Date: Mon, 16 Nov 2026 07:20:15 +0000 Subject: [PATCH 122/178] [Diag] Frame-overlap: byte-level attribution of every counted fault Each fault is classified by its address (the first byte touched; the access width is not decoded, so 1 byte is assumed): read-set pages written -> rs_hit (inside a bound range) or rs_nb (only the page); write-set pages read/written -> label (only command-processor or end-of-pipe label bytes, known at record time and landed on the CPU at publication: not a wait), gpu (bytes a GPU-valued write covers: storage, binding, device address, fill, copy, writeback, or a clock/GDS/atomic end-of-pipe destination, now origin eop_gpu_valued), nb; device-address-only pages written -> hit/nb with the program hash. real_wait_pages = gpu hits, real_trap_pages = rs hits + gpu hits + device-address hits; k6_* = GPU-valued read hits (frames, ms after completion, before the guest's first submission of N+1); real_wait_ms / overlap_until_wait_ms = first real wait after completion and the build work it leaves to hide (clamped to the commit->completion window); armed_before_complete. Storage and device-address write notes carry the writing program's hash (SetWriter at the two binding sites). Every 15th window prints the 10 pages with most faults (ranges on the page with origin and program, up to 8 faulting offsets with r/w and class); the first 60 K6/K3 hits of a run print one [METAL-V2][OVERLAP-DIAG-HIT] line each. --- .../GpuMemory/FrameOverlapDiagnostic.cs | 269 +++++++++++++++++- .../V2/MetalCommandStream.cs | 6 +- .../V2/MetalRenderHost.Descriptors.cs | 12 +- .../HLE/FrameOverlapTrackerTests.cs | 56 ++++ 4 files changed, 333 insertions(+), 10 deletions(-) diff --git a/src/SharpEmu.HLE/GpuMemory/FrameOverlapDiagnostic.cs b/src/SharpEmu.HLE/GpuMemory/FrameOverlapDiagnostic.cs index a66f08ba1..38c15182e 100644 --- a/src/SharpEmu.HLE/GpuMemory/FrameOverlapDiagnostic.cs +++ b/src/SharpEmu.HLE/GpuMemory/FrameOverlapDiagnostic.cs @@ -40,6 +40,9 @@ public enum OverlapWrite Unbounded, CpWrite, EopDestination, + + /// An end-of-pipe destination whose value only the GPU knows: a clock sample, a GDS store, an atomic add. + EopGpuValued, } /// The page watches the diagnostic arms; a seam so the bookkeeping runs without a guard. @@ -138,9 +141,23 @@ public static void Attach(PageGuard? guard, bool readWatchesShared) } } - public static void MarkGpuRead(ulong address, ulong size, OverlapRead kind) => Tracker?.MarkRead(address, size, kind); + public static void MarkGpuRead(ulong address, ulong size, OverlapRead kind, ulong program = 0) => Tracker?.MarkRead(address, size, kind, program); + + public static void NoteGpuWrite(ulong address, ulong size, OverlapWrite origin) => + Tracker?.NoteWrite(address, size, origin, origin is OverlapWrite.Storage or OverlapWrite.Binding or OverlapWrite.DeviceAddress ? TakeWriter() : 0); - public static void NoteGpuWrite(ulong address, ulong size, OverlapWrite origin) => Tracker?.NoteWrite(address, size, origin); + [ThreadStatic] + private static ulong t_writer; + + /// The program whose store the next storage or device-address write note on this thread records (consumed by it). + public static void SetWriter(ulong programHash) => t_writer = programHash; + + private static ulong TakeWriter() + { + var writer = t_writer; + t_writer = 0; + return writer; + } public static void NoteDeviceAddressProgram(bool planned) => Tracker?.NoteDeviceAddressProgram(planned); @@ -259,9 +276,31 @@ public sealed class FrameOverlapTracker : IDisposable // A single range above this is counted, not walked page by page (a whole window or table). internal const ulong HugeRangeBytes = 256UL << 20; private const ulong PageBytes = TrackerLayout.PageBytes; - private const int OriginCount = (int)OverlapWrite.EopDestination + 1; + private const int OriginCount = (int)OverlapWrite.EopGpuValued + 1; private static readonly string[] OriginNames = - ["storage", "binding", "device_address", "fill", "copy", "writeback", "eop_label", "unbounded", "cp_write", "eop_dest"]; + ["storage", "binding", "device_address", "fill", "copy", "writeback", "eop_label", "unbounded", "cp_write", "eop_dest", "eop_gpu_valued"]; + + // Writes whose bytes are known when the packet is recorded: an overlapped frame lands them on + // the CPU at publication, so a guest read of them is not a wait. + private static bool KnownAtRecord(int origin) => + origin is (int)OverlapWrite.EopLabel or (int)OverlapWrite.CpWrite or (int)OverlapWrite.EopDestination; + + /// What a fault's address meets on its page (the fault reports the first byte touched; the access width is not decoded, so 1 byte is assumed). + internal enum Hit + { + Neighbour, + Label, + GpuValued, + } + + private sealed class PageReport + { + public long Faults; + public readonly List Ranges = new(); + public readonly List Accesses = new(); + } + + private readonly Dictionary _pageReports = new(); // Page flags of an armed frame. private const byte InRead = 1; @@ -338,6 +377,11 @@ internal sealed class Frame(long index) public readonly OverlapPageSet[] ByOrigin = Enumerable.Range(0, OriginCount).Select(_ => new OverlapPageSet()).ToArray(); public readonly long[] OriginBytes = new long[OriginCount]; public readonly List<(ulong Address, ulong Size)> ReadRanges = new(); + public readonly List<(ulong Address, ulong Size, ulong Program)> DeviceRanges = new(); + public readonly List<(ulong Address, ulong Size, int Origin, ulong Program)> WriteRanges = new(); + public readonly List ReadHitAddresses = new(); + public int RsHit, RsNeighbour, WsReadLabel, WsReadGpu, WsReadNeighbour, WsWriteLabel, WsWriteGpu, WsWriteNeighbour, DaOnlyHit, DaOnlyNeighbour; + public long FirstRealWaitTicks, FirstK6Ticks; public readonly List Labels = new(); public readonly List AtomicTargets = new(); public long InPlaceBytes, StagedBytes, UploadBytes, DeviceAddressBytes, HugeRanges; @@ -366,14 +410,17 @@ private sealed class Window public readonly List InPlacePages = new(), InPlaceMb = new(), StagedMb = new(), UploadMb = new(), DaPages = new(), WrittenPages = new(), LabelsInCb = new(), DrainMs = new(), OverlapMs = new(), CompleteToAdmitMs = new(), ArmMs = new(), ArmedPages = new(), RsWritten = new(), DetachMb = new(), WsRead = new(), WsWritten = new(), LabelTouched = new(), CbTouched = new(), - DaOnly = new(), Managed = new(), FirstFaultMs = new(); + DaOnly = new(), Managed = new(), FirstFaultMs = new(), + RsHit = new(), RsNb = new(), WsRLabel = new(), WsRGpu = new(), WsRNb = new(), WsWLabel = new(), WsWGpu = new(), WsWNb = new(), + DaHit = new(), DaNb = new(), RealTrap = new(), RealWait = new(), DetachHitMb = new(), K6Ms = new(), RealWaitMs = new(), OverlapUntilWait = new(); + public int ArmedBeforeComplete, K6Frames, K6BeforeSubmit, RealWaitBeforeSubmit; public readonly double[] OriginPages = new double[OriginCount]; public long DaPlanned, DaUnplanned, Gds, GpuValued, Unbounded, AtomicInWrites, Huge, Skipped, Faults; } // ---- recording side ----------------------------------------------------------------- - public void MarkRead(ulong address, ulong size, OverlapRead kind) + public void MarkRead(ulong address, ulong size, OverlapRead kind, ulong program = 0) { if (size == 0 || size > ulong.MaxValue - address) { @@ -398,6 +445,7 @@ public void MarkRead(ulong address, ulong size, OverlapRead kind) case OverlapRead.DeviceAddress: frame.DeviceAddressBytes += (long)size; frame.DeviceAddress.Add(address, size); + frame.DeviceRanges.Add((address, size, program)); break; default: if (kind == OverlapRead.Upload) @@ -413,7 +461,7 @@ public void MarkRead(ulong address, ulong size, OverlapRead kind) } } - public void NoteWrite(ulong address, ulong size, OverlapWrite origin) + public void NoteWrite(ulong address, ulong size, OverlapWrite origin, ulong program = 0) { lock (_gate) { @@ -438,6 +486,7 @@ public void NoteWrite(ulong address, ulong size, OverlapWrite origin) frame.OriginBytes[(int)origin] += (long)size; frame.ByOrigin[(int)origin].Add(address, size); frame.Written.Add(address, size); + frame.WriteRanges.Add((address, size, (int)origin, program)); if (origin is OverlapWrite.CpWrite or OverlapWrite.EopDestination) { frame.Labels.Add(address); @@ -867,6 +916,7 @@ public bool TryHandleFault(FaultKind kind, ulong address, out bool stillBlocked) mask.Set((int)((page & (TrackerLayout.BlockBytes - 1)) / PageBytes)); frame.Pages[page] = (byte)(flags & ~Armed); Count(frame, page, flags, write: kind != FaultKind.Read); + Attribute(frame, address, flags, write: kind != FaultKind.Read); _watches.Remove(page & ~(TrackerLayout.BlockBytes - 1), mask, reads); stillBlocked = _watches.StillBlocks(page, kind); return true; @@ -902,6 +952,145 @@ public void NoteManagedWrite(ulong address, ulong size) } } + /// Which GPU ranges on the page the faulting address itself lies in. + internal static Hit ClassifyWrite(List<(ulong Address, ulong Size, int Origin, ulong Program)> ranges, ulong address, out int origin, out ulong program) + { + var hit = Hit.Neighbour; + origin = -1; + program = 0; + foreach (var range in ranges) + { + if (address < range.Address || address - range.Address >= range.Size) + { + continue; + } + + if (!KnownAtRecord(range.Origin)) + { + origin = range.Origin; + program = range.Program; + return Hit.GpuValued; + } + + hit = Hit.Label; + origin = range.Origin; + } + + return hit; + } + + private static bool Inside(List<(ulong Address, ulong Size)> ranges, ulong address) + { + foreach (var range in ranges) + { + if (address >= range.Address && address - range.Address < range.Size) return true; + } + + return false; + } + + private int _reported; + + // The first 60 real waits and device-address-only stores of the run, one line each: when, and before or + // after the guest's first submission of the next frame (none yet at the fault means before). + private void Report(string what, Frame frame, ulong address, bool write, int origin, ulong program, long now) + { + if (Interlocked.Increment(ref _reported) > 60) + { + return; + } + + var frequency = (double)Stopwatch.Frequency; + var sinceComplete = frame.CompletedTicks == 0 ? 0 : (now - frame.CompletedTicks) * 1000.0 / frequency; + Console.Error.WriteLine(string.Create(CultureInfo.InvariantCulture, + $"[METAL-V2][OVERLAP-DIAG-HIT] {what} frame={frame.Index} {(write ? "write" : "read")} 0x{address:X} origin={(origin >= 0 ? OriginNames[origin] : "-")} " + + $"prog=0x{program:X16} ms_after_complete={(frame.CompletedTicks == 0 ? "before" : sinceComplete.ToString("F2", CultureInfo.InvariantCulture))} " + + $"ms_after_commit={(now - frame.CommittedTicks) * 1000.0 / frequency:F2} before_first_submit={(frame.FirstAdmitTicks == 0 || now < frame.FirstAdmitTicks ? 1 : 0)}")); + } + + private void Attribute(Frame frame, ulong address, byte flags, bool write) + { + var now = _clock(); + var page = address & ~(PageBytes - 1); + var what = new StringBuilder(); + if ((flags & InWrite) != 0) + { + var hit = ClassifyWrite(frame.WriteRanges, address, out var origin, out var program); + if (hit == Hit.GpuValued) + { + if (write) frame.WsWriteGpu++; else frame.WsReadGpu++; + if (frame.FirstRealWaitTicks == 0) frame.FirstRealWaitTicks = now; + if (!write && frame.FirstK6Ticks == 0) frame.FirstK6Ticks = now; + Report("K6", frame, address, write, origin, program, now); + } + else if (hit == Hit.Label) + { + if (write) frame.WsWriteLabel++; else frame.WsReadLabel++; + } + else + { + if (write) frame.WsWriteNeighbour++; else frame.WsReadNeighbour++; + } + + what.Append(hit switch { Hit.GpuValued => "gpu_hit", Hit.Label => "label_hit", _ => "neighbour" }); + if (origin >= 0) what.Append(':').Append(OriginNames[origin]); + if (program != 0) what.Append(CultureInfo.InvariantCulture, $":prog=0x{program:X16}"); + } + + if ((flags & InRead) != 0 && write) + { + var hit = Inside(frame.ReadRanges, address); + if (hit) { frame.RsHit++; frame.ReadHitAddresses.Add(address); } else frame.RsNeighbour++; + what.Append(what.Length != 0 ? "," : string.Empty).Append(hit ? "read_set_hit" : "read_set_neighbour"); + } + + if ((flags & DeviceAddressOnly) != 0 && write) + { + var hit = false; + ulong program = 0; + foreach (var range in frame.DeviceRanges) + { + if (address >= range.Address && address - range.Address < range.Size) { hit = true; program = range.Program; break; } + } + + if (hit) frame.DaOnlyHit++; else frame.DaOnlyNeighbour++; + Report(hit ? "K3-hit" : "K3-neighbour", frame, address, write, (int)OverlapWrite.DeviceAddress, program, now); + what.Append(what.Length != 0 ? "," : string.Empty).Append(hit ? "da_only_hit" : "da_only_neighbour"); + if (program != 0) what.Append(CultureInfo.InvariantCulture, $":prog=0x{program:X16}"); + } + + lock (_pageReports) + { + if (!_pageReports.TryGetValue(page, out var report)) + { + report = new PageReport(); + _pageReports[page] = report; + foreach (var range in frame.WriteRanges) + { + if (report.Ranges.Count < 8 && range.Address < page + PageBytes && page < range.Address + range.Size) + report.Ranges.Add(string.Create(CultureInfo.InvariantCulture, + $"{OriginNames[range.Origin]}:0x{range.Address:X}+0x{range.Size:X}{(range.Program != 0 ? $":prog=0x{range.Program:X16}" : string.Empty)}")); + } + + foreach (var range in frame.ReadRanges) + { + if (report.Ranges.Count < 8 && range.Address < page + PageBytes && page < range.Address + range.Size) + report.Ranges.Add(string.Create(CultureInfo.InvariantCulture, $"read:0x{range.Address:X}+0x{range.Size:X}")); + } + + foreach (var range in frame.DeviceRanges) + { + if (report.Ranges.Count < 8 && range.Address < page + PageBytes && page < range.Address + range.Size) + report.Ranges.Add(string.Create(CultureInfo.InvariantCulture, $"da_read:0x{range.Address:X}+0x{range.Size:X}:prog=0x{range.Program:X16}")); + } + } + + report.Faults++; + var access = string.Create(CultureInfo.InvariantCulture, $"0x{address & (PageBytes - 1):X3}{(write ? "w" : "r")}={what}"); + if (report.Accesses.Count < 8 && !report.Accesses.Contains(access)) report.Accesses.Add(access); + } + } + private void Count(Frame frame, ulong page, byte flags, bool write) { if (frame.FirstFaultTicks == 0) @@ -988,6 +1177,20 @@ internal void FinalizeFrame(Frame frame) } // Bytes of the bound ranges the guest wrote while it built the next frame: what would be detached. + // Bound ranges that contain a written address itself (not just its page). + long detachHitBytes = 0; + foreach (var range in frame.ReadRanges) + { + foreach (var address in frame.ReadHitAddresses) + { + if (address >= range.Address && address - range.Address < range.Size) + { + detachHitBytes += (long)range.Size; + break; + } + } + } + long detachBytes = 0; if (frame.ReadWrittenPages.Count != 0) { @@ -1066,6 +1269,35 @@ internal void FinalizeFrame(Frame frame) window.FirstFaultMs.Add(Ms(frame.CompletedTicks, frame.FirstFaultTicks)); if (frame.FirstAdmitTicks == 0 || frame.FirstFaultTicks < frame.FirstAdmitTicks) window.TrapBeforeSubmitFrames++; } + + if (frame.ArmedTicks < frame.CompletedTicks) window.ArmedBeforeComplete++; + window.RsHit.Add(frame.RsHit); window.RsNb.Add(frame.RsNeighbour); + window.WsRLabel.Add(frame.WsReadLabel); window.WsRGpu.Add(frame.WsReadGpu); window.WsRNb.Add(frame.WsReadNeighbour); + window.WsWLabel.Add(frame.WsWriteLabel); window.WsWGpu.Add(frame.WsWriteGpu); window.WsWNb.Add(frame.WsWriteNeighbour); + window.DaHit.Add(frame.DaOnlyHit); window.DaNb.Add(frame.DaOnlyNeighbour); + window.RealTrap.Add(frame.RsHit + frame.WsReadGpu + frame.WsWriteGpu + frame.DaOnlyHit); + window.RealWait.Add(frame.WsReadGpu + frame.WsWriteGpu); + window.DetachHitMb.Add(detachHitBytes / 1048576.0); + var available = Ms(frame.CommittedTicks, frame.CompletedTicks); + if (frame.FirstK6Ticks != 0) + { + window.K6Frames++; + window.K6Ms.Add(Ms(frame.CompletedTicks, frame.FirstK6Ticks)); + if (frame.FirstAdmitTicks == 0 || frame.FirstK6Ticks < frame.FirstAdmitTicks) window.K6BeforeSubmit++; + } + + if (frame.FirstRealWaitTicks != 0) + { + var wait = Ms(frame.CompletedTicks, frame.FirstRealWaitTicks); + window.RealWaitMs.Add(wait); + if (frame.FirstAdmitTicks == 0 || frame.FirstRealWaitTicks < frame.FirstAdmitTicks) window.RealWaitBeforeSubmit++; + // Build work done before the first real wait is what an overlap would hide. + window.OverlapUntilWait.Add(Math.Clamp(wait, 0, double.IsNaN(available) ? 0 : available)); + } + else + { + window.OverlapUntilWait.Add(available); + } } } } @@ -1097,7 +1329,12 @@ public string TakeWindowLine() builder.Append(culture, $"trap: armed_pages={Mx(w.ArmedPages)} arm_ms={P(w.ArmMs)} late_arms={w.LateArms} late_faults={Interlocked.Exchange(ref _lateFaults, 0)} cap_frames={w.CapFrames} skipped_read_watched={w.Skipped} "); builder.Append($"rs_written={Mx(w.RsWritten)} detach_mb={Mx(w.DetachMb)} ws_read={Mx(w.WsRead)} ws_written={Mx(w.WsWritten)} "); builder.Append($"label_touched={Mx(w.LabelTouched)} cb_touched={Mx(w.CbTouched)} da_only_written={Mx(w.DaOnly)} managed={Mx(w.Managed)} first_fault_ms={P(w.FirstFaultMs)} "); - builder.Append(culture, $"trap_before_submit_frames={w.TrapBeforeSubmitFrames} ws_read_frames={w.WriteSetReadFrames}"); + builder.Append(culture, $"trap_before_submit_frames={w.TrapBeforeSubmitFrames} ws_read_frames={w.WriteSetReadFrames} | "); + builder.Append(culture, $"bytes: armed_before_complete={w.ArmedBeforeComplete} rs_hit={Mx(w.RsHit)} rs_nb={Mx(w.RsNb)} detach_hit_mb={Mx(w.DetachHitMb)} "); + builder.Append($"ws_read label={Mx(w.WsRLabel)} gpu={Mx(w.WsRGpu)} nb={Mx(w.WsRNb)} ws_write label={Mx(w.WsWLabel)} gpu={Mx(w.WsWGpu)} nb={Mx(w.WsWNb)} "); + builder.Append($"da_only hit={Mx(w.DaHit)} nb={Mx(w.DaNb)} real_trap_pages={Mx(w.RealTrap)} real_wait_pages={Mx(w.RealWait)} "); + builder.Append(culture, $"k6_frames={w.K6Frames} k6_ms={P(w.K6Ms)} k6_before_submit={w.K6BeforeSubmit} "); + builder.Append(culture, $"real_wait_ms={P(w.RealWaitMs)} real_wait_before_submit={w.RealWaitBeforeSubmit} overlap_until_wait_ms={P(w.OverlapUntilWait)}"); _window.Frames = 0; ResetWindow(); } @@ -1121,6 +1358,15 @@ internal string TopRanges() } } + lock (_pageReports) + { + foreach (var pair in _pageReports.OrderByDescending(pair => pair.Value.Faults).Take(10)) + { + builder.Append(CultureInfo.InvariantCulture, $"\n[METAL-V2][OVERLAP-DIAG-PAGE] 0x{pair.Key:X} faults={pair.Value.Faults} ranges=[{string.Join(' ', pair.Value.Ranges)}] accesses=[{string.Join(' ', pair.Value.Accesses)}]"); + } + } + + builder.Append("\n[METAL-V2][OVERLAP-DIAG-TOP]"); builder.Append(" | wait (GPU-written pages the guest touched):"); lock (_topWaits) { @@ -1138,6 +1384,13 @@ private void ResetWindow() var w = _window; w.Frames = w.Sampled = w.CapFrames = w.UnfinishedFrames = w.BlockedFrames = w.RefusedFrames = w.TrapBeforeSubmitFrames = 0; w.WriteSetReadFrames = w.LateArms = 0; + w.ArmedBeforeComplete = w.K6Frames = w.K6BeforeSubmit = w.RealWaitBeforeSubmit = 0; + foreach (var list in new[] { w.RsHit, w.RsNb, w.WsRLabel, w.WsRGpu, w.WsRNb, w.WsWLabel, w.WsWGpu, w.WsWNb, w.DaHit, w.DaNb, + w.RealTrap, w.RealWait, w.DetachHitMb, w.K6Ms, w.RealWaitMs, w.OverlapUntilWait }) + { + list.Clear(); + } + w.DaPlanned = w.DaUnplanned = w.Gds = w.GpuValued = w.Unbounded = w.AtomicInWrites = w.Huge = w.Skipped = w.Faults = 0; Array.Clear(w.OriginPages); foreach (var list in new[] { w.InPlacePages, w.InPlaceMb, w.StagedMb, w.UploadMb, w.DaPages, w.WrittenPages, w.LabelsInCb, diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalCommandStream.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalCommandStream.cs index ebecfb534..2353964ff 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalCommandStream.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalCommandStream.cs @@ -1016,20 +1016,24 @@ private void RecordEndOfPipeGdsWrite(in EndOfPipeWrite write) private static void NoteEndOfPipeForOverlapDiagnostic(in EndOfPipeWrite write) { var bytes = (ulong)EndOfPipeLabelBytes(write.Kind); + var origin = SharpEmu.HLE.GpuMemory.OverlapWrite.EopDestination; switch (write.Kind) { case EndOfPipeWriteKind.GdsWrite32: SharpEmu.HLE.GpuMemory.FrameOverlapDiagnostic.NoteRefusal(gds: true); bytes = (ulong)write.GdsWordCount * sizeof(uint); + origin = SharpEmu.HLE.GpuMemory.OverlapWrite.EopGpuValued; break; case EndOfPipeWriteKind.AtomicAdd32: SharpEmu.HLE.GpuMemory.FrameOverlapDiagnostic.NoteEndOfPipeAtomicAdd(write.Destination); bytes = sizeof(uint); + origin = SharpEmu.HLE.GpuMemory.OverlapWrite.EopGpuValued; break; default: if (IsClockLabel(in write)) { SharpEmu.HLE.GpuMemory.FrameOverlapDiagnostic.NoteRefusal(gds: false); + origin = SharpEmu.HLE.GpuMemory.OverlapWrite.EopGpuValued; } break; @@ -1037,7 +1041,7 @@ private static void NoteEndOfPipeForOverlapDiagnostic(in EndOfPipeWrite write) if (write.Destination != 0 && bytes != 0) { - SharpEmu.HLE.GpuMemory.FrameOverlapDiagnostic.NoteGpuWrite(write.Destination, bytes, SharpEmu.HLE.GpuMemory.OverlapWrite.EopDestination); + SharpEmu.HLE.GpuMemory.FrameOverlapDiagnostic.NoteGpuWrite(write.Destination, bytes, origin); } } diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Descriptors.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Descriptors.cs index c31a7ccda..5a123ed80 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Descriptors.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Descriptors.cs @@ -1112,6 +1112,11 @@ public void BindResources(IPreparedBindings prepared) using (var noteScope = SharpEmu.Libs.VideoOut.RenderPhaseProfile.MeasureDetail(SharpEmu.Libs.VideoOut.RenderPhaseProfile.Phase.BindingWrittenNote)) { + if (SharpEmu.HLE.GpuMemory.FrameOverlapDiagnostic.Enabled) + { + SharpEmu.HLE.GpuMemory.FrameOverlapDiagnostic.SetWriter(stage.Program.Hash); + } + NoteGuestMemoryWrite(descriptor.Address, size, MetalGpuWriteOrigin.StorageBuffer); } } @@ -1221,7 +1226,7 @@ private void BindDeviceAddressRanges( var size = ClampMappedSize(range.Base, range.Size); if (SharpEmu.HLE.GpuMemory.FrameOverlapDiagnostic.Enabled) { - SharpEmu.HLE.GpuMemory.FrameOverlapDiagnostic.MarkGpuRead(range.Base, size, SharpEmu.HLE.GpuMemory.OverlapRead.DeviceAddress); + SharpEmu.HLE.GpuMemory.FrameOverlapDiagnostic.MarkGpuRead(range.Base, size, SharpEmu.HLE.GpuMemory.OverlapRead.DeviceAddress, stage.Program.Hash); } if (_traceBufferUserAddress != 0) @@ -1256,6 +1261,11 @@ private void BindDeviceAddressRanges( } _imageCache.InvalidateMemoryFromGpu(range.Base, size); + if (SharpEmu.HLE.GpuMemory.FrameOverlapDiagnostic.Enabled) + { + SharpEmu.HLE.GpuMemory.FrameOverlapDiagnostic.SetWriter(stage.Program.Hash); + } + NoteGuestMemoryWrite(range.Base, size, MetalGpuWriteOrigin.DeviceAddress); _slotTrap?.NoteBinding( $"device_address handle={range.Handle} hash=0x{stage.Program.Hash:X16} written", diff --git a/tests/SharpEmu.Libs.Tests/HLE/FrameOverlapTrackerTests.cs b/tests/SharpEmu.Libs.Tests/HLE/FrameOverlapTrackerTests.cs index a6729c8d0..91631a91b 100644 --- a/tests/SharpEmu.Libs.Tests/HLE/FrameOverlapTrackerTests.cs +++ b/tests/SharpEmu.Libs.Tests/HLE/FrameOverlapTrackerTests.cs @@ -222,6 +222,62 @@ public void AFaultThatRacedTheDisarmIsRetriedOncePerPage() Assert.Contains("late_faults=1", tracker.TakeWindowLine()); } + [Fact] + public void FaultsAreSplitIntoHitsNeighboursAndRecordTimeLabels() + { + var watches = new FakeWatches(); + var tracker = Create(watches); + tracker.MarkRead(0x10000, 0x100, OverlapRead.InPlace); + tracker.MarkRead(0x20000, 0x100, OverlapRead.InPlace); + tracker.MarkRead(0x60000, 0x10, OverlapRead.DeviceAddress, program: 0xDA); + tracker.NoteWrite(0x30000, 0x100, OverlapWrite.Storage, program: 0xABC); + tracker.NoteWrite(0x31800, 0x10, OverlapWrite.Storage); + tracker.NoteWrite(0x40008, 8, OverlapWrite.CpWrite); + tracker.OnBoundaryAdmitted(0, 0); + _now = 10 * Millisecond; + tracker.OnFrameCommitted(1); + _now = 50 * Millisecond; + tracker.OnCompleted(1); + tracker.DrainRequests(); + + _now = 53 * Millisecond; + Assert.True(tracker.TryHandleFault(FaultKind.Write, 0x10F00, out _)); // read set, other bytes of the page + Assert.True(tracker.TryHandleFault(FaultKind.Write, 0x20010, out _)); // read set, inside the bound range + Assert.True(tracker.TryHandleFault(FaultKind.Read, 0x30010, out _)); // GPU-valued store: a real wait + Assert.True(tracker.TryHandleFault(FaultKind.Read, 0x31000, out _)); // shares the page only + Assert.True(tracker.TryHandleFault(FaultKind.Read, 0x4000C, out _)); // a CP write: landed at publication + Assert.True(tracker.TryHandleFault(FaultKind.Write, 0x60008, out _)); // device-address reach itself + _now = 55 * Millisecond; + tracker.OnAdmission(0x90000, 0x40); + tracker.OnBoundaryAdmitted(0, 0); + tracker.DrainRequests(); + + var line = tracker.TakeWindowLine(); + Assert.Contains("armed_before_complete=0", line); + Assert.Contains("rs_hit=1/1 rs_nb=1/1", line); + Assert.Contains("ws_read label=1/1 gpu=1/1 nb=1/1", line); + Assert.Contains("da_only hit=1/1 nb=0/0", line); + Assert.Contains("real_trap_pages=3/3 real_wait_pages=1/1", line); + Assert.Contains("k6_frames=1 k6_ms=3/3 k6_before_submit=1", line); + Assert.Contains("overlap_until_wait_ms=3/3", line); + var pages = tracker.TopRanges(); + Assert.Contains("0x30000 faults=1 ranges=[storage:0x30000+0x100:prog=0x0000000000000ABC] accesses=[0x010r=gpu_hit:storage:prog=0x0000000000000ABC]", pages); + Assert.Contains("0x008w=da_only_hit:prog=0x00000000000000DA", pages); + } + + [Fact] + public void AGpuValuedRangeOutranksALabelOverTheSameBytes() + { + var ranges = new List<(ulong, ulong, int, ulong)> + { + (0x1000, 8, (int)OverlapWrite.EopLabel, 0), + (0x1000, 8, (int)OverlapWrite.EopGpuValued, 0), + }; + Assert.Equal(FrameOverlapTracker.Hit.GpuValued, FrameOverlapTracker.ClassifyWrite(ranges, 0x1004, out _, out _)); + Assert.Equal(FrameOverlapTracker.Hit.Label, FrameOverlapTracker.ClassifyWrite(ranges.Take(1).ToList(), 0x1004, out _, out _)); + Assert.Equal(FrameOverlapTracker.Hit.Neighbour, FrameOverlapTracker.ClassifyWrite(ranges, 0x1008, out _, out _)); + } + [Fact] public void ThePageSetCountsDistinctPagesAcrossBlocks() { From d215a62cc9492c1237558e4f84094d518baea1b7 Mon Sep 17 00:00:00 2001 From: kuba Date: Mon, 16 Nov 2026 07:28:51 +0000 Subject: [PATCH 123/178] [Diag] Frame-overlap: retry every thread that faults on a page the diagnostic released r ovl3 (arm at commit, read watches on): six job workers read one read-watched page at once; the first fault released it, the other five found it no longer armed and were declined, and the run died with SIGBUS at 89 s. A fault on any page of the armed or the last released frame that the guard no longer blocks is now retried (late_faults), at most 256 times a page per armed frame, with a WARN beyond. Write faults never hit this: the page guard's write-restoration version already retries them. Not yet run in a game. --- .../GpuMemory/FrameOverlapDiagnostic.cs | 30 +++++++++++++----- .../HLE/FrameOverlapTrackerTests.cs | 31 ++++++++++++++++--- 2 files changed, 48 insertions(+), 13 deletions(-) diff --git a/src/SharpEmu.HLE/GpuMemory/FrameOverlapDiagnostic.cs b/src/SharpEmu.HLE/GpuMemory/FrameOverlapDiagnostic.cs index 38c15182e..e59cf57dc 100644 --- a/src/SharpEmu.HLE/GpuMemory/FrameOverlapDiagnostic.cs +++ b/src/SharpEmu.HLE/GpuMemory/FrameOverlapDiagnostic.cs @@ -310,7 +310,6 @@ private sealed class PageReport private const byte ReadArmed = 16; private const byte Armed = 32; private const byte ManagedSeen = 64; - private const byte Retried = 128; private readonly IFrameOverlapWatches _watches; private readonly Func _clock; @@ -344,6 +343,12 @@ private sealed class PageReport private Frame? _released; private long _lateFaults; + // Retries answered per page: several guest threads can fault on one page at once (r ovl3: six job + // workers reading one read-watched page; the first released it, the other five were declined and + // the run died). Bounded so a page some other protection holds cannot loop forever. + private const int MaxRetriesPerPage = 256; + private readonly Dictionary _retries = new(); + private readonly Window _window = new(); private readonly Dictionary _topDetach = new(); private readonly Dictionary _topWaits = new(); @@ -759,6 +764,7 @@ internal void Arm(Frame frame) lock (_watchGate) { + _retries.Clear(); Volatile.Write(ref _armed, frame); foreach (var block in blocks) { @@ -898,14 +904,22 @@ public bool TryHandleFault(FaultKind kind, ulong address, out bool stillBlocked) { if (_armed is not { } frame || !frame.Pages.TryGetValue(page, out var flags) || (flags & Armed) == 0) { - // Released already, but the access faulted on the protection the watch had: once - // the release is applied the access goes through, so it is retried, once a page. - if (_released is { } released && released.Pages.TryGetValue(page, out var old) && (old & Retried) == 0 && - !_watches.StillBlocks(page, kind)) + // Released already (by another thread's fault on the page, or by the disarm), but the + // access faulted on the protection the watch had: once the release is applied the + // access goes through, so it is retried. + var owned = (_armed is { } current && current.Pages.ContainsKey(page)) || + (_released is { } released && released.Pages.ContainsKey(page)); + if (owned && !_watches.StillBlocks(page, kind)) { - released.Pages[page] = (byte)(old | Retried); - Interlocked.Increment(ref _lateFaults); - return true; + var retries = _retries.GetValueOrDefault(page); + if (retries < MaxRetriesPerPage) + { + _retries[page] = retries + 1; + Interlocked.Increment(ref _lateFaults); + return true; + } + + Console.Error.WriteLine($"[METAL-V2][OVERLAP-DIAG][WARN] page 0x{page:X}: {MaxRetriesPerPage} retries answered, declining the fault"); } return false; diff --git a/tests/SharpEmu.Libs.Tests/HLE/FrameOverlapTrackerTests.cs b/tests/SharpEmu.Libs.Tests/HLE/FrameOverlapTrackerTests.cs index 91631a91b..55332c69d 100644 --- a/tests/SharpEmu.Libs.Tests/HLE/FrameOverlapTrackerTests.cs +++ b/tests/SharpEmu.Libs.Tests/HLE/FrameOverlapTrackerTests.cs @@ -79,10 +79,12 @@ public void ACompletedFrameArmsItsInPlaceReadsForWritesAndItsWritesForReads() Assert.False(watches.Counts.ContainsKey((0x20000, false))); Assert.Equal(4, watches.Live); - // The first fault on a page is counted and lets the page go; the second is someone else's. + // The first fault on a page is counted and lets the page go; a second one (another thread that + // faulted before the release was applied) is retried without being counted again. Assert.True(tracker.TryHandleFault(FaultKind.Write, 0x10010, out var blocked)); Assert.False(blocked); - Assert.False(tracker.TryHandleFault(FaultKind.Write, 0x10020, out _)); + Assert.True(tracker.TryHandleFault(FaultKind.Write, 0x10020, out _)); + Assert.False(tracker.TryHandleFault(FaultKind.Write, 0x90000, out _)); _now = 52 * Millisecond; tracker.OnAdmission(0x50000, 0x100); Assert.True(tracker.TryHandleFault(FaultKind.Read, 0x40010, out _)); @@ -214,12 +216,31 @@ public void AFaultThatRacedTheDisarmIsRetriedOncePerPage() tracker.DrainRequests(); Assert.Equal(0, watches.Live); - // The guest read the page before the given-back protection reached it. + // The guest read the page before the given-back protection reached it (two threads at once). Assert.True(tracker.TryHandleFault(FaultKind.Read, 0x40000, out var blocked)); Assert.False(blocked); - Assert.False(tracker.TryHandleFault(FaultKind.Read, 0x40000, out _)); + Assert.True(tracker.TryHandleFault(FaultKind.Read, 0x40000, out _)); Assert.False(tracker.TryHandleFault(FaultKind.Read, 0x50000, out _)); - Assert.Contains("late_faults=1", tracker.TakeWindowLine()); + Assert.Contains("late_faults=2", tracker.TakeWindowLine()); + } + + [Fact] + public void ASecondThreadFaultingOnAPageAnotherThreadReleasedIsRetried() + { + var watches = new FakeWatches(); + var tracker = Create(watches); + tracker.NoteWrite(0x40000, 8, OverlapWrite.Storage); + tracker.OnBoundaryAdmitted(0, 0); + tracker.OnFrameCommitted(1); + tracker.OnCompleted(1); + tracker.DrainRequests(); + Assert.True(tracker.TryHandleFault(FaultKind.Read, 0x40000, out _)); + Assert.True(tracker.TryHandleFault(FaultKind.Read, 0x40004, out _)); + tracker.OnBoundaryAdmitted(0, 0); + tracker.DrainRequests(); + var line = tracker.TakeWindowLine(); + Assert.Contains("ws_read=1/1", line); + Assert.Contains("late_faults=1", line); } [Fact] From 8ba199851e1c0a83e8879b6655968551c5fc8449 Mon Sep 17 00:00:00 2001 From: kuba Date: Mon, 16 Nov 2026 01:24:31 +0000 Subject: [PATCH 124/178] [VideoOut] Flip ahead: publish a recorded flip once the flip before it has really completed SHARPEMU_FLIP_AHEAD=1, default off. A GPU-queued flip the GPU host reports recorded, committed and captured as a copy (NoteFlipRecorded, carried across the split as FlipEvent Recorded) has its guest-visible completion published once the GPU-queued flip before it on the handle has really completed and been published; only the oldest unpublished request on a handle may go, so an unpublished CPU flip before it holds it back. The request stays for the pacer; its real completion still releases the GPU slot and sets the ready timestamp without publishing again or re-triggering events, and a cancel gives the slot back. A notice that arrives after the real completion is ignored. Off, or without notices, the sequence is unchanged. [VIDEOOUT][FLIP-AHEAD] reports flips published at record, at the previous completion, late notices and the mean lead over the real completion, at most every 2 s. --- src/SharpEmu.GpuRemote/GpuSplitMessages.cs | 3 + src/SharpEmu.GpuSplit/GuestProcessSide.cs | 3 + src/SharpEmu.GpuSplit/RemoteVideoOutBridge.cs | 2 + .../VideoOut/VideoOutBackendServices.cs | 12 + .../VideoOut/VideoOutExports.FlipAhead.cs | 233 ++++++++++++++ .../VideoOut/VideoOutExports.FlipRequests.cs | 74 ++++- .../Gpu/Split/SplitHookTests.cs | 2 + .../VideoOut/VideoOutFlipAheadTests.cs | 292 ++++++++++++++++++ 8 files changed, 610 insertions(+), 11 deletions(-) create mode 100644 src/SharpEmu.Libs/VideoOut/VideoOutExports.FlipAhead.cs create mode 100644 tests/SharpEmu.Libs.Tests/VideoOut/VideoOutFlipAheadTests.cs diff --git a/src/SharpEmu.GpuRemote/GpuSplitMessages.cs b/src/SharpEmu.GpuRemote/GpuSplitMessages.cs index d9eccfd68..359b55cb2 100644 --- a/src/SharpEmu.GpuRemote/GpuSplitMessages.cs +++ b/src/SharpEmu.GpuRemote/GpuSplitMessages.cs @@ -43,6 +43,9 @@ public enum GpuSplitFlipEvent : uint /// CompleteFlip. Completed = 6, + + /// NoteFlipRecorded (SHARPEMU_FLIP_AHEAD). + Recorded = 7, } /// The kinds of . diff --git a/src/SharpEmu.GpuSplit/GuestProcessSide.cs b/src/SharpEmu.GpuSplit/GuestProcessSide.cs index 425f27518..da4d46cd2 100644 --- a/src/SharpEmu.GpuSplit/GuestProcessSide.cs +++ b/src/SharpEmu.GpuSplit/GuestProcessSide.cs @@ -77,6 +77,9 @@ public void FlipEvent(GpuSplitFlipEvent kind, ulong requestId) case GpuSplitFlipEvent.Completed: VideoOutBackendServices.CompleteFlip(requestId); break; + case GpuSplitFlipEvent.Recorded: + VideoOutBackendServices.NoteFlipRecorded(requestId); + break; } } diff --git a/src/SharpEmu.GpuSplit/RemoteVideoOutBridge.cs b/src/SharpEmu.GpuSplit/RemoteVideoOutBridge.cs index 517144961..680a187c2 100644 --- a/src/SharpEmu.GpuSplit/RemoteVideoOutBridge.cs +++ b/src/SharpEmu.GpuSplit/RemoteVideoOutBridge.cs @@ -83,6 +83,8 @@ public bool IsFlipPresentationPending(ulong requestId) => public void MarkFlipPresented(ulong requestId) => FlipEvent(GpuSplitFlipEvent.Presented, requestId); + public void NoteFlipRecorded(ulong requestId) => FlipEvent(GpuSplitFlipEvent.Recorded, requestId); + public void NotifyPresentationWindowClosed() => host.SendNotice(GpuSplitNotice.PresentationWindowClosed); // Only a flip that names no buffer (-1) is released here; every other flip answers false without diff --git a/src/SharpEmu.Libs/VideoOut/VideoOutBackendServices.cs b/src/SharpEmu.Libs/VideoOut/VideoOutBackendServices.cs index 3b3dda0c5..aba99437e 100644 --- a/src/SharpEmu.Libs/VideoOut/VideoOutBackendServices.cs +++ b/src/SharpEmu.Libs/VideoOut/VideoOutBackendServices.cs @@ -74,6 +74,16 @@ public static void CompleteFlipOnGpu(ulong requestId) VideoOutExports.CompleteFlipOnGpu(requestId); } + // SHARPEMU_FLIP_AHEAD: the GPU host recorded the flip, committed the buffer carrying it + // and captured its frame as a copy (VideoOutExports.NoteFlipRecorded). + public static void NoteFlipRecorded(ulong requestId) + { + if (Bridge is { } bridge) + bridge.NoteFlipRecorded(requestId); + else + VideoOutExports.NoteFlipRecorded(requestId); + } + public static void DiscardFlip(ulong requestId) { if (Bridge is { } bridge) @@ -204,6 +214,8 @@ public interface IVideoOutBackendBridge void MarkFlipPresented(ulong requestId); + void NoteFlipRecorded(ulong requestId); + void NotifyPresentationWindowClosed(); bool ReleaseNoBufferFlip(int bufferIndex, ulong requestId); diff --git a/src/SharpEmu.Libs/VideoOut/VideoOutExports.FlipAhead.cs b/src/SharpEmu.Libs/VideoOut/VideoOutExports.FlipAhead.cs new file mode 100644 index 000000000..4ab7b331e --- /dev/null +++ b/src/SharpEmu.Libs/VideoOut/VideoOutExports.FlipAhead.cs @@ -0,0 +1,233 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using System.Diagnostics; + +namespace SharpEmu.Libs.VideoOut; + +// SHARPEMU_FLIP_AHEAD=1 (experimental, default off). A GPU-queued flip's guest-visible +// completion (flip count, process time, flip arg, current buffer, the previous buffer's +// label, the pending count and the flip events) is published once the GPU host has recorded +// the flip, committed the buffer carrying it and handed the presenter a copy of its frame +// (NoteFlipRecorded), and the GPU-queued flip before it on the handle has really completed +// on the GPU and been published. The guest is then at most one flip ahead of the GPU. The +// request itself stays in the table for the pacer, which presents or drops it as before, and +// its real GPU completion still releases the GPU slot and sets the ready timestamp. Without +// the notice (switch off, or a flip whose frame was not copied) nothing here runs. +public static partial class VideoOutExports +{ + internal static bool FlipAheadEnabled { get; set; } = string.Equals( + Environment.GetEnvironmentVariable("SHARPEMU_FLIP_AHEAD"), "1", StringComparison.Ordinal); + + // The last GPU-queued request reserved on each handle. Guarded by the state gate. + private static readonly Dictionary _lastGpuQueuedFlip = new(); + + private static long _flipAheadAtRecord; + private static long _flipAheadAtPrevious; + private static long _flipAheadLateNotices; + private static long _flipAheadLeadTicks; + private static long _flipAheadLeadCount; + private static long _flipAheadReportedAt; + + // Caller holds the state gate. + private static void NoteGpuQueuedFlipLocked(FlipRequest request) + { + if (_lastGpuQueuedFlip.TryGetValue(request.Handle, out var previous) && + previous.Outcome != FlipOutcome.Cancelled && + !(previous.State == FlipRequestState.Completed && previous.GpuCompleted && previous.EventsTriggered)) + { + request.AheadPrevious = previous; + } + + _lastGpuQueuedFlip[request.Handle] = request; + } + + /// + /// The GPU host recorded this flip, committed the command buffer that carries it and + /// captured its frame as a copy the guest cannot overwrite. A notice for a request that is + /// already past that point (its real completion came first, it was cancelled or published) + /// is ignored, and the flip keeps today's timing. + /// + internal static void NoteFlipRecorded(ulong requestId) + { + if (!FlipAheadEnabled) + { + return; + } + + int handle; + lock (_stateGate) + { + if (!_flipRequests.TryGetValue(requestId, out var request) || !request.GpuQueued || + request.State != FlipRequestState.Reserved) + { + Interlocked.Increment(ref _flipAheadLateNotices); + return; + } + + request.AheadRecorded = true; + handle = request.Handle; + } + + DrainFlipAhead(handle, requestId); + } + + // Caller holds the state gate. The real completion of a flip published ahead. + private static void CompleteAheadFlipOnGpuLocked(FlipRequest request) + { + ReleaseGpuQueueSlotLocked(request); + request.GpuCompleted = true; + Interlocked.Add(ref _flipAheadLeadTicks, Math.Max(0, Stopwatch.GetTimestamp() - request.AheadPublishedAt)); + Interlocked.Increment(ref _flipAheadLeadCount); + RemoveIfFinishedLocked(request); + Monitor.PulseAll(_stateGate); + } + + // Outside the state gate. The flip's counters were published: trigger its events, then let + // the flip after it go ahead if it was waiting for this one. + private static void TriggerPublishedFlip(FlipRequest request) + { + TriggerFlipEvents(request); + if (!FlipAheadEnabled) + { + return; + } + + lock (_stateGate) + { + request.EventsTriggered = true; + } + + DrainFlipAhead(request.Handle, noticed: 0); + } + + // Outside the state gate. Publishes, oldest first, every flip on the handle that may go + // ahead now. noticed is the request whose recorded notice is being handled, if any. + private static void DrainFlipAhead(int handle, ulong noticed) + { + if (!FlipAheadEnabled) + { + return; + } + + while (true) + { + FlipRequest? next; + lock (_stateGate) + { + next = FindFlipAheadCandidateLocked(handle); + if (next is not null) + { + // Set first: a dropped frame's request must outlive the publication until its + // real completion releases the GPU slot (RemoveIfFinishedLocked). + next.AheadPublishedAt = Stopwatch.GetTimestamp(); + PublishFlipLocked(next); + Interlocked.Increment(ref next.RequestId == noticed ? ref _flipAheadAtRecord : ref _flipAheadAtPrevious); + } + } + + if (next is null) + { + break; + } + + TriggerFlipEvents(next); + lock (_stateGate) + { + next.EventsTriggered = true; + } + } + + ReportFlipAhead(); + } + + // Caller holds the state gate. Only the oldest unpublished request on the handle may be + // published, so the guest sees flips in order; an unpublished CPU flip before it blocks it. + private static FlipRequest? FindFlipAheadCandidateLocked(int handle) + { + FlipRequest? oldest = null; + foreach (var request in _flipRequests.Values) + { + if (request.Handle == handle && request.State != FlipRequestState.Completed && + (oldest is null || request.RequestId < oldest.RequestId)) + { + oldest = request; + } + } + + if (oldest is null || !oldest.AheadRecorded || !oldest.GpuQueued || oldest.State != FlipRequestState.Reserved) + { + return null; + } + + var previous = oldest.AheadPrevious; + if (previous is not null && previous.Outcome != FlipOutcome.Cancelled && + !(previous.State == FlipRequestState.Completed && previous.GpuCompleted && previous.EventsTriggered)) + { + return null; + } + + return oldest; + } + + // At most one line every two seconds, and only while flips go ahead. + private static void ReportFlipAhead() + { + var now = Stopwatch.GetTimestamp(); + var last = Interlocked.Read(ref _flipAheadReportedAt); + if (now - last < 2 * Stopwatch.Frequency || + Interlocked.CompareExchange(ref _flipAheadReportedAt, now, last) != last) + { + return; + } + + var atRecord = Interlocked.Exchange(ref _flipAheadAtRecord, 0); + var atPrevious = Interlocked.Exchange(ref _flipAheadAtPrevious, 0); + var late = Interlocked.Exchange(ref _flipAheadLateNotices, 0); + var leadTicks = Interlocked.Exchange(ref _flipAheadLeadTicks, 0); + var leadCount = Interlocked.Exchange(ref _flipAheadLeadCount, 0); + if (last == 0 || atRecord + atPrevious + late == 0) + { + return; + } + + var leadMs = leadCount == 0 ? 0 : leadTicks * 1000.0 / Stopwatch.Frequency / leadCount; + Console.Error.WriteLine( + $"[VIDEOOUT][FLIP-AHEAD] ahead_at_record={atRecord} ahead_at_previous_completion={atPrevious} " + + $"late_notices={late} lead_ms_mean={leadMs.ToString("F1", System.Globalization.CultureInfo.InvariantCulture)} " + + $"lead_samples={leadCount} seconds={((now - last) / (double)Stopwatch.Frequency).ToString("F1", System.Globalization.CultureInfo.InvariantCulture)}"); + } + + internal readonly record struct FlipAheadCounters(long AtRecord, long AtPrevious, long LateNotices, long LeadSamples); + + internal static FlipAheadCounters PeekFlipAheadCountersForTests() => new( + Interlocked.Read(ref _flipAheadAtRecord), + Interlocked.Read(ref _flipAheadAtPrevious), + Interlocked.Read(ref _flipAheadLateNotices), + Interlocked.Read(ref _flipAheadLeadCount)); + + internal static void ResetFlipAheadForTests(bool enabled) + { + lock (_stateGate) + { + _lastGpuQueuedFlip.Clear(); + } + + FlipAheadEnabled = enabled; + // Keep the report from consuming the counters while a test reads them. + Interlocked.Exchange(ref _flipAheadReportedAt, Stopwatch.GetTimestamp() + 3600 * Stopwatch.Frequency); + Interlocked.Exchange(ref _flipAheadAtRecord, 0); + Interlocked.Exchange(ref _flipAheadAtPrevious, 0); + Interlocked.Exchange(ref _flipAheadLateNotices, 0); + Interlocked.Exchange(ref _flipAheadLeadTicks, 0); + Interlocked.Exchange(ref _flipAheadLeadCount, 0); + } + + internal static int GetGpuQueueCountForTests(int handle) + { + lock (_stateGate) + { + return _ports.TryGetValue(handle, out var port) ? port.GpuQueueCount : -1; + } + } +} diff --git a/src/SharpEmu.Libs/VideoOut/VideoOutExports.FlipRequests.cs b/src/SharpEmu.Libs/VideoOut/VideoOutExports.FlipRequests.cs index a2d0c0fc3..9a5484e92 100644 --- a/src/SharpEmu.Libs/VideoOut/VideoOutExports.FlipRequests.cs +++ b/src/SharpEmu.Libs/VideoOut/VideoOutExports.FlipRequests.cs @@ -47,6 +47,18 @@ private sealed class FlipRequest public int FlipEventCount; public FlipRequestState State; public FlipOutcome Outcome; + + // SHARPEMU_FLIP_AHEAD (see VideoOutExports.FlipAhead.cs). The GPU host recorded the flip, + // committed the buffer carrying it and handed the presenter a copy of its frame. + public bool AheadRecorded; + // The GPU really finished the submission carrying the flip (CompleteFlipOnGpu ran). + public bool GpuCompleted; + // The flip events of the published flip have been triggered. + public bool EventsTriggered; + // When the guest-visible completion was published ahead of the GPU; zero otherwise. + public long AheadPublishedAt; + // The GPU-queued flip reserved before this one on the same handle, until this one is published. + public FlipRequest? AheadPrevious; } private static readonly Dictionary _flipRequests = new(); @@ -146,6 +158,10 @@ internal static int TryReserveFlipRequest( } _flipRequests.Add(request.RequestId, request); + if (gpuQueued && FlipAheadEnabled) + { + NoteGpuQueuedFlipLocked(request); + } } if (bufferIndex >= 0 && TryGetDisplayBufferInfo(handle, bufferIndex, out var displayBuffer)) @@ -237,10 +253,11 @@ internal static void CompleteFlip(ulong requestId) } ReleaseGpuQueueSlotLocked(request); + request.GpuCompleted = true; PublishFlipLocked(request); } - TriggerFlipEvents(request); + TriggerPublishedFlip(request); } /// @@ -253,25 +270,49 @@ internal static void CompleteFlip(ulong requestId) internal static void CompleteFlipOnGpu(ulong requestId) { FlipRequest request; + var aheadAlready = false; lock (_stateGate) { - if (!_flipRequests.TryGetValue(requestId, out request!) || request.State != FlipRequestState.Reserved) + if (!_flipRequests.TryGetValue(requestId, out request!)) { return; } - ReleaseGpuQueueSlotLocked(request); - if (request.Outcome == FlipOutcome.Pending) + if (request.State != FlipRequestState.Reserved) { - request.State = FlipRequestState.GpuDone; - Monitor.PulseAll(_stateGate); - return; + // A flip published ahead still owes its GPU-side state; the guest was told already, + // so neither the counters nor the events are published again. + if (request.AheadPublishedAt == 0 || request.GpuCompleted) + { + return; + } + + CompleteAheadFlipOnGpuLocked(request); + aheadAlready = true; + } + else + { + ReleaseGpuQueueSlotLocked(request); + request.GpuCompleted = true; + if (request.Outcome == FlipOutcome.Pending) + { + request.State = FlipRequestState.GpuDone; + Monitor.PulseAll(_stateGate); + return; + } + + PublishFlipLocked(request); } + } - PublishFlipLocked(request); + if (aheadAlready) + { + // The flip after this one may be waiting for this real completion. + DrainFlipAhead(request.Handle, noticed: 0); + return; } - TriggerFlipEvents(request); + TriggerPublishedFlip(request); } // Caller holds the state gate. The GPU no longer holds the request. @@ -288,6 +329,7 @@ private static void ReleaseGpuQueueSlotLocked(FlipRequest request) private static void PublishFlipLocked(FlipRequest request) { request.State = FlipRequestState.Completed; + request.AheadPrevious = null; if (_ports.TryGetValue(request.Handle, out var port)) { port.FlipCount++; @@ -385,7 +427,7 @@ private static bool SetFlipOutcome(ulong requestId, FlipOutcome outcome) if (published is not null) { - TriggerFlipEvents(published); + TriggerPublishedFlip(published); } return true; @@ -394,7 +436,9 @@ private static bool SetFlipOutcome(ulong requestId, FlipOutcome outcome) // Both responsibilities are done: the retirement ran and the presenter released the frame. private static void RemoveIfFinishedLocked(FlipRequest request) { - if (request.State == FlipRequestState.Completed && request.Outcome != FlipOutcome.Pending) + // A flip published ahead of the GPU stays until its real completion has released its GPU slot. + if (request.State == FlipRequestState.Completed && request.Outcome != FlipOutcome.Pending && + (request.AheadPublishedAt == 0 || request.GpuCompleted)) { _flipRequests.Remove(request.RequestId); } @@ -461,6 +505,14 @@ private static void CancelFlipLocked(FlipRequest request) request.FlipEvents = null; } } + else if (request.AheadPublishedAt != 0 && !request.GpuCompleted && request.GpuQueued && + _ports.TryGetValue(request.Handle, out var aheadPort)) + { + // Published ahead of the GPU: the guest was told, the GPU slot was still held. + aheadPort.GpuQueueCount = Math.Max(0, aheadPort.GpuQueueCount - 1); + } + + request.AheadPrevious = null; // Completed requests leave event-array ownership with the completion caller. request.Outcome = FlipOutcome.Cancelled; _flipRequests.Remove(request.RequestId); diff --git a/tests/SharpEmu.Libs.Tests/Gpu/Split/SplitHookTests.cs b/tests/SharpEmu.Libs.Tests/Gpu/Split/SplitHookTests.cs index e1d52c3f9..d9a34ea7e 100644 --- a/tests/SharpEmu.Libs.Tests/Gpu/Split/SplitHookTests.cs +++ b/tests/SharpEmu.Libs.Tests/Gpu/Split/SplitHookTests.cs @@ -310,6 +310,8 @@ public long NextFlipPresentTimestamp(ulong requestId, long timestamp) public void CompleteFlipOnGpu(ulong requestId) => Calls.Add($"gpu {requestId}"); + public void NoteFlipRecorded(ulong requestId) => Calls.Add($"recorded {requestId}"); + public void DiscardFlip(ulong requestId) => Calls.Add($"discard {requestId}"); public string GetApplicationTitleId() diff --git a/tests/SharpEmu.Libs.Tests/VideoOut/VideoOutFlipAheadTests.cs b/tests/SharpEmu.Libs.Tests/VideoOut/VideoOutFlipAheadTests.cs new file mode 100644 index 000000000..8b806cb8f --- /dev/null +++ b/tests/SharpEmu.Libs.Tests/VideoOut/VideoOutFlipAheadTests.cs @@ -0,0 +1,292 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using System.Buffers.Binary; +using System.Diagnostics; +using SharpEmu.HLE; +using SharpEmu.Libs.Kernel; +using SharpEmu.Libs.Tests.Gpu.Scheduling; +using SharpEmu.Libs.VideoOut; +using Xunit; + +namespace SharpEmu.Libs.Tests.VideoOut; + +// SHARPEMU_FLIP_AHEAD: a flip the GPU host recorded (NoteFlipRecorded) is published to the guest +// once the flip before it really completed on the GPU; the request stays for the pacer and its +// real completion releases the GPU slot without publishing again. +[Collection(SchedulingStateCollection.Name)] +public sealed class VideoOutFlipAheadTests : IDisposable +{ + private const ulong MemoryBase = 0x1_0000_0000; + private const ulong StatusAddress = MemoryBase + 0x100; + private const ulong ScratchAddress = MemoryBase + 0x200; + private const ulong EventAddress = MemoryBase + 0x300; + private const ulong OutCountAddress = MemoryBase + 0x400; + private const ulong TimeoutAddress = MemoryBase + 0x480; + private const int TimedOut = unchecked((int)0x8002003C); + + private readonly FakeCpuMemory _memory = new(MemoryBase, 0x1000); + private readonly CpuContext _context; + private readonly int _handle; + private ulong _queue; + + public VideoOutFlipAheadTests() + { + _context = new CpuContext(_memory, Generation.Gen5); + _context[CpuRegister.Rdi] = 0; + _context[CpuRegister.Rsi] = 0; + _context[CpuRegister.Rdx] = 0; + _context[CpuRegister.Rcx] = 0; + _handle = VideoOutExports.VideoOutOpen(_context); + Assert.True(_handle > 0); + VideoOutExports.ResetFlipAheadForTests(enabled: true); + } + + public void Dispose() + { + if (_queue != 0) + { + _context[CpuRegister.Rdi] = _queue; + _ = KernelEventQueueCompatExports.KernelDeleteEqueue(_context); + } + + _context[CpuRegister.Rdi] = unchecked((ulong)_handle); + _ = VideoOutExports.VideoOutClose(_context); + VideoOutExports.ResetFlipAheadForTests(enabled: false); + } + + private ulong Reserve(long flipArg, bool gpuQueued = true) + { + Assert.Equal(0, VideoOutExports.TryReserveFlipRequest(_handle, -1, 2, flipArg, gpuQueued, out var requestId)); + return requestId; + } + + private (ulong Count, long FlipArg, int GpuQueue, int Pending) Status() + { + _context[CpuRegister.Rdi] = unchecked((ulong)_handle); + _context[CpuRegister.Rsi] = StatusAddress; + Assert.Equal(0, VideoOutExports.VideoOutGetFlipStatus(_context)); + Span status = stackalloc byte[0x40]; + Assert.True(_memory.TryRead(StatusAddress, status)); + return (BinaryPrimitives.ReadUInt64LittleEndian(status), + BinaryPrimitives.ReadInt64LittleEndian(status[0x18..]), + BinaryPrimitives.ReadInt32LittleEndian(status[0x30..]), + BinaryPrimitives.ReadInt32LittleEndian(status[0x34..])); + } + + private void AddFlipEvent() + { + _context[CpuRegister.Rdi] = ScratchAddress; + _context[CpuRegister.Rsi] = 0; + Assert.Equal(0, KernelEventQueueCompatExports.KernelCreateEqueue(_context)); + Assert.True(_context.TryReadUInt64(ScratchAddress, out _queue)); + _context[CpuRegister.Rdi] = _queue; + _context[CpuRegister.Rsi] = unchecked((ulong)_handle); + _context[CpuRegister.Rdx] = 0x55; + Assert.Equal(0, VideoOutExports.VideoOutAddFlipEvent(_context)); + } + + private int WaitOne(uint timeoutUsec) + { + Assert.True(_memory.TryWrite(TimeoutAddress, BitConverter.GetBytes(timeoutUsec))); + _context[CpuRegister.Rdi] = _queue; + _context[CpuRegister.Rsi] = EventAddress; + _context[CpuRegister.Rdx] = 1; + _context[CpuRegister.Rcx] = OutCountAddress; + _context[CpuRegister.R8] = TimeoutAddress; + return KernelEventQueueCompatExports.KernelWaitEqueue(_context); + } + + [Fact] + public void AheadPublicationPublishesOnceAndTheRealCompletionOnlyReleasesTheGpuSlot() + { + AddFlipEvent(); + var before = Status(); + var request = Reserve(101); + Assert.Equal(before.GpuQueue + 1, Status().GpuQueue); + + VideoOutExports.NoteFlipRecorded(request); + var ahead = Status(); + Assert.Equal(before.Count + 1, ahead.Count); + Assert.Equal(101, ahead.FlipArg); + Assert.Equal(before.Pending, ahead.Pending); + // The GPU still holds the flip. + Assert.Equal(before.GpuQueue + 1, ahead.GpuQueue); + Assert.Equal(0, WaitOne(100_000)); + // The pacer still has the request. + Assert.True(VideoOutExports.IsFlipPresentationPending(request)); + Assert.Equal(VideoOutExports.FlipOutcome.Pending, VideoOutExports.GetFlipOutcomeForTests(request)); + + VideoOutExports.CompleteFlipOnGpu(request); + VideoOutExports.CompleteFlipOnGpu(request); + var done = Status(); + Assert.Equal(ahead.Count, done.Count); + Assert.Equal(before.GpuQueue, done.GpuQueue); + Assert.Equal(TimedOut, WaitOne(1_000)); + Assert.True(VideoOutExports.CanPresentFlip(request, Stopwatch.GetTimestamp())); + + VideoOutExports.MarkFlipPresented(request); + Assert.Equal(ahead.Count, Status().Count); + Assert.Equal(TimedOut, WaitOne(1_000)); + Assert.Null(VideoOutExports.GetFlipOutcomeForTests(request)); + + var counters = VideoOutExports.PeekFlipAheadCountersForTests(); + Assert.Equal(1, counters.AtRecord); + Assert.Equal(0, counters.AtPrevious); + Assert.Equal(1, counters.LeadSamples); + } + + [Fact] + public void TheNextFlipWaitsForThePreviousRealCompletion() + { + var before = Status(); + var first = Reserve(111); + var second = Reserve(112); + + VideoOutExports.NoteFlipRecorded(first); + VideoOutExports.NoteFlipRecorded(second); + Assert.Equal(before.Count + 1, Status().Count); + Assert.Equal(111, Status().FlipArg); + + VideoOutExports.CompleteFlipOnGpu(first); + Assert.Equal(before.Count + 2, Status().Count); + Assert.Equal(112, Status().FlipArg); + + var counters = VideoOutExports.PeekFlipAheadCountersForTests(); + Assert.Equal(1, counters.AtRecord); + Assert.Equal(1, counters.AtPrevious); + + VideoOutExports.CompleteFlipOnGpu(second); + VideoOutExports.MarkFlipPresented(first); + VideoOutExports.MarkFlipPresented(second); + Assert.Equal(before.Count + 2, Status().Count); + Assert.Equal(before.GpuQueue, Status().GpuQueue); + Assert.Equal(before.Pending, Status().Pending); + Assert.Null(VideoOutExports.GetFlipOutcomeForTests(first)); + Assert.Null(VideoOutExports.GetFlipOutcomeForTests(second)); + } + + // A flip whose predecessor was not published ahead goes no later than today: when the + // predecessor is shown, never before it. + [Fact] + public void AFlipIsNeverPublishedBeforeTheOneBeforeIt() + { + var before = Status(); + var first = Reserve(121); + var second = Reserve(122); + + VideoOutExports.NoteFlipRecorded(second); + Assert.Equal(before.Count, Status().Count); + + VideoOutExports.CompleteFlipOnGpu(first); + Assert.Equal(before.Count, Status().Count); + + VideoOutExports.MarkFlipPresented(first); + Assert.Equal(before.Count + 2, Status().Count); + Assert.Equal(122, Status().FlipArg); + + VideoOutExports.CompleteFlipOnGpu(second); + VideoOutExports.MarkFlipPresented(second); + Assert.Equal(before.Count + 2, Status().Count); + Assert.Equal(before.GpuQueue, Status().GpuQueue); + } + + [Fact] + public void ThePacerStillPresentsAFlipPublishedAheadInOrder() + { + var before = Status(); + var first = Reserve(131); + VideoOutExports.NoteFlipRecorded(first); + var second = Reserve(132); + // The guest's next flip arrives before the first was shown; both stay with the pacer. + Assert.False(VideoOutExports.IsFlipDone(_handle, -1)); + Assert.True(VideoOutExports.IsFlipPresentationPending(first)); + Assert.True(VideoOutExports.IsFlipPresentationPending(second)); + + // Shown before its real completion: the request outlives the presentation until then. + VideoOutExports.MarkFlipPresented(first); + Assert.Equal(VideoOutExports.FlipOutcome.Presented, VideoOutExports.GetFlipOutcomeForTests(first)); + Assert.Equal(before.GpuQueue + 2, Status().GpuQueue); + VideoOutExports.CompleteFlipOnGpu(first); + Assert.Null(VideoOutExports.GetFlipOutcomeForTests(first)); + Assert.Equal(before.GpuQueue + 1, Status().GpuQueue); + + VideoOutExports.NoteFlipRecorded(second); + Assert.Equal(before.Count + 2, Status().Count); + VideoOutExports.CompleteFlipOnGpu(second); + VideoOutExports.DiscardFlip(second); + Assert.Equal(before.Count + 2, Status().Count); + Assert.True(VideoOutExports.IsFlipDone(_handle, -1)); + Assert.Null(VideoOutExports.GetFlipOutcomeForTests(second)); + Assert.Equal(before.GpuQueue, Status().GpuQueue); + Assert.Equal(before.Pending, Status().Pending); + } + + [Fact] + public void ALateNoticeAndCancelledOrCpuFlipsKeepTodaysTiming() + { + var before = Status(); + + // Real completion first: the notice is ignored and presentation publishes. + var late = Reserve(141); + VideoOutExports.CompleteFlipOnGpu(late); + VideoOutExports.NoteFlipRecorded(late); + Assert.Equal(before.Count, Status().Count); + VideoOutExports.MarkFlipPresented(late); + Assert.Equal(before.Count + 1, Status().Count); + + // Cancelled: nothing is published. + var cancelled = Reserve(142); + VideoOutExports.CancelFlip(cancelled); + VideoOutExports.NoteFlipRecorded(cancelled); + Assert.Equal(before.Count + 1, Status().Count); + + // A CPU flip is not GPU-queued: a notice for it is ignored. + var cpu = Reserve(143, gpuQueued: false); + VideoOutExports.NoteFlipRecorded(cpu); + Assert.Equal(before.Count + 1, Status().Count); + + // An unpublished CPU flip before a GPU flip holds the GPU flip back. + var gpu = Reserve(144); + VideoOutExports.NoteFlipRecorded(gpu); + Assert.Equal(before.Count + 1, Status().Count); + VideoOutExports.CompleteFlip(cpu); + Assert.Equal(before.Count + 3, Status().Count); + Assert.Equal(144, Status().FlipArg); + VideoOutExports.MarkFlipPresented(cpu); + + // Cancelling a flip published ahead gives its GPU slot back. + Assert.Equal(before.GpuQueue + 1, Status().GpuQueue); + VideoOutExports.CancelFlip(gpu); + Assert.Equal(before.GpuQueue, Status().GpuQueue); + Assert.Equal(before.Pending, Status().Pending); + Assert.Equal(before.Count + 3, Status().Count); + + Assert.Equal(3, VideoOutExports.PeekFlipAheadCountersForTests().LateNotices); + } + + [Fact] + public void WithTheSwitchOffTheNoticeChangesNothing() + { + VideoOutExports.ResetFlipAheadForTests(enabled: false); + AddFlipEvent(); + var before = Status(); + var request = Reserve(151); + + VideoOutExports.NoteFlipRecorded(request); + Assert.Equal(before.Count, Status().Count); + Assert.Equal(TimedOut, WaitOne(1_000)); + + VideoOutExports.CompleteFlipOnGpu(request); + Assert.Equal(before.Count, Status().Count); + Assert.Equal(before.GpuQueue, Status().GpuQueue); + Assert.Equal(before.Pending + 1, Status().Pending); + + VideoOutExports.MarkFlipPresented(request); + Assert.Equal(before.Count + 1, Status().Count); + Assert.Equal(before.Pending, Status().Pending); + Assert.Equal(0, WaitOne(100_000)); + Assert.Null(VideoOutExports.GetFlipOutcomeForTests(request)); + Assert.Equal(default, VideoOutExports.PeekFlipAheadCountersForTests()); + } +} From 5bbbb7d81881a8903fec685fbed59bc4ea9dca4b Mon Sep 17 00:00:00 2001 From: kuba Date: Mon, 16 Nov 2026 01:24:31 +0000 Subject: [PATCH 125/178] [Metal] Flip ahead: hand the presenter a stream-ordered copy of the flip's frame With SHARPEMU_FLIP_AHEAD=1 a GPU flip's presented view is blitted, in the stream's open command buffer at the flip and fenced like every encoder, into a presenter-owned texture of the same format, size and swizzle (MetalFlipCopyPool, up to 7). Without it the presenter samples the display image itself until the next promotion, so a guest told of a flip early could draw its next frame into the frame on screen. A pool texture is reused only when it is not presented, queued or being encoded and the last presentation that sampled it has completed. A refused copy (pool exhausted, not a single-level 2D texture, multisampled, creation or encoder failure) is logged once, counted, and the frame goes live as today. The recorded notice is sent after the flip's completion is queued, only for a copied frame whose previous frame was a copy too. Interrupts and labels stay at the real completion. [METAL-PRESENT] gains flip_copies, flip_copy_refused, flip_copy_pool, flip_copy_pool_high and flip_copy_mb while the switch is on. --- docs/macos/configuration.md | 1 + .../V2/MetalCommandStream.cs | 20 +- .../V2/MetalFlipCopyPool.cs | 298 ++++++++++++++++++ .../V2/MetalRenderHost.FlipCopy.cs | 153 +++++++++ .../V2/MetalV2Diagnostics.cs | 5 + .../SharpEmu.Gpu.Metal/V2/MetalV2Presenter.cs | 50 ++- .../MetalFlipCopyTests.cs | 104 ++++++ 7 files changed, 626 insertions(+), 5 deletions(-) create mode 100644 src/graphics/SharpEmu.Gpu.Metal/V2/MetalFlipCopyPool.cs create mode 100644 src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.FlipCopy.cs create mode 100644 tests/SharpEmu.Gpu.Metal.Tests/MetalFlipCopyTests.cs diff --git a/docs/macos/configuration.md b/docs/macos/configuration.md index d09a4ea15..c52a8bb9c 100644 --- a/docs/macos/configuration.md +++ b/docs/macos/configuration.md @@ -41,6 +41,7 @@ them for measurements or to isolate a problem. | `SHARPEMU_GUEST_BACKING_SHAREABLE` | unset | `1` makes the guest backing shareable with another process, and keeps a shared table and log of guest views. This is groundwork for the two-process split (`SHARPEMU_GPU_PROCESS=1` sets it too). See [Guest memory for the two-process split](split-shared-memory.md). | | `SHARPEMU_HLE_FAST_PATH` | on | `0` disables the native stubs for `pthread_self` and `pthread_getspecific`. They are also off while import or pthread tracing is active. | | `SHARPEMU_STALL_WATCHDOG_SECONDS` | `20` | Seconds without import progress before the stall watchdog acts. `0` disables it. | +| `SHARPEMU_FLIP_AHEAD` | off | Experimental. `1` tells the game a GPU flip is done once the flip is recorded and the flip before it has really finished on the GPU, instead of when the frame is shown, so the game can build its next frame while the GPU draws this one (at most one flip ahead). Each such frame is copied in the GPU stream into a presenter-owned texture (up to 7 textures the size of the display buffer), so what is shown is unchanged; a flip whose frame cannot be copied keeps the usual timing, and the refusal is logged once. Pacing, interrupts and labels are unchanged. Counters: `[VIDEOOUT][FLIP-AHEAD]` and the `flip_copy*` fields of `[METAL-PRESENT]`. | ## Metal memory diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalCommandStream.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalCommandStream.cs index 2353964ff..77370f60b 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalCommandStream.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalCommandStream.cs @@ -910,6 +910,7 @@ public void RecordEndOfPipe(in EndOfPipeWrite write) VideoOutBackendServices.CompleteFlipOnGpu(requestId); MetalV2Presenter.SignalFlipPacer(); }); + NoteFlipRecordedIfEligible(requestId); break; case EndOfPipeWriteKind.FlipWithInterruptWriteBack32: NoteFlipSerialForEarlyLabels(); @@ -920,6 +921,7 @@ public void RecordEndOfPipe(in EndOfPipeWrite write) MetalV2Presenter.SignalFlipPacer(); TriggerInterrupt(eventId, 0); }); + NoteFlipRecordedIfEligible(requestId); break; case EndOfPipeWriteKind.GdsWrite32: RecordEndOfPipeGdsWrite(in write); @@ -2965,7 +2967,7 @@ public ulong PrepareFlip(int handle, int index, int flipMode, long flipArgument) try { - CaptureFlip(handle, index, requestId, flipMode, flipArgument); + CaptureFlip(handle, index, requestId, flipMode, flipArgument, gpuQueued: true); } catch { @@ -2986,7 +2988,7 @@ public void PrepareCpuFlip(int handle, int index, ulong requestId) } DrainDraws(); - CaptureFlip(handle, index, requestId, flipMode: 0, flipArg: 0); + CaptureFlip(handle, index, requestId, flipMode: 0, flipArg: 0, gpuQueued: false); } // The display surface is a cached image like any other; the flip hands its @@ -2999,7 +3001,7 @@ public void PrepareCpuFlip(int handle, int index, ulong requestId) internal static long FlipsDiscarded; internal static long FlipsPublished; - private void CaptureFlip(int handle, int index, ulong requestId, int flipMode, long flipArg) + private void CaptureFlip(int handle, int index, ulong requestId, int flipMode, long flipArg, bool gpuQueued) { Interlocked.Increment(ref _flipAttempts); Interlocked.Increment(ref FlipsCaptured); @@ -3063,6 +3065,11 @@ private void CaptureFlip(int handle, int index, ulong requestId, int flipMode, l if (_dumpThisFlip) { DumpTexture(image.Texture, "flip-after-refresh"); } SampleFlipLuma(image.Texture); var texture = PresentationViewOf(imageIdentifier, image, in request); + // SHARPEMU_FLIP_AHEAD: the presenter gets a copy taken here, in the stream, instead of + // the display image the guest may render into once it hears of the flip. + var presented = texture; + var copied = MetalV2Diagnostics.FlipAhead && gpuQueued && _flipTarget is not null && texture != 0 && + TryCopyFlipFrame(texture, out presented); var serial = SubmissionSerial; FlushCommandBuffer(PassEndCause.Present); if (_flipTarget is null || texture == 0) @@ -3087,12 +3094,17 @@ private void CaptureFlip(int handle, int index, ulong requestId, int flipMode, l Interlocked.Increment(ref FlipsPublished); ReportFlipSurface(in displayBuffer, in request, imageIdentifier, image, texture); _flipTarget.PublishGuestFrame( - texture, + presented, Math.Max(displayBuffer.Width, 1), Math.Max(displayBuffer.Height, 1), requestId, serial, VideoOutBackendServices.IsHdrPixelFormat(displayBuffer.PixelFormat)); + if (MetalV2Diagnostics.FlipAhead) + { + NoteFlipFrameCaptured(requestId, copied); + } + VideoOutBackendServices.TraceGpuFlip( _memory, handle, index, flipMode, flipArg, displayBuffer.Address, requestId); // The shared phase profile measures the whole draw translation path, which v2 diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalFlipCopyPool.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalFlipCopyPool.cs new file mode 100644 index 000000000..29123fd17 --- /dev/null +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalFlipCopyPool.cs @@ -0,0 +1,298 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using System.Runtime.InteropServices; + +namespace SharpEmu.Gpu.Metal.V2; + +/// +/// SHARPEMU_FLIP_AHEAD: the presenter-owned textures a GPU flip's frame is copied into, in the +/// stream at the flip (MetalRenderHost.FlipCopy.cs). Without the copy the presenter samples the +/// display image's own texture until the next frame replaces it, so a guest told of flip N before +/// N is shown could render the next frame into the buffer still on screen. +/// A texture goes back to the pool only once the presenter can no longer read it: it is not +/// the presented frame, not queued, not being encoded by a presentation, and the last +/// presentation command buffer that sampled it has completed. +/// +internal static partial class MetalFlipCopyPool +{ + // The frame on screen, the frames the presenter queues (MaxPendingFrames = 4), the one the + // stream is writing, and one whose last presentation may still be on the GPU. + internal const int Capacity = 7; + + internal enum Refusal + { + PoolExhausted, + TextureType, + Multisampled, + Layout, + TextureCreate, + Encoder, + Count, + } + + private static readonly string[] RefusalNames = + ["pool_exhausted", "texture_type", "multisampled", "layout", "texture_create", "encoder"]; + + private sealed class Entry + { + public nint Texture; + public nint Presented; + public ulong PixelFormat; + public uint Width; + public uint Height; + public MtlTextureSwizzleChannels Swizzle; + public nint LastSampledBy; + } + + private static readonly object _gate = new(); + private static readonly List _entries = new(); + private static readonly long[] _refusals = new long[(int)Refusal.Count]; + private static long _copies; + private static int _highWater; + private static ulong _copyBytes; + + private static readonly nint SelSwizzle = MetalNative.Selector("swizzle"); + private static readonly nint SelStatus = MetalNative.Selector("status"); + private static readonly nint SelRetain = MetalNative.Selector("retain"); + private static readonly nint SelRelease = MetalNative.Selector("release"); + private static readonly nint SelSetUsage = MetalNative.Selector("setUsage:"); + private static readonly nint SelSetStorageMode = MetalNative.Selector("setStorageMode:"); + private static readonly nint SelNewTexture = MetalNative.Selector("newTextureWithDescriptor:"); + private static readonly nint SelNewSwizzledView = + MetalNative.Selector("newTextureViewWithPixelFormat:textureType:levels:slices:swizzle:"); + + // MTLCommandBufferStatusCompleted; Error (5) is past it too. + private const nuint CommandBufferCompleted = 4; + + [LibraryImport("/usr/lib/libobjc.A.dylib", EntryPoint = "objc_msgSend")] + private static partial MtlTextureSwizzleChannels SendSwizzle(nint receiver, nint selector); + + /// The swizzle the presenter samples a texture through. + internal static MtlTextureSwizzleChannels SwizzleOf(nint texture) => SendSwizzle(texture, SelSwizzle); + + /// + /// A texture of this shape the presenter cannot read any more, or a new one. destination is + /// what the copy writes, presented what the presenter is handed (the same texture, or a view + /// of it with the source's swizzle). + /// + internal static bool TryAcquire(nint device, ulong pixelFormat, uint width, uint height, + MtlTextureSwizzleChannels swizzle, out nint destination, out nint presented, out Refusal refusal) + { + destination = 0; + presented = 0; + refusal = Refusal.Count; + lock (_gate) + { + Entry? free = null; + Entry? reclaim = null; + var held = 0; + foreach (var entry in _entries) + { + if (IsReadableLocked(entry)) + { + held++; + continue; + } + + var matches = entry.PixelFormat == pixelFormat && entry.Width == width && entry.Height == height && + SameSwizzle(entry.Swizzle, swizzle); + if (matches) + { + free ??= entry; + } + else + { + reclaim ??= entry; + } + } + + if (free is null) + { + if (_entries.Count >= Capacity) + { + if (reclaim is null) + { + refusal = Refusal.PoolExhausted; + return false; + } + + ReleaseLocked(reclaim); + _entries.Remove(reclaim); + } + + free = Create(device, pixelFormat, width, height, swizzle); + if (free is null) + { + refusal = Refusal.TextureCreate; + return false; + } + + _entries.Add(free); + } + + _highWater = Math.Max(_highWater, held + 1); + destination = free.Texture; + presented = free.Presented; + return true; + } + } + + internal static void NoteCopy(ulong bytes) + { + Interlocked.Increment(ref _copies); + Interlocked.Exchange(ref _copyBytes, bytes); + } + + internal static void NoteRefusal(Refusal refusal) => Interlocked.Increment(ref _refusals[(int)refusal]); + + internal static string RefusalName(Refusal refusal) => RefusalNames[(int)refusal]; + + /// A presentation command buffer, now committed, sampled this texture. + internal static void NoteSampled(nint texture, nint commandBuffer) + { + if (texture == 0 || commandBuffer == 0) + { + return; + } + + lock (_gate) + { + foreach (var entry in _entries) + { + if (entry.Presented != texture) + { + continue; + } + + MetalNative.SendVoid(commandBuffer, SelRetain); + if (entry.LastSampledBy != 0) + { + MetalNative.SendVoid(entry.LastSampledBy, SelRelease); + } + + entry.LastSampledBy = commandBuffer; + return; + } + } + } + + /// Copies, refusals by reason, the most textures the presenter could read at once plus the one written. + internal static string TakeReport() + { + var copies = Interlocked.Exchange(ref _copies, 0); + var refusals = new System.Text.StringBuilder(); + for (var index = 0; index < (int)Refusal.Count; index++) + { + var count = Interlocked.Exchange(ref _refusals[index], 0); + if (count != 0) + { + refusals.Append(refusals.Length == 0 ? "" : ",").Append(RefusalNames[index]).Append(':').Append(count); + } + } + + int pool; + int high; + lock (_gate) + { + pool = _entries.Count; + high = _highWater; + } + + return $"flip_copies={copies} flip_copy_refused={(refusals.Length == 0 ? "0" : refusals.ToString())} " + + $"flip_copy_pool={pool} flip_copy_pool_high={high} flip_copy_mb={Interlocked.Read(ref _copyBytes) / (1024.0 * 1024.0):F1}"; + } + + // Caller holds the gate. + private static bool IsReadableLocked(Entry entry) + { + if (MetalV2Presenter.IsFlipCopyHeld(entry.Presented)) + { + return true; + } + + if (entry.LastSampledBy == 0) + { + return false; + } + + if (MetalV2Native.SendValue(entry.LastSampledBy, SelStatus) < CommandBufferCompleted) + { + return true; + } + + MetalNative.SendVoid(entry.LastSampledBy, SelRelease); + entry.LastSampledBy = 0; + return false; + } + + private static bool SameSwizzle(MtlTextureSwizzleChannels left, MtlTextureSwizzleChannels right) => + left.Red == right.Red && left.Green == right.Green && left.Blue == right.Blue && left.Alpha == right.Alpha; + + // MTLTextureSwizzleRed..Alpha are 2..5. + private static bool IsIdentity(MtlTextureSwizzleChannels swizzle) => + swizzle.Red == 2 && swizzle.Green == 3 && swizzle.Blue == 4 && swizzle.Alpha == 5; + + private static Entry? Create(nint device, ulong pixelFormat, uint width, uint height, MtlTextureSwizzleChannels swizzle) + { + var descriptor = MetalNative.SendTextureDescriptor( + MetalNative.Class("MTLTextureDescriptor"), + MetalNative.Selector("texture2DDescriptorWithPixelFormat:width:height:mipmapped:"), + (nuint)pixelFormat, + width, + height, + mipmapped: false); + if (descriptor == 0) + { + return null; + } + + var identity = IsIdentity(swizzle); + MetalV2Native.SendVoidValue(descriptor, SelSetUsage, + (nuint)(Mtl.TextureUsageShaderRead | (identity ? 0 : Mtl.TextureUsagePixelFormatView))); + MetalV2Native.SendVoidValue(descriptor, SelSetStorageMode, Mtl.StorageModePrivate); + var texture = MetalNative.Send(device, SelNewTexture, descriptor); + if (texture == 0) + { + return null; + } + + var presented = texture; + if (!identity) + { + presented = MetalV2Native.SendNewSwizzledTextureView( + texture, SelNewSwizzledView, (nuint)pixelFormat, (nuint)Mtl.TextureType2D, + new NsRange { Location = 0, Length = 1 }, new NsRange { Location = 0, Length = 1 }, swizzle); + if (presented == 0) + { + MetalNative.SendVoid(texture, SelRelease); + return null; + } + } + + return new Entry + { + Texture = texture, + Presented = presented, + PixelFormat = pixelFormat, + Width = width, + Height = height, + Swizzle = swizzle, + }; + } + + // Caller holds the gate; the entry is not readable. + private static void ReleaseLocked(Entry entry) + { + if (entry.Presented != entry.Texture) + { + MetalNative.SendVoid(entry.Presented, SelRelease); + } + + MetalNative.SendVoid(entry.Texture, SelRelease); + if (entry.LastSampledBy != 0) + { + MetalNative.SendVoid(entry.LastSampledBy, SelRelease); + } + } +} diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.FlipCopy.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.FlipCopy.cs new file mode 100644 index 000000000..db9f1ae83 --- /dev/null +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.FlipCopy.cs @@ -0,0 +1,153 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using SharpEmu.Libs.VideoOut; + +namespace SharpEmu.Gpu.Metal.V2; + +// SHARPEMU_FLIP_AHEAD: a GPU flip's frame is copied, in the stream at the flip, into a texture +// only the presenter reads (MetalFlipCopyPool), and video-out is told once the flip is recorded +// and the buffer carrying it committed, so it may publish the flip to the guest before the GPU +// finishes it (VideoOutExports.FlipAhead.cs). +internal sealed partial class MetalRenderHost +{ + private static readonly nint SelMipmapLevelCount = MetalNative.Selector("mipmapLevelCount"); + private static readonly nint SelArrayLength = MetalNative.Selector("arrayLength"); + private static readonly nint SelAllocatedSize = MetalNative.Selector("allocatedSize"); + + // The flips whose frame was copied while the frame before them was a copy too: the only + // ones whose recorded notice is sent. Worker thread; locked for the command thread's sake. + private readonly List _flipAheadEligible = new(); + + // Whether the last frame handed to the presenter was a copy. A frame handed over live (a CPU + // flip, a refused copy) is the display image itself, which stays on screen until the next + // frame is promoted: the guest must not hear of that next flip before it is shown. + private bool _previousFlipFrameCopied = true; + + // Copies the flip's presented view into a pool texture at this point of the stream. False + // (refused, logged once and counted) leaves the frame to be presented live, as today. + internal bool TryCopyFlipFrame(nint source, out nint presented) + { + presented = source; + var type = (ulong)MetalV2Native.SendValue(source, SelTextureType); + if (type != Mtl.TextureType2D) + { + return RefuseFlipCopy(MetalFlipCopyPool.Refusal.TextureType, $"type={type}"); + } + + var samples = (ulong)MetalV2Native.SendValue(source, SelSampleCount); + if (samples > 1) + { + return RefuseFlipCopy(MetalFlipCopyPool.Refusal.Multisampled, $"samples={samples}"); + } + + var levels = (ulong)MetalV2Native.SendValue(source, SelMipmapLevelCount); + var layers = (ulong)MetalV2Native.SendValue(source, SelArrayLength); + if (levels != 1 || layers != 1) + { + return RefuseFlipCopy(MetalFlipCopyPool.Refusal.Layout, $"levels={levels} layers={layers}"); + } + + var pixelFormat = (ulong)MetalV2Native.SendValue(source, SelPixelFormat); + var width = (uint)MetalV2Native.SendValue(source, SelWidth); + var height = (uint)MetalV2Native.SendValue(source, SelHeight); + var swizzle = MetalFlipCopyPool.SwizzleOf(source); + if (!MetalFlipCopyPool.TryAcquire(_device, pixelFormat, width, height, swizzle, + out var destination, out var copy, out var refusal)) + { + return RefuseFlipCopy(refusal, $"format={pixelFormat} {width}x{height} capacity={MetalFlipCopyPool.Capacity}"); + } + + EndEncoders(PassEndCause.Present); + var encoder = MetalNative.Send(EnsureCommandBuffer(), SelBlitEncoder); + MetalMemoryTelemetry.BlitEncoders.Add(); + if (encoder == 0) + { + return RefuseFlipCopy(MetalFlipCopyPool.Refusal.Encoder, $"format={pixelFormat} {width}x{height}"); + } + + // Fenced like every other encoder of the stream: after the passes that drew the frame, + // before anything recorded after the flip. + WaitForPreviousEncoder(encoder, render: false); + try + { + MetalNative.SendCopyTextureSlice( + encoder, + SelCopyTextureSlice, + source, + 0, + 0, + default, + new MtlSize { Width = width, Height = height, Depth = 1 }, + destination, + 0, + 0, + default); + } + finally + { + UpdateEncoderFence(encoder, render: false); + MetalNative.SendVoid(encoder, SelEndEncoding); + } + + NoteRecordedWork(); + MetalFlipCopyPool.NoteCopy((ulong)MetalV2Native.SendValue(destination, SelAllocatedSize)); + presented = copy; + return true; + } + + private static bool RefuseFlipCopy(MetalFlipCopyPool.Refusal refusal, string detail) + { + MetalFlipCopyPool.NoteRefusal(refusal); + MetalV2Diagnostics.WarnOnce( + $"flip-copy-{MetalFlipCopyPool.RefusalName(refusal)}", + $"Flip ahead: a flip's frame could not be copied for the presenter ({MetalFlipCopyPool.RefusalName(refusal)}: " + + $"{detail}); it is presented live and published to the guest at presentation, as without the switch."); + return false; + } + + // After the frame went to the presenter: copied flips whose previous frame was a copy too + // may be published ahead once their end-of-pipe completion is queued. + private void NoteFlipFrameCaptured(ulong requestId, bool copied) + { + var eligible = copied && _previousFlipFrameCopied; + _previousFlipFrameCopied = copied; + if (!eligible) + { + return; + } + + lock (_flipAheadEligible) + { + // A flip whose end-of-pipe write never reaches RecordEndOfPipe (a label published by + // the interpreter) keeps today's timing; its entry is dropped here. + if (_flipAheadEligible.Count >= 8) + { + _flipAheadEligible.RemoveAt(0); + } + + _flipAheadEligible.Add(requestId); + } + } + + // RecordEndOfPipe queued the flip's completion: the buffer carrying it is committed (or the + // completion already ran inline, in which case video-out ignores the late notice). + private void NoteFlipRecordedIfEligible(ulong requestId) + { + if (!MetalV2Diagnostics.FlipAhead || requestId == 0) + { + return; + } + + bool eligible; + lock (_flipAheadEligible) + { + eligible = _flipAheadEligible.Remove(requestId); + } + + if (eligible) + { + VideoOutBackendServices.NoteFlipRecorded(requestId); + } + } +} diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalV2Diagnostics.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalV2Diagnostics.cs index 4bd321076..d07215d3c 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalV2Diagnostics.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalV2Diagnostics.cs @@ -153,6 +153,11 @@ private static HashSet ParseHashes(string? text) public static readonly ulong[] EarlyLabelProbeAddresses = ParseEarlyLabelAddresses( Environment.GetEnvironmentVariable("SHARPEMU_METAL_V2_EARLY_LABEL_PROBE")); + // SHARPEMU_FLIP_AHEAD=1 (experimental, default off): a GPU flip hands the presenter a copy of its + // frame, blitted in the stream at the flip, and tells video-out the flip is recorded, so the guest + // may learn of it before the GPU finishes it (VideoOutExports.FlipAhead.cs, MetalFlipCopyPool). + public static readonly bool FlipAhead = Environment.GetEnvironmentVariable("SHARPEMU_FLIP_AHEAD") == "1"; + public static readonly int EarlyLabelProbe = Environment.GetEnvironmentVariable("SHARPEMU_METAL_V2_EARLY_LABEL_PROBE") switch { diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalV2Presenter.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalV2Presenter.cs index eab98df3e..6121dcb1a 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalV2Presenter.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalV2Presenter.cs @@ -711,6 +711,11 @@ private static void PresentFrame() if (presented != 0) { MetalNative.Send(presented, MetalNative.Selector("retain")); + if (MetalV2Diagnostics.FlipAhead) + { + // A flip copy being encoded is not handed back to the pool (IsFlipCopyHeld). + _encodingTexture = presented; + } } } @@ -782,6 +787,11 @@ private static void PresentFrame() MetalNative.SendVoid(commandBuffer, MetalNative.Selector("presentDrawable:"), drawable); MetalMemoryTelemetry.Commits.Add(); MetalNative.SendVoid(commandBuffer, MetalNative.Selector("commit")); + if (MetalV2Diagnostics.FlipAhead && presented != 0 && texture == presented) + { + MetalFlipCopyPool.NoteSampled(presented, commandBuffer); + } + PresentationCache.RecordPresented(in stamp); PerfOverlay.RecordPresent(); ReportPresentationStatistics(); @@ -790,6 +800,14 @@ private static void PresentFrame() { if (presented != 0) { + if (MetalV2Diagnostics.FlipAhead) + { + lock (_frameGate) + { + _encodingTexture = 0; + } + } + MetalNative.SendVoid(presented, MetalNative.Selector("release")); } } @@ -818,6 +836,35 @@ private static void AdoptPendingFrame() private static readonly AutoResetEvent _flipPacerSignal = new(false); + // SHARPEMU_FLIP_AHEAD: the presented frame PresentFrame is encoding outside the frame gate. + private static nint _encodingTexture; + + /// + /// SHARPEMU_FLIP_AHEAD: whether the presenter may still read this flip copy from the CPU + /// side: it is the presented frame, a queued one, or the one a presentation is encoding. + /// The pool checks the presentation command buffers that sampled it itself. + /// + internal static bool IsFlipCopyHeld(nint texture) + { + lock (_frameGate) + { + if (texture == _presentTexture || texture == _encodingTexture) + { + return true; + } + + foreach (var frame in _pendingFrames) + { + if (frame.Texture == texture) + { + return true; + } + } + + return false; + } + } + // Wakes the pacer: a frame was published or a flip submission completed. internal static void SignalFlipPacer() => _flipPacerSignal.Set(); @@ -1291,7 +1338,8 @@ private static void ReportPresentationStatistics(bool presented = true) $"host_hz={hostHz} seconds={window} published={published} adopt_blocked={blocked} " + $"flip_attempts={flips.Attempts} flip_no_buffer={flips.WithoutBuffer} " + $"flip_discarded={flips.Discarded} flip_published={flips.Published} " + - $"flip_refreshed={flips.Refreshed} {DescribeGpuMemory()}"); + $"flip_refreshed={flips.Refreshed} {DescribeGpuMemory()}" + + (MetalV2Diagnostics.FlipAhead ? " " + MetalFlipCopyPool.TakeReport() : "")); } private static readonly nint SelCurrentAllocatedSize = MetalNative.Selector("currentAllocatedSize"); diff --git a/tests/SharpEmu.Gpu.Metal.Tests/MetalFlipCopyTests.cs b/tests/SharpEmu.Gpu.Metal.Tests/MetalFlipCopyTests.cs new file mode 100644 index 000000000..a5173cc22 --- /dev/null +++ b/tests/SharpEmu.Gpu.Metal.Tests/MetalFlipCopyTests.cs @@ -0,0 +1,104 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using System.Runtime.InteropServices; +using SharpEmu.Gpu.Metal.V2; +using SharpEmu.Libs.Gpu.Abstractions; +using Xunit; +using Xunit.Abstractions; + +namespace SharpEmu.Gpu.Metal.Tests; + +/// +/// SHARPEMU_FLIP_AHEAD: the frame a flip hands the presenter is a copy taken in the stream at the +/// flip, so a draw into the display image recorded after the flip does not reach it. +/// +public sealed class MetalFlipCopyTests(ITestOutputHelper output) +{ + private const uint Side = 64; + private const ulong Address = MetalPassRig.GuestBase + 0x10000; + + [Fact] + public void ADrawIntoTheDisplayImageRecordedAfterTheFlipDoesNotChangeTheCapturedFrame() + { + if (!RequireDevice()) return; + using var rig = new MetalPassRig(Device.Value, 1024 * 1024); + var host = rig.Host; + var formats = new[] { GpuFormat.R8G8B8A8Unorm }; + var red = rig.Pipeline(formats, ["1.0f, 0.0f, 0.0f, 1.0f"]); + var green = rig.Pipeline(formats, ["0.0f, 1.0f, 0.0f, 1.0f"]); + var target = rig.MakeTarget(Address, GpuFormat.R8G8B8A8Unorm, Side, Side); + + using (host.BeginPreparation()) + { + rig.Draw(red, [target]); + host.EndRendering(); + } + + var display = host.ImageCache.GetImage(target.State.Image).Texture; + Assert.True(host.TryCopyFlipFrame(display, out var captured)); + Assert.NotEqual(display, captured); + + // The next frame, recorded after the flip, renders into the same display image. + using (host.BeginPreparation()) + { + rig.Draw(green, [target]); + host.EndRendering(); + } + + host.FlushAndWaitForGpu(MetalWaitReason.Synchronize); + var frame = ReadTexture(Device.Value, captured); + var next = ReadTexture(Device.Value, host.ImageCache.GetImage(target.State.Image).Texture); + output.WriteLine($"captured=0x{BitConverter.ToUInt32(frame, 0):X8} display=0x{BitConverter.ToUInt32(next, 0):X8}"); + for (var texel = 0; texel < frame.Length; texel += 4) + { + Assert.Equal([0xFF, 0x00, 0x00, 0xFF], frame.AsSpan(texel, 4).ToArray()); + Assert.Equal([0x00, 0xFF, 0x00, 0xFF], next.AsSpan(texel, 4).ToArray()); + } + } + + private static byte[] ReadTexture(nint device, nint texture) + { + const nuint bytes = Side * Side * 4; + var queue = MetalNative.Send(device, MetalNative.Selector("newCommandQueue")); + var buffer = MetalNative.SendNewBuffer(device, MetalNative.Selector("newBufferWithLength:options:"), bytes, 0); + try + { + var commandBuffer = MetalNative.Send(queue, MetalNative.Selector("commandBuffer")); + var blit = MetalNative.Send(commandBuffer, MetalNative.Selector("blitCommandEncoder")); + MetalNative.SendCopyTextureToBufferOptions( + blit, + MetalNative.Selector( + "copyFromTexture:sourceSlice:sourceLevel:sourceOrigin:sourceSize:" + + "toBuffer:destinationOffset:destinationBytesPerRow:destinationBytesPerImage:options:"), + texture, 0, 0, default, new MtlSize { Width = Side, Height = Side, Depth = 1 }, + buffer, 0, Side * 4, bytes, 0); + MetalNative.SendVoid(blit, MetalNative.Selector("endEncoding")); + MetalNative.SendVoid(commandBuffer, MetalNative.Selector("commit")); + MetalNative.SendVoid(commandBuffer, MetalNative.Selector("waitUntilCompleted")); + var result = new byte[bytes]; + Marshal.Copy(MetalNative.Send(buffer, MetalNative.Selector("contents")), result, 0, result.Length); + return result; + } + finally + { + MetalNative.SendVoid(buffer, MetalNative.Selector("release")); + MetalNative.SendVoid(queue, MetalNative.Selector("release")); + } + } + + private bool RequireDevice() + { + if (Environment.GetEnvironmentVariable("SHARPEMU_TEST_REQUIRE_DEVICE") != "1") + { + output.WriteLine("The flip copy is encoded on the device only behind the exclusive device gate."); + return false; + } + + Assert.True(OperatingSystem.IsMacOS()); + Assert.NotEqual(0, Device.Value); + return true; + } + + private static readonly Lazy Device = new(MetalNative.MTLCreateSystemDefaultDevice); +} From 7969522f9d26bd637b5164db0e5888336b17a8b3 Mon Sep 17 00:00:00 2001 From: kuba Date: Mon, 16 Nov 2026 07:53:58 +0000 Subject: [PATCH 126/178] [Probe] Unguarded frame-overlap probe: publish a frame's completions once the frame before it is done SHARPEMU_FRAME_OVERLAP_PROBE=1, default off. THIS PROBE IS UNGUARDED AND FOR MEASUREMENT ONLY: nothing protects what an unfinished frame still reads or writes, so rendering and guest memory may be corrupted. It must never ship or be turned on by default. With the switch on, the host-side publications a frame queues for its GPU completion (host-landed labels, end-of-pipe label slots with parse-time clocks, command-processor writes, end-of-pipe atomic adds and interrupts, the flip's label and interrupt) are published together, in stream order, once the frame is walked and committed and the frame before it has really completed; the guest is at most one frame ahead. Host-landed labels are forced, and flip ahead (SHARPEMU_FLIP_AHEAD) is on for both processes. A frame with an end-of-pipe GDS store, a value only the GPU produces, an unbounded write, an atomic add into its GPU write set, a park on bytes a completion still owes, or a command-processor copy from GPU-produced memory is refused, logged and counted, and published by its real completion. [METAL-V2][OVERLAP-PROBE] reports per window. Off, every hook is one static readonly branch. --- .../Gpu/GpuCommands/CommandStreamQueue.cs | 5 + .../Gpu/GpuCommands/FrameOverlapProbe.cs | 380 ++++++++++++++++++ .../VideoOut/VideoOutExports.FlipAhead.cs | 4 +- .../V2/MetalCommandStream.cs | 91 ++++- .../V2/MetalGpuWriteRanges.cs | 5 + .../SharpEmu.Gpu.Metal/V2/MetalRenderHost.cs | 21 + .../V2/MetalV2Diagnostics.cs | 4 +- .../Gpu/GpuCommands/FrameOverlapProbeTests.cs | 255 ++++++++++++ 8 files changed, 757 insertions(+), 8 deletions(-) create mode 100644 src/SharpEmu.Libs/Gpu/GpuCommands/FrameOverlapProbe.cs create mode 100644 tests/SharpEmu.Libs.Tests/Gpu/GpuCommands/FrameOverlapProbeTests.cs diff --git a/src/SharpEmu.Libs/Gpu/GpuCommands/CommandStreamQueue.cs b/src/SharpEmu.Libs/Gpu/GpuCommands/CommandStreamQueue.cs index efb55c3df..d31b4e91f 100644 --- a/src/SharpEmu.Libs/Gpu/GpuCommands/CommandStreamQueue.cs +++ b/src/SharpEmu.Libs/Gpu/GpuCommands/CommandStreamQueue.cs @@ -1690,6 +1690,11 @@ submission.Kind is not (CommandSubmissionKind.FlipPreparation or CommandSubmissi submission.BlockedPacketAddress = packetAddress; submission.Wait = submission.Commands.SuspendCondition; + if (FrameOverlapProbe.Enabled && !raced) + { + // SHARPEMU_FRAME_OVERLAP_PROBE=1: a park on bytes only a completion writes refuses the frame. + FrameOverlapProbe.Active?.NoteSuspendedWalk(submission.Wait); + } if (submission.Wait.Watched) { // What the packet saw, not what memory holds now: a store that landed diff --git a/src/SharpEmu.Libs/Gpu/GpuCommands/FrameOverlapProbe.cs b/src/SharpEmu.Libs/Gpu/GpuCommands/FrameOverlapProbe.cs new file mode 100644 index 000000000..fb1362d27 --- /dev/null +++ b/src/SharpEmu.Libs/Gpu/GpuCommands/FrameOverlapProbe.cs @@ -0,0 +1,380 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using System.Diagnostics; + +namespace SharpEmu.Libs.Gpu.GpuCommands; + +/// Why a frame's publications were left to its real completion. +public enum FrameOverlapRefusal +{ + /// An end-of-pipe GDS store: the words are whatever the GPU left in the data share. + GdsStore, + + /// A write whose value only the GPU (or its completion) can produce. + GpuValued, + + /// A GPU write with no bounds: the frame's write set is everything. + Unbounded, + + /// An end-of-pipe atomic add into memory the frame's GPU work writes. + AtomicIntoWriteSet, + + /// The walk parked on a wait that only a completion of this stream releases. + SuspendedWalk, + + /// A command-processor copy whose source the GPU still produces. + CopyFromGpu, +} + +/// +/// SHARPEMU_FRAME_OVERLAP_PROBE=1: an UNGUARDED measurement probe, default off, never to be +/// shipped. The host-side publications a frame queues for its GPU completion (host-landed +/// labels, end-of-pipe label slots, command-processor writes, end-of-pipe interrupts) are +/// published together, in stream order, once the frame is fully walked and committed and the +/// frame before it has really completed on the GPU, instead of when the frame itself completes. +/// The guest is then at most one frame ahead of the GPU. Nothing protects what the unfinished +/// frame still reads or writes: rendering and guest memory may be corrupted. A frame that queued +/// a publication the probe cannot make early (see ) is +/// published by its real completion, as without the switch. +/// +/// +/// The probe only reorders work the host already queues. enqueueAtSerial runs an action +/// once the GPU signalled a serial, in serial order and, among equal serials, in the order queued +/// (the Metal completion queue); every publication then runs on that one thread, so a publication +/// that ran early is skipped by its real completion without a lock around the work itself. +/// +public sealed class FrameOverlapProbe +{ + public static readonly bool Enabled = string.Equals( + Environment.GetEnvironmentVariable("SHARPEMU_FRAME_OVERLAP_PROBE"), "1", StringComparison.Ordinal); + + public const string WarningLine = + "unguarded frame-overlap probe: rendering and guest memory are not protected; measurement only"; + + /// The probe the command stream reports into (one GPU host per process). + public static FrameOverlapProbe? Active { get; set; } + + private const int RefusalCount = (int)FrameOverlapRefusal.CopyFromGpu + 1; + private const int MaxRefusalReports = 24; + + private readonly Action _enqueueAtSerial; + private readonly Func _completedSerial; + private readonly Func _clock; + private readonly object _gate = new(); + private Frame _open = new(0, 1); + private Frame? _committed; + private Frame? _lastVisibleFlip; + private int _depth; + private int _refusalReports; + + // Window counters, guarded by _gate. + private long _frames; + private long _framesEarly; + private long _framesAtCompletion; + private long _framesRefused; + private long _framesWaited; + private long _itemsEarly; + private long _flipsEarly; + private long _flips; + private int _depthMax; + private long _suspendedOther; + private readonly long[] _refusals = new long[RefusalCount]; + private readonly List _earlyMs = new(); + private readonly List _periodMs = new(); + + public FrameOverlapProbe(Action enqueueAtSerial, Func completedSerial, Func? clock = null) + { + _enqueueAtSerial = enqueueAtSerial; + _completedSerial = completedSerial; + _clock = clock ?? Stopwatch.GetTimestamp; + } + + /// + /// A publication the open frame queued for its completion. The result is what the real + /// completion runs: the publication unless it already ran early, then + /// , which is never published early. + /// + public Action Track(Action publish, Action? atRealCompletion = null, ulong address = 0, ulong bytes = 0) + { + var item = new Item(publish, address, bytes); + lock (_gate) + { + _open.Items.Add(item); + } + + return atRealCompletion is null + ? () => item.Run() + : () => + { + item.Run(); + atRealCompletion(); + }; + } + + /// The open frame carries a flip. + public void NoteFlip() + { + lock (_gate) + { + _open.HasFlip = true; + } + } + + /// The first serial the open frame's work can carry. + public ulong OpenFrameFirstSerial + { + get + { + lock (_gate) + { + return _open.FirstSerial; + } + } + } + + /// The open frame queued something the probe cannot publish early. + public void Refuse(FrameOverlapRefusal reason, ulong address = 0) + { + lock (_gate) + { + _refusals[(int)reason]++; + var first = _open.Refusal is null; + _open.Refusal ??= reason; + if (first && _refusalReports < MaxRefusalReports) + { + _refusalReports++; + Console.Error.WriteLine( + $"[METAL-V2][OVERLAP-PROBE] refused frame={_open.Index} reason={Name(reason)} address=0x{address:X16}; " + + "it publishes at its real completion"); + } + } + } + + /// + /// The command walk parked a submission of the open frame. A wait on bytes a queued, not yet + /// published completion writes is released only by a completion: the frame is refused. + /// + public void NoteSuspendedWalk(in CommandWaitCondition wait) + { + if (wait.Kind == CommandWaitKind.GuestMemory && wait.Size != 0) + { + bool owed; + lock (_gate) + { + owed = Owes(_open, wait.Address, wait.Size) || (_committed is { } last && Owes(last, wait.Address, wait.Size)); + if (!owed) + { + _suspendedOther++; + } + } + + if (owed) + { + Refuse(FrameOverlapRefusal.SuspendedWalk, wait.Address); + } + + return; + } + + lock (_gate) + { + _suspendedOther++; + } + } + + /// + /// Everything the open frame recorded is committed; finishes it. + /// Its publications go out once the frame before it has really completed, and the next + /// frame's wait for this one's real completion: the guest is at most one frame ahead. + /// + public void OnFrameCommitted(ulong lastSerial) + { + Frame frame; + ulong previousLast; + lock (_gate) + { + frame = _open; + frame.LastSerial = Math.Max(lastSerial, frame.FirstSerial - 1); + frame.CommittedAt = _clock(); + previousLast = _committed?.LastSerial ?? 0; + _committed = frame; + _open = new Frame(frame.Index + 1, frame.LastSerial + 1); + _frames++; + if (previousLast > _completedSerial()) + { + _framesWaited++; + } + } + + _enqueueAtSerial(previousLast, () => Publish(frame)); + _enqueueAtSerial(frame.LastSerial, () => Completed(frame)); + } + + // Runs once the frame before it has really completed (completion thread). + private void Publish(Frame frame) + { + if (frame.Refusal is not null) + { + lock (_gate) + { + _framesRefused++; + } + + return; + } + + var early = _completedSerial() < frame.LastSerial; + var ran = 0; + foreach (var item in frame.Items) + { + if (item.Run()) + { + ran++; + } + } + + lock (_gate) + { + if (!early) + { + _framesAtCompletion++; + return; + } + + frame.PublishedEarly = true; + frame.VisibleAt = _clock(); + _framesEarly++; + _itemsEarly += ran; + _flipsEarly += frame.HasFlip ? 1 : 0; + _depth++; + _depthMax = Math.Max(_depthMax, _depth); + } + } + + // Runs once the frame has really completed (completion thread), after all its items. + private void Completed(Frame frame) + { + var now = _clock(); + lock (_gate) + { + if (frame.PublishedEarly) + { + _depth--; + _earlyMs.Add((now - frame.VisibleAt) * 1000.0 / Stopwatch.Frequency); + } + else + { + frame.VisibleAt = now; + } + + if (frame.HasFlip) + { + _flips++; + if (_lastVisibleFlip is { } previous) + { + _periodMs.Add((frame.VisibleAt - previous.VisibleAt) * 1000.0 / Stopwatch.Frequency); + } + + _lastVisibleFlip = frame; + } + + // Every item has run: none is owed to a wait any more. + frame.Items.Clear(); + } + } + + private static bool Owes(Frame frame, ulong address, ulong size) + { + foreach (var item in frame.Items) + { + if (item.Bytes != 0 && !item.HasRun && address < item.Address + item.Bytes && item.Address < address + size) + { + return true; + } + } + + return false; + } + + public static string Name(FrameOverlapRefusal reason) => reason switch + { + FrameOverlapRefusal.GdsStore => "gds_store", + FrameOverlapRefusal.GpuValued => "gpu_valued", + FrameOverlapRefusal.Unbounded => "unbounded", + FrameOverlapRefusal.AtomicIntoWriteSet => "atomic_write_set", + FrameOverlapRefusal.SuspendedWalk => "suspended_walk", + FrameOverlapRefusal.CopyFromGpu => "copy_from_gpu", + _ => reason.ToString(), + }; + + /// The window's counters as one line, then reset. + public string TakeWindowLine() + { + lock (_gate) + { + var refusals = string.Join(' ', Enumerable.Range(0, RefusalCount).Select(index => + $"{Name((FrameOverlapRefusal)index)}={_refusals[index]}")); + var line = + $"[METAL-V2][OVERLAP-PROBE] frames={_frames} published_early={_framesEarly} " + + $"published_at_completion={_framesAtCompletion} refused_frames={_framesRefused} " + + $"prev_running_at_commit={_framesWaited} items_early={_itemsEarly} " + + $"ms_early_p50={Percentile(_earlyMs, 0.5):F1} ms_early_p90={Percentile(_earlyMs, 0.9):F1} " + + $"depth_max={_depthMax} flips={_flips} flips_early={_flipsEarly} " + + $"flip_period_p50={Percentile(_periodMs, 0.5):F1} flip_period_p90={Percentile(_periodMs, 0.9):F1} " + + $"suspended_other={_suspendedOther} refusals: {refusals}"; + _frames = _framesEarly = _framesAtCompletion = _framesRefused = _framesWaited = 0; + _itemsEarly = _flipsEarly = _flips = _suspendedOther = 0; + _depthMax = _depth; + Array.Clear(_refusals); + _earlyMs.Clear(); + _periodMs.Clear(); + return line; + } + } + + private static double Percentile(List values, double fraction) + { + if (values.Count == 0) + { + return 0; + } + + values.Sort(); + return values[Math.Min(values.Count - 1, (int)(fraction * values.Count))]; + } + + private sealed class Frame(long index, ulong firstSerial) + { + public long Index { get; } = index; + public ulong FirstSerial { get; } = firstSerial; + public ulong LastSerial { get; set; } + public List Items { get; } = new(); + public FrameOverlapRefusal? Refusal { get; set; } + public bool HasFlip { get; set; } + public bool PublishedEarly { get; set; } + public long CommittedAt { get; set; } + public long VisibleAt { get; set; } + } + + private sealed class Item(Action publish, ulong address, ulong bytes) + { + private int _ran; + + public ulong Address { get; } = address; + public ulong Bytes { get; } = bytes; + public bool HasRun => Volatile.Read(ref _ran) != 0; + + // Runs the publication once, whoever gets there first; true when this call ran it. + public bool Run() + { + if (Interlocked.Exchange(ref _ran, 1) != 0) + { + return false; + } + + publish(); + return true; + } + } +} diff --git a/src/SharpEmu.Libs/VideoOut/VideoOutExports.FlipAhead.cs b/src/SharpEmu.Libs/VideoOut/VideoOutExports.FlipAhead.cs index 4ab7b331e..493b6ecbf 100644 --- a/src/SharpEmu.Libs/VideoOut/VideoOutExports.FlipAhead.cs +++ b/src/SharpEmu.Libs/VideoOut/VideoOutExports.FlipAhead.cs @@ -16,8 +16,10 @@ namespace SharpEmu.Libs.VideoOut; // the notice (switch off, or a flip whose frame was not copied) nothing here runs. public static partial class VideoOutExports { + // SHARPEMU_FRAME_OVERLAP_PROBE=1 (the unguarded measurement probe) turns it on too. internal static bool FlipAheadEnabled { get; set; } = string.Equals( - Environment.GetEnvironmentVariable("SHARPEMU_FLIP_AHEAD"), "1", StringComparison.Ordinal); + Environment.GetEnvironmentVariable("SHARPEMU_FLIP_AHEAD"), "1", StringComparison.Ordinal) || + SharpEmu.Libs.Gpu.GpuCommands.FrameOverlapProbe.Enabled; // The last GPU-queued request reserved on each handle. Guarded by the state gate. private static readonly Dictionary _lastGpuQueuedFlip = new(); diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalCommandStream.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalCommandStream.cs index 77370f60b..d01800ea9 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalCommandStream.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalCommandStream.cs @@ -127,6 +127,12 @@ void ICommandStreamHost.FlushFrame() // Everything the frame recorded is committed: this serial finishes it. SharpEmu.HLE.GpuMemory.FrameOverlapDiagnostic.OnFrameCommitted(Volatile.Read(ref _submittedSerial)); } + + if (SharpEmu.Libs.Gpu.GpuCommands.FrameOverlapProbe.Enabled) + { + // SHARPEMU_FRAME_OVERLAP_PROBE=1 (unguarded): the frame's publications may go out early. + _overlapProbe!.OnFrameCommitted(Volatile.Read(ref _submittedSerial)); + } } // ---- command-buffer coalescing (SHARPEMU_METAL_V2_FLUSH_COALESCE) ---- @@ -888,6 +894,12 @@ public void RecordEndOfPipe(in EndOfPipeWrite write) label = write with { ReferenceClock = false }; } + if (SharpEmu.Libs.Gpu.GpuCommands.FrameOverlapProbe.Enabled && + RecordEndOfPipeForOverlapProbe(in write, in label, encoded, owed)) + { + return; + } + switch (write.Kind) { case EndOfPipeWriteKind.InterruptOnly: @@ -938,13 +950,56 @@ public void RecordEndOfPipe(in EndOfPipeWrite write) if (!encoded) { QueueCompletion(() => PublishHostLabel(in label, owed), - lazy ? (label.Destination, EndOfPipeLabelBytes(label.Kind)) : null); + lazy ? (label.Destination, EndOfPipeLabelBytes(label.Kind)) : null, + probeRange: (label.Destination, EndOfPipeLabelBytes(label.Kind))); } break; } } + // SHARPEMU_FRAME_OVERLAP_PROBE=1 (unguarded, measurement only). Refuses the open frame for an + // end-of-pipe write the probe cannot publish before the GPU finishes it, and records a flip with + // its label and interrupt published by the probe while the flip's own GPU completion stays at the + // real completion (flip ahead tells video-out about the flip). True when the flip was recorded here. + private bool RecordEndOfPipeForOverlapProbe(in EndOfPipeWrite write, in EndOfPipeWrite label, bool encoded, bool owed) + { + var probe = _overlapProbe!; + if (write.Kind == EndOfPipeWriteKind.GdsWrite32) + { + probe.Refuse(SharpEmu.Libs.Gpu.GpuCommands.FrameOverlapRefusal.GdsStore, write.Destination); + } + else if (label.ReferenceClock || (encoded && EndOfPipeLabelBytes(write.Kind) != 0)) + { + // A clock sampled at completion, or a label the GPU writes itself: its value is the GPU's. + probe.Refuse(SharpEmu.Libs.Gpu.GpuCommands.FrameOverlapRefusal.GpuValued, write.Destination); + } + + if (write.Kind is not (EndOfPipeWriteKind.Flip or EndOfPipeWriteKind.FlipWithWrite32 or + EndOfPipeWriteKind.FlipWithInterruptWriteBack32)) + { + return false; + } + + probe.NoteFlip(); + NoteFlipSerialForEarlyLabels(); + var published = label; + var requestId = write.FlipRequestId; + var eventId = write.EventId; + var interrupt = write.Kind == EndOfPipeWriteKind.FlipWithInterruptWriteBack32; + QueueCompletion(() => + { + if (!encoded) PublishHostLabel(in published, owed); + if (interrupt) TriggerInterrupt(eventId, 0); + }, atRealCompletion: () => + { + VideoOutBackendServices.CompleteFlipOnGpu(requestId); + MetalV2Presenter.SignalFlipPacer(); + }, probeRange: (published.Destination, EndOfPipeLabelBytes(published.Kind))); + NoteFlipRecordedIfEligible(requestId); + return true; + } + /// The interpreter leaves end-of-pipe GDS stores to this host (RecordEndOfPipeGdsWrite). public bool WritesGdsAtEndOfPipe => true; @@ -1006,7 +1061,7 @@ private void RecordEndOfPipeGdsWrite(in EndOfPipeWrite write) { Interlocked.Decrement(ref _owedHostLabels); } - }); + }, probeRange: (destinationAddress, (int)bytes)); } /// @@ -1057,6 +1112,12 @@ private void RecordEndOfPipeAtomicAdd(in EndOfPipeWrite write) var address = write.Destination; var addend = (uint)write.Value; + if (SharpEmu.Libs.Gpu.GpuCommands.FrameOverlapProbe.Enabled && + _gpuWrites.WrittenSince(address, sizeof(uint), _overlapProbe!.OpenFrameFirstSerial)) + { + _overlapProbe.Refuse(SharpEmu.Libs.Gpu.GpuCommands.FrameOverlapRefusal.AtomicIntoWriteSet, address); + } + Interlocked.Increment(ref _owedHostLabels); QueueCompletion(() => { @@ -1073,7 +1134,7 @@ private void RecordEndOfPipeAtomicAdd(in EndOfPipeWrite write) { Interlocked.Decrement(ref _owedHostLabels); } - }); + }, probeRange: (address, sizeof(uint))); } /// @@ -1502,7 +1563,7 @@ public void RecordCommandProcessorWrite(ulong address, ReadOnlySpan source { Interlocked.Decrement(ref _owedHostLabels); } - }, lazy ? (address, bytes.Length) : null); + }, lazy ? (address, bytes.Length) : null, probeRange: (address, bytes.Length)); } // SHARPEMU_METAL_V2_EARLY_LABEL_PROBE (MetalV2Diagnostics.EarlyLabelProbe): the serial whose completion @@ -2635,8 +2696,10 @@ private void PublishClockAtCompletion(in EndOfPipeWrite label) // finished, so a title that writes a label per render pass pays both per pass: // measured at 9.5 fps against 24. The GPU writing the label where its packet sits // says the same thing and costs neither, which is why it is the default. + // SHARPEMU_FRAME_OVERLAP_PROBE=1 forces host-landed labels: the probe publishes what completions land. private static readonly bool GpuTimedLabels = - Environment.GetEnvironmentVariable("SHARPEMU_METAL_V2_GPU_LABELS") != "0"; + Environment.GetEnvironmentVariable("SHARPEMU_METAL_V2_GPU_LABELS") != "0" && + !SharpEmu.Libs.Gpu.GpuCommands.FrameOverlapProbe.Enabled; /// /// The interpreter must never publish label bytes itself on this host: it parses a @@ -2815,15 +2878,31 @@ private void CountClockForcedLabel() /// ): the worker commits it when it parks, and a wait /// packet polling these bytes commits it through the Poll cause. /// - private void QueueCompletion(Action work, (ulong Address, int Bytes)? lazyLabel = null) + /// + /// SHARPEMU_FRAME_OVERLAP_PROBE=1 only: work that runs at the real completion, after + /// , and is never published early. + /// + /// SHARPEMU_FRAME_OVERLAP_PROBE=1 only: the bytes the work writes. + private void QueueCompletion( + Action work, + (ulong Address, int Bytes)? lazyLabel = null, + Action? atRealCompletion = null, + (ulong Address, int Bytes) probeRange = default) { if (InlineCompletions && LastWorkSerial <= CompletedSerial && _completions.PendingCount == 0) { Interlocked.Increment(ref _inlineCompletionCount); work(); + atRealCompletion?.Invoke(); return; } + if (SharpEmu.Libs.Gpu.GpuCommands.FrameOverlapProbe.Enabled) + { + // SHARPEMU_FRAME_OVERLAP_PROBE=1 (unguarded): the open frame may publish it early. + work = _overlapProbe!.Track(work, atRealCompletion, probeRange.Address, (ulong)Math.Max(0, probeRange.Bytes)); + } + // Nothing has been recorded since the last flush, so everything this completion // waits for is in the submission already committed: it rides that one's serial // and needs no flush of its own. A run of end-of-pipe labels with no work diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalGpuWriteRanges.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalGpuWriteRanges.cs index ec6131893..1fcacaabf 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalGpuWriteRanges.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalGpuWriteRanges.cs @@ -506,6 +506,11 @@ public void NoteUnbounded(ulong serial) SharpEmu.HLE.GpuMemory.FrameOverlapDiagnostic.NoteGpuWrite(0, 0, SharpEmu.HLE.GpuMemory.OverlapWrite.Unbounded); } + if (SharpEmu.Libs.Gpu.GpuCommands.FrameOverlapProbe.Enabled) + { + SharpEmu.Libs.Gpu.GpuCommands.FrameOverlapProbe.Active?.Refuse(SharpEmu.Libs.Gpu.GpuCommands.FrameOverlapRefusal.Unbounded); + } + BeginMutation(); try { diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.cs index 678d36752..39b1784ee 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.cs @@ -90,6 +90,8 @@ private string FormatGraphicsBindingCounters() => private readonly IMetalImageTransfer _transfer; private readonly MetalGpuWorkerRelay _relay; private readonly MetalCompletionQueue _completions; + // SHARPEMU_FRAME_OVERLAP_PROBE=1 only (unguarded measurement probe). + private readonly SharpEmu.Libs.Gpu.GpuCommands.FrameOverlapProbe? _overlapProbe; private nint _commandBuffer; private nint _previousCommandBuffer; @@ -201,6 +203,13 @@ public MetalRenderHost( _imageCache.StagedRanges = _stagedRanges; } _completions = new MetalCompletionQueue(_sharedEvent); + if (SharpEmu.Libs.Gpu.GpuCommands.FrameOverlapProbe.Enabled) + { + Console.Error.WriteLine("[METAL-V2][OVERLAP-PROBE][WARN] " + SharpEmu.Libs.Gpu.GpuCommands.FrameOverlapProbe.WarningLine); + _overlapProbe = new SharpEmu.Libs.Gpu.GpuCommands.FrameOverlapProbe( + (serial, action) => _completions.Enqueue(serial, action), () => CompletedSerial); + SharpEmu.Libs.Gpu.GpuCommands.FrameOverlapProbe.Active = _overlapProbe; + } RegisterMemoryTelemetry(); } @@ -1810,6 +1819,13 @@ public void CopyGuestMemory(ulong destination, ulong source, ulong size, bool al return; } + if (SharpEmu.Libs.Gpu.GpuCommands.FrameOverlapProbe.Enabled && + (_imageCache.HasGpuModifiedImageBytes(source, size) || PendingSerialHinted(source, size) != 0)) + { + // SHARPEMU_FRAME_OVERLAP_PROBE=1: the GPU still produces what this copy reads. + _overlapProbe!.Refuse(SharpEmu.Libs.Gpu.GpuCommands.FrameOverlapRefusal.CopyFromGpu, source); + } + FlushGpuWrites(source, size, MetalWritebackCause.GuestCopy); // A label held for the commit over the source or the destination lands first, as a boundary used to land it. OrderAfterDeferredCopies(source, size, LabelLandCause.Transfer); @@ -2855,6 +2871,11 @@ public void ReportCounters() Console.Error.WriteLine(overlapLine); } + if (SharpEmu.Libs.Gpu.GpuCommands.FrameOverlapProbe.Enabled) + { + Console.Error.WriteLine(_overlapProbe!.TakeWindowLine()); + } + _slowWaitReports = 0; ResetSlowCompletionReports(); if (WaitOrigins && _waitOrigins.Count != 0) diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalV2Diagnostics.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalV2Diagnostics.cs index d07215d3c..78aadd6a6 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalV2Diagnostics.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalV2Diagnostics.cs @@ -156,7 +156,9 @@ private static HashSet ParseHashes(string? text) // SHARPEMU_FLIP_AHEAD=1 (experimental, default off): a GPU flip hands the presenter a copy of its // frame, blitted in the stream at the flip, and tells video-out the flip is recorded, so the guest // may learn of it before the GPU finishes it (VideoOutExports.FlipAhead.cs, MetalFlipCopyPool). - public static readonly bool FlipAhead = Environment.GetEnvironmentVariable("SHARPEMU_FLIP_AHEAD") == "1"; + // SHARPEMU_FRAME_OVERLAP_PROBE=1 turns it on too. + public static readonly bool FlipAhead = Environment.GetEnvironmentVariable("SHARPEMU_FLIP_AHEAD") == "1" || + SharpEmu.Libs.Gpu.GpuCommands.FrameOverlapProbe.Enabled; public static readonly int EarlyLabelProbe = Environment.GetEnvironmentVariable("SHARPEMU_METAL_V2_EARLY_LABEL_PROBE") switch diff --git a/tests/SharpEmu.Libs.Tests/Gpu/GpuCommands/FrameOverlapProbeTests.cs b/tests/SharpEmu.Libs.Tests/Gpu/GpuCommands/FrameOverlapProbeTests.cs new file mode 100644 index 000000000..d7666abc2 --- /dev/null +++ b/tests/SharpEmu.Libs.Tests/Gpu/GpuCommands/FrameOverlapProbeTests.cs @@ -0,0 +1,255 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using SharpEmu.HLE; +using SharpEmu.Libs.Gpu.GpuCommands; +using SharpEmu.Libs.Gpu.Scheduling; +using Xunit; + +namespace SharpEmu.Libs.Tests.Gpu.GpuCommands; + +/// +/// SHARPEMU_FRAME_OVERLAP_PROBE's publication rules on the managed host, with a fake GPU timeline +/// standing in for the Metal completion queue: a frame publishes at its commit once the frame +/// before it really completed, in stream order behind anything older; never two frames ahead; +/// a refused frame waits for its real completion; real-completion-only work never runs early. +/// +public sealed class FrameOverlapProbeTests +{ + // Runs work once its serial is signalled: in serial order, and in queue order among equals. + private sealed class FakeGpu + { + private readonly List<(ulong Serial, Action Work)> _pending = new(); + + public ulong Signaled { get; private set; } + + public void Enqueue(ulong serial, Action work) => _pending.Add((serial, work)); + + public void Signal(ulong value) + { + Signaled = Math.Max(Signaled, value); + Pump(); + } + + // The completion thread waking: everything already signalled runs. + public void Pump() + { + while (true) + { + var index = -1; + for (var candidate = 0; candidate < _pending.Count; candidate++) + { + if (_pending[candidate].Serial <= Signaled && + (index < 0 || _pending[candidate].Serial < _pending[index].Serial)) + { + index = candidate; + } + } + + if (index < 0) + { + return; + } + + var work = _pending[index].Work; + _pending.RemoveAt(index); + work(); + } + } + } + + private sealed class Log : IEndOfPipeSink, ICommandStreamFlipTarget + { + public List Entries { get; } = new(); + + public void TriggerInterrupt(int eventId, uint contextId) => Entries.Add($"interrupt {eventId}"); + + public ulong Prepare(int handle, int index, int flipMode, long flipArgument) => 0; + + public void Complete(ulong requestId) => Entries.Add($"flip {requestId}"); + + public void Presented(ulong requestId) + { + } + + public bool IsDone(int handle, int index) => true; + } + + private sealed class NullMemory : ICpuMemory + { + public bool TryRead(ulong virtualAddress, Span destination) => true; + + public bool TryWrite(ulong virtualAddress, ReadOnlySpan source) => true; + } + + // The managed host, with its end-of-pipe work queued for a GPU completion through the probe + // the way the Metal host queues it, and serials advancing at every commit. + private sealed class ProbeHost : ManagedCommandStreamHost + { + public ProbeHost(FakeGpu gpu, Log log) : base(new NullMemory(), log, log) + { + Gpu = gpu; + Probe = new FrameOverlapProbe(gpu.Enqueue, () => gpu.Signaled); + } + + public FakeGpu Gpu { get; } + + public FrameOverlapProbe Probe { get; } + + public ulong OpenSerial { get; private set; } = 1; + + public override void RecordEndOfPipe(in EndOfPipeWrite write) + { + var copy = write; + Gpu.Enqueue(OpenSerial, Probe.Track(() => base.RecordEndOfPipe(copy), address: copy.Destination, + bytes: copy.Destination == 0 ? 0UL : sizeof(uint))); + } + + // A flip whose own completion stays with the GPU, as the Metal host records it under the probe. + public void RecordFlip(ulong requestId, int eventId) + { + Probe.NoteFlip(); + Gpu.Enqueue(OpenSerial, Probe.Track( + () => TriggerInterrupt(eventId, 0), + atRealCompletion: () => base.RecordEndOfPipe(new EndOfPipeWrite(EndOfPipeWriteKind.Flip, 0, FlipRequestId: requestId)))); + } + + public void Interrupt(int eventId, ulong destination = 0) => + RecordEndOfPipe(new EndOfPipeWrite(EndOfPipeWriteKind.InterruptOnly, 0, Destination: destination, EventId: eventId)); + + public override void Flush() => OpenSerial++; + + // FlushFrame: the frame's last buffer is committed with the open serial. + public void CommitFrame() + { + var last = OpenSerial++; + Probe.OnFrameCommitted(last); + } + } + + private readonly FakeGpu _gpu = new(); + private readonly Log _log = new(); + + private static string Counter(string line, string name) + { + var start = line.IndexOf(" " + name + "=", StringComparison.Ordinal); + Assert.True(start >= 0, $"{name} missing from: {line}"); + start += name.Length + 2; + var end = line.IndexOf(' ', start); + return end < 0 ? line[start..] : line[start..end]; + } + + [Fact] + public void AFramePublishesAtItsCommitOnceThePreviousFrameIsDone() + { + var host = new ProbeHost(_gpu, _log); + host.Interrupt(1); + host.Flush(); + host.Interrupt(2); + host.CommitFrame(); + _gpu.Pump(); + + Assert.Equal(["interrupt 1", "interrupt 2"], _log.Entries); + + // The real completion finds them published and does not publish them again. + _gpu.Signal(2); + Assert.Equal(["interrupt 1", "interrupt 2"], _log.Entries); + var line = host.Probe.TakeWindowLine(); + Assert.Equal("1", Counter(line, "published_early")); + Assert.Equal("2", Counter(line, "items_early")); + Assert.Equal("1", Counter(line, "depth_max")); + } + + [Fact] + public void TheNextFrameWaitsForThePublishedFrameToReallyComplete() + { + var host = new ProbeHost(_gpu, _log); + host.Interrupt(1); + host.CommitFrame(); + _gpu.Pump(); + host.Interrupt(2); + host.CommitFrame(); + _gpu.Pump(); + + // Frame 0 is published and still on the GPU: frame 1 is not published, the guest is one ahead. + Assert.Equal(["interrupt 1"], _log.Entries); + + // Frame 0 completes after frame 1's commit: frame 1 publishes at that completion, still early. + _gpu.Signal(1); + Assert.Equal(["interrupt 1", "interrupt 2"], _log.Entries); + var line = host.Probe.TakeWindowLine(); + Assert.Equal("2", Counter(line, "published_early")); + Assert.Equal("1", Counter(line, "prev_running_at_commit")); + Assert.Equal("1", Counter(line, "depth_max")); + + _gpu.Signal(2); + Assert.Equal(["interrupt 1", "interrupt 2"], _log.Entries); + } + + [Fact] + public void ARefusedFramePublishesAtItsRealCompletionAndStreamOrderHolds() + { + var host = new ProbeHost(_gpu, _log); + host.Interrupt(1); + host.Probe.Refuse(FrameOverlapRefusal.GdsStore, 0x1000); + host.Interrupt(2); + host.CommitFrame(); + _gpu.Pump(); + Assert.Empty(_log.Entries); + + host.Interrupt(3); + host.Interrupt(4); + host.CommitFrame(); + _gpu.Pump(); + Assert.Empty(_log.Entries); + + // Frame 0 completes: its own completions run, then frame 1 publishes behind them. + _gpu.Signal(1); + Assert.Equal(["interrupt 1", "interrupt 2", "interrupt 3", "interrupt 4"], _log.Entries); + var line = host.Probe.TakeWindowLine(); + Assert.Equal("1", Counter(line, "refused_frames")); + Assert.Equal("1", Counter(line, "published_early")); + Assert.Equal("1", Counter(line, "gds_store")); + } + + [Fact] + public void RealCompletionWorkNeverRunsEarly() + { + var host = new ProbeHost(_gpu, _log); + host.Interrupt(1); + host.RecordFlip(requestId: 7, eventId: 2); + host.CommitFrame(); + _gpu.Pump(); + + // The flip's interrupt goes out with the frame; the flip's GPU completion does not. + Assert.Equal(["interrupt 1", "interrupt 2"], _log.Entries); + _gpu.Signal(1); + Assert.Equal(["interrupt 1", "interrupt 2", "flip 7"], _log.Entries); + var line = host.Probe.TakeWindowLine(); + Assert.Equal("1", Counter(line, "flips_early")); + } + + [Fact] + public void AParkOnBytesACompletionStillOwesRefusesTheFrame() + { + var host = new ProbeHost(_gpu, _log); + host.Interrupt(1, destination: 0x2000); + host.Probe.NoteSuspendedWalk(CommandWaitCondition.Memory(0x3000, 4)); + host.CommitFrame(); + _gpu.Pump(); + Assert.Equal(["interrupt 1"], _log.Entries); + + host.Interrupt(2, destination: 0x2100); + host.Probe.NoteSuspendedWalk(CommandWaitCondition.Memory(0x2100, 4)); + host.CommitFrame(); + _gpu.Signal(1); + Assert.Empty(_log.Entries.Skip(1)); + + _gpu.Signal(2); + Assert.Equal(["interrupt 1", "interrupt 2"], _log.Entries); + var line = host.Probe.TakeWindowLine(); + Assert.Equal("1", Counter(line, "suspended_walk")); + Assert.Equal("1", Counter(line, "suspended_other")); + Assert.Equal("1", Counter(line, "refused_frames")); + } +} From 21028604dc65ac7cae13574d33c558104cf8b430 Mon Sep 17 00:00:00 2001 From: kuba Date: Mon, 16 Nov 2026 08:01:36 +0000 Subject: [PATCH 127/178] [Probe] Frame-overlap probe: SHARPEMU_FRAME_OVERLAP_PROBE_WAITS=count counts owed-byte parks instead of refusing Unguarded, measurement only, like the probe itself. --- .../Gpu/GpuCommands/FrameOverlapProbe.cs | 17 ++++++++++++++--- 1 file changed, 14 insertions(+), 3 deletions(-) diff --git a/src/SharpEmu.Libs/Gpu/GpuCommands/FrameOverlapProbe.cs b/src/SharpEmu.Libs/Gpu/GpuCommands/FrameOverlapProbe.cs index fb1362d27..299033470 100644 --- a/src/SharpEmu.Libs/Gpu/GpuCommands/FrameOverlapProbe.cs +++ b/src/SharpEmu.Libs/Gpu/GpuCommands/FrameOverlapProbe.cs @@ -49,6 +49,12 @@ public sealed class FrameOverlapProbe public static readonly bool Enabled = string.Equals( Environment.GetEnvironmentVariable("SHARPEMU_FRAME_OVERLAP_PROBE"), "1", StringComparison.Ordinal); + // SHARPEMU_FRAME_OVERLAP_PROBE_WAITS=count: a park on owed bytes is counted (suspended_owed) + // instead of refusing the frame. By the frame's commit the walk is past the wait, so this measures + // what the refusal costs. + public static readonly bool CountOwedWaitsOnly = string.Equals( + Environment.GetEnvironmentVariable("SHARPEMU_FRAME_OVERLAP_PROBE_WAITS"), "count", StringComparison.Ordinal); + public const string WarningLine = "unguarded frame-overlap probe: rendering and guest memory are not protected; measurement only"; @@ -79,6 +85,7 @@ public sealed class FrameOverlapProbe private long _flips; private int _depthMax; private long _suspendedOther; + private long _suspendedOwed; private readonly long[] _refusals = new long[RefusalCount]; private readonly List _earlyMs = new(); private readonly List _periodMs = new(); @@ -167,9 +174,13 @@ public void NoteSuspendedWalk(in CommandWaitCondition wait) { _suspendedOther++; } + else if (CountOwedWaitsOnly) + { + _suspendedOwed++; + } } - if (owed) + if (owed && !CountOwedWaitsOnly) { Refuse(FrameOverlapRefusal.SuspendedWalk, wait.Address); } @@ -322,9 +333,9 @@ public string TakeWindowLine() $"ms_early_p50={Percentile(_earlyMs, 0.5):F1} ms_early_p90={Percentile(_earlyMs, 0.9):F1} " + $"depth_max={_depthMax} flips={_flips} flips_early={_flipsEarly} " + $"flip_period_p50={Percentile(_periodMs, 0.5):F1} flip_period_p90={Percentile(_periodMs, 0.9):F1} " + - $"suspended_other={_suspendedOther} refusals: {refusals}"; + $"suspended_other={_suspendedOther} suspended_owed={_suspendedOwed} refusals: {refusals}"; _frames = _framesEarly = _framesAtCompletion = _framesRefused = _framesWaited = 0; - _itemsEarly = _flipsEarly = _flips = _suspendedOther = 0; + _itemsEarly = _flipsEarly = _flips = _suspendedOther = _suspendedOwed = 0; _depthMax = _depth; Array.Clear(_refusals); _earlyMs.Clear(); From 8e6a007ff9a70d33403bb5077e2f2e23881240c0 Mon Sep 17 00:00:00 2001 From: kuba Date: Mon, 16 Nov 2026 08:19:59 +0000 Subject: [PATCH 128/178] [Probe] Frame-overlap probe: no per-label commits, queued values answer waits until they land Still SHARPEMU_FRAME_OVERLAP_PROBE=1 only, UNGUARDED and for measurement. Round 1 forced host-landed labels and every one committed its own command buffer (~310 per frame), which serialized the walk behind the GPU. Under the probe now: a record-time-known publication rides the next commit instead of forcing one; pending labels carry no completion tick and stay in the queue's table (answering waits and parse-time reads, as the default mode's pending labels do) until their publication has written memory (CommandStreamQueue.LandPendingLabels); a copy whose source is a queued publication is queued behind it as a host copy. SHARPEMU_FRAME_OVERLAP_PROBE_AFTER_S= arms early publication only after that delay. --- .../Gpu/GpuCommands/CommandStreamQueue.cs | 82 +++++++++++++++++++ .../Gpu/GpuCommands/FrameOverlapProbe.cs | 58 ++++++++++++- .../V2/MetalCommandStream.cs | 33 +++++++- .../SharpEmu.Gpu.Metal/V2/MetalRenderHost.cs | 14 +++- .../Gpu/GpuCommands/FrameOverlapProbeTests.cs | 68 +++++++++++++++ 5 files changed, 250 insertions(+), 5 deletions(-) diff --git a/src/SharpEmu.Libs/Gpu/GpuCommands/CommandStreamQueue.cs b/src/SharpEmu.Libs/Gpu/GpuCommands/CommandStreamQueue.cs index d31b4e91f..d8c71b604 100644 --- a/src/SharpEmu.Libs/Gpu/GpuCommands/CommandStreamQueue.cs +++ b/src/SharpEmu.Libs/Gpu/GpuCommands/CommandStreamQueue.cs @@ -1186,6 +1186,88 @@ submission.Kind is not (CommandSubmissionKind.Graphics or CommandSubmissionKind. return count; } + /// How many pending labels the queue holds (SHARPEMU_FRAME_OVERLAP_PROBE's leak check). + public int PendingLabelCount + { + get + { + lock (_labelGate) + { + return _pendingLabels.Count; + } + } + } + + /// + /// SHARPEMU_FRAME_OVERLAP_PROBE=1: a host that notes pending labels with no completion tick lands them + /// here once its publication wrote the bytes. An entry overlapping the range whose value memory now + /// holds is dropped; one a newer write replaced (memory holds something else) stays. + /// + public void LandPendingLabels(ulong address, ulong size, SharpEmu.HLE.ICpuMemory memory) + { + if (size == 0 || address > ulong.MaxValue - size) + { + return; + } + + Span bytes = stackalloc byte[sizeof(ulong)]; + var end = address + size; + lock (_labelGate) + { + if (_pendingLabels.Count == 0) + { + return; + } + + if (size <= 256) + { + for (var at = address >= sizeof(uint) ? (address - sizeof(uint)) & ~3UL : 0; at < end; at += sizeof(uint)) + { + if (_pendingLabels.TryGetValue(at, out var label) && Written(memory, bytes, at, label.Value, label.Size)) + { + _landedLabels.Add(at); + } + } + } + else + { + foreach (var (at, label) in _pendingLabels) + { + if (Written(memory, bytes, at, label.Value, label.Size)) + { + _landedLabels.Add(at); + } + } + } + + foreach (var at in _landedLabels) + { + _pendingLabels.Remove(at); + } + + _landedLabels.Clear(); + } + + bool Written(SharpEmu.HLE.ICpuMemory source, Span scratch, ulong at, ulong value, int labelSize) + { + if (at >= end || at + (ulong)labelSize <= address) + { + return false; + } + + var span = scratch[..labelSize]; + if (!source.TryRead(at, span)) + { + return false; + } + + var held = labelSize == sizeof(ulong) + ? System.Buffers.Binary.BinaryPrimitives.ReadUInt64LittleEndian(span) + : System.Buffers.Binary.BinaryPrimitives.ReadUInt32LittleEndian(span); + return held == value; + } + } + private bool TryGetPendingLabel(ulong address, bool is64Bit, out ulong value) { lock (_labelGate) diff --git a/src/SharpEmu.Libs/Gpu/GpuCommands/FrameOverlapProbe.cs b/src/SharpEmu.Libs/Gpu/GpuCommands/FrameOverlapProbe.cs index 299033470..4be9d2a41 100644 --- a/src/SharpEmu.Libs/Gpu/GpuCommands/FrameOverlapProbe.cs +++ b/src/SharpEmu.Libs/Gpu/GpuCommands/FrameOverlapProbe.cs @@ -55,6 +55,14 @@ public sealed class FrameOverlapProbe public static readonly bool CountOwedWaitsOnly = string.Equals( Environment.GetEnvironmentVariable("SHARPEMU_FRAME_OVERLAP_PROBE_WAITS"), "count", StringComparison.Ordinal); + // SHARPEMU_FRAME_OVERLAP_PROBE_AFTER_S=: frames publish early only that long after the probe + // started (boot and menus publish at real completion); the other probe rules apply from the start. + private static readonly double ArmAfterSeconds = + double.TryParse(Environment.GetEnvironmentVariable("SHARPEMU_FRAME_OVERLAP_PROBE_AFTER_S"), + System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture, out var seconds) && seconds > 0 + ? seconds + : 0; + public const string WarningLine = "unguarded frame-overlap probe: rendering and guest memory are not protected; measurement only"; @@ -70,6 +78,10 @@ public sealed class FrameOverlapProbe private readonly object _gate = new(); private Frame _open = new(0, 1); private Frame? _committed; + // Committed frames whose real completion has not run yet, oldest first. + private readonly List _unfinished = new(); + private readonly long _armAt; + private long _framesUnarmed; private Frame? _lastVisibleFlip; private int _depth; private int _refusalReports; @@ -95,6 +107,34 @@ public FrameOverlapProbe(Action enqueueAtSerial, Func comp _enqueueAtSerial = enqueueAtSerial; _completedSerial = completedSerial; _clock = clock ?? Stopwatch.GetTimestamp; + _armAt = ArmAfterSeconds > 0 ? _clock() + (long)(ArmAfterSeconds * Stopwatch.Frequency) : long.MinValue; + } + + /// Whether a publication still queued (not yet run) writes any of these bytes. + public bool Owes(ulong address, ulong size) + { + lock (_gate) + { + return OwesLocked(address, size); + } + } + + private bool OwesLocked(ulong address, ulong size) + { + if (Owes(_open, address, size)) + { + return true; + } + + foreach (var frame in _unfinished) + { + if (Owes(frame, address, size)) + { + return true; + } + } + + return false; } /// @@ -169,7 +209,7 @@ public void NoteSuspendedWalk(in CommandWaitCondition wait) bool owed; lock (_gate) { - owed = Owes(_open, wait.Address, wait.Size) || (_committed is { } last && Owes(last, wait.Address, wait.Size)); + owed = OwesLocked(wait.Address, wait.Size); if (!owed) { _suspendedOther++; @@ -210,6 +250,7 @@ public void OnFrameCommitted(ulong lastSerial) frame.CommittedAt = _clock(); previousLast = _committed?.LastSerial ?? 0; _committed = frame; + _unfinished.Add(frame); _open = new Frame(frame.Index + 1, frame.LastSerial + 1); _frames++; if (previousLast > _completedSerial()) @@ -235,6 +276,16 @@ private void Publish(Frame frame) return; } + if (_clock() < _armAt) + { + lock (_gate) + { + _framesUnarmed++; + } + + return; + } + var early = _completedSerial() < frame.LastSerial; var ran = 0; foreach (var item in frame.Items) @@ -292,6 +343,7 @@ private void Completed(Frame frame) // Every item has run: none is owed to a wait any more. frame.Items.Clear(); + _unfinished.Remove(frame); } } @@ -328,13 +380,13 @@ public string TakeWindowLine() $"{Name((FrameOverlapRefusal)index)}={_refusals[index]}")); var line = $"[METAL-V2][OVERLAP-PROBE] frames={_frames} published_early={_framesEarly} " + - $"published_at_completion={_framesAtCompletion} refused_frames={_framesRefused} " + + $"published_at_completion={_framesAtCompletion} refused_frames={_framesRefused} unarmed={_framesUnarmed} " + $"prev_running_at_commit={_framesWaited} items_early={_itemsEarly} " + $"ms_early_p50={Percentile(_earlyMs, 0.5):F1} ms_early_p90={Percentile(_earlyMs, 0.9):F1} " + $"depth_max={_depthMax} flips={_flips} flips_early={_flipsEarly} " + $"flip_period_p50={Percentile(_periodMs, 0.5):F1} flip_period_p90={Percentile(_periodMs, 0.9):F1} " + $"suspended_other={_suspendedOther} suspended_owed={_suspendedOwed} refusals: {refusals}"; - _frames = _framesEarly = _framesAtCompletion = _framesRefused = _framesWaited = 0; + _frames = _framesEarly = _framesAtCompletion = _framesRefused = _framesWaited = _framesUnarmed = 0; _itemsEarly = _flipsEarly = _flips = _suspendedOther = _suspendedOwed = 0; _depthMax = _depth; Array.Clear(_refusals); diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalCommandStream.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalCommandStream.cs index d01800ea9..81a757340 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalCommandStream.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalCommandStream.cs @@ -2718,7 +2718,11 @@ private void PublishClockAtCompletion(in EndOfPipeWrite label) // On the command thread the buffer the label will ride is not open yet: the worker's serial is a // provisional tick (too early only makes a wait read memory again), and the worker gives the real // one when it records the label (RecordEndOfPipe). - public ulong PendingLabelTick => !PendingLabelsVisible ? 0 : OnCommandThread ? Volatile.Read(ref _submissionSerial) : SubmissionSerial; + // SHARPEMU_FRAME_OVERLAP_PROBE=1: no completion tick lands a host-published label; its publication does + // (QueueCompletion lands it in the queue once it wrote the bytes). + public ulong PendingLabelTick => !PendingLabelsVisible ? 0 : + SharpEmu.Libs.Gpu.GpuCommands.FrameOverlapProbe.Enabled ? ulong.MaxValue : + OnCommandThread ? Volatile.Read(ref _submissionSerial) : SubmissionSerial; private static readonly bool PendingLabelsVisible = Environment.GetEnvironmentVariable("SHARPEMU_METAL_V2_PENDING_LABELS") != "0"; @@ -2889,6 +2893,19 @@ private void QueueCompletion( Action? atRealCompletion = null, (ulong Address, int Bytes) probeRange = default) { + if (SharpEmu.Libs.Gpu.GpuCommands.FrameOverlapProbe.Enabled && probeRange.Bytes > 0) + { + // SHARPEMU_FRAME_OVERLAP_PROBE=1: the queue holds what these bytes will be (a pending label with + // no completion tick) until this publication has written them, whenever it runs. + var publish = work; + var landed = probeRange; + work = () => + { + publish(); + _commandStream?.LandPendingLabels(landed.Address, (ulong)landed.Bytes, _memory); + }; + } + if (InlineCompletions && LastWorkSerial <= CompletedSerial && _completions.PendingCount == 0) { Interlocked.Increment(ref _inlineCompletionCount); @@ -2918,6 +2935,20 @@ private void QueueCompletion( var serial = SubmissionSerial; Enqueue(serial); + if (SharpEmu.Libs.Gpu.GpuCommands.FrameOverlapProbe.Enabled) + { + // SHARPEMU_FRAME_OVERLAP_PROBE=1: a record-time-known publication never commits the buffer for + // itself; it rides the next commit (stream coalescing, the frame flush, the worker parking, a poll). + if (probeRange.Bytes > 0) + { + _lazyLabelRanges.Add(probeRange); + } + + _pendingLabelWrites++; + Interlocked.Increment(ref _lazyLabelCompletions); + return; + } + if (lazyLabel is { } open && pending == serial) { // The work before it is in the open buffer, which some commit takes out anyway. diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.cs index 39b1784ee..bba8cfb6f 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.cs @@ -1786,6 +1786,18 @@ public void CopyGuestMemory(ulong destination, ulong source, ulong size, bool al return; } + if (SharpEmu.Libs.Gpu.GpuCommands.FrameOverlapProbe.Enabled && _overlapProbe!.Owes(source, size)) + { + // SHARPEMU_FRAME_OVERLAP_PROBE=1: the source is a publication still queued, so the copy is one + // too, made on the host behind it in stream order. + QueueCompletion(() => + { + CopyGuestBytesOnHost(destination, source, size); + _imageCache.InvalidateMemory(destination, size); + }, probeRange: (destination, (int)Math.Min(size, int.MaxValue))); + return; + } + var target = _guestMemory.ResolveWritable(destination, size); var origin = _guestMemory.Resolve(source, size); // A source too large to stage resolves to a prefix, which a blit of the whole @@ -2873,7 +2885,7 @@ public void ReportCounters() if (SharpEmu.Libs.Gpu.GpuCommands.FrameOverlapProbe.Enabled) { - Console.Error.WriteLine(_overlapProbe!.TakeWindowLine()); + Console.Error.WriteLine(_overlapProbe!.TakeWindowLine() + $" pending_labels={_commandStream?.PendingLabelCount ?? 0}"); } _slowWaitReports = 0; diff --git a/tests/SharpEmu.Libs.Tests/Gpu/GpuCommands/FrameOverlapProbeTests.cs b/tests/SharpEmu.Libs.Tests/Gpu/GpuCommands/FrameOverlapProbeTests.cs index d7666abc2..c675340a5 100644 --- a/tests/SharpEmu.Libs.Tests/Gpu/GpuCommands/FrameOverlapProbeTests.cs +++ b/tests/SharpEmu.Libs.Tests/Gpu/GpuCommands/FrameOverlapProbeTests.cs @@ -252,4 +252,72 @@ public void AParkOnBytesACompletionStillOwesRefusesTheFrame() Assert.Equal("1", Counter(line, "suspended_other")); Assert.Equal("1", Counter(line, "refused_frames")); } + + // The probe's queue side: a pending label noted with no completion tick (the Metal host's tick under + // the probe) answers waits and parse-time reads until its publication lands it, not when a tick passes. + [Fact] + public void AQueuedPublicationAnswersWaitsUntilItLandsNotWhenATickPasses() + { + const ulong label = StreamRunner.LabelAddress; + var host = new RecordingCommandStreamHost { PendingLabelTick = ulong.MaxValue }; + var queue = new CommandStreamQueue(host); + var interpreter = queue.GetInterpreter(0); + interpreter.PendingLabelRecorded!(label, 4, 7); + + // Every submission completes on the GPU: the label is still only queued, and still answers. + queue.NotifyCompletedGpuTick(1_000_000); + Assert.True(interpreter.PendingLabelLookup!(label, false, out var queued)); + Assert.Equal(7UL, queued); + + // Its publication has not written memory yet: landing keeps it. + queue.LandPendingLabels(label, 4, host.Memory); + Assert.Equal(1, queue.PendingLabelCount); + + // Published: memory holds the value, and memory answers from now on. + Assert.True(host.Memory.TryWrite(label, BitConverter.GetBytes(7u))); + queue.LandPendingLabels(label, 4, host.Memory); + Assert.Equal(0, queue.PendingLabelCount); + Assert.False(interpreter.PendingLabelLookup!(label, false, out _)); + } + + [Fact] + public void LandingAnOlderPublicationKeepsTheNewerQueuedValue() + { + const ulong label = StreamRunner.LabelAddress; + var host = new RecordingCommandStreamHost { PendingLabelTick = ulong.MaxValue }; + var queue = new CommandStreamQueue(host); + var interpreter = queue.GetInterpreter(0); + interpreter.PendingLabelRecorded!(label, 8, 1); + interpreter.PendingLabelRecorded!(label, 8, 2); + + // The first publication wrote 1; the stream's newest write (2) is still queued. + Assert.True(host.Memory.TryWrite(label, BitConverter.GetBytes(1UL))); + queue.LandPendingLabels(label, 8, host.Memory); + Assert.True(interpreter.PendingLabelLookup!(label, true, out var newest)); + Assert.Equal(2UL, newest); + + Assert.True(host.Memory.TryWrite(label, BitConverter.GetBytes(2UL))); + queue.LandPendingLabels(label, 8, host.Memory); + Assert.False(interpreter.PendingLabelLookup!(label, true, out _)); + } + + [Fact] + public void ARefusedFramesQueuedBytesStayOwedUntilItsRealCompletion() + { + var host = new ProbeHost(_gpu, _log); + host.Interrupt(1, destination: 0x2000); + host.Probe.Refuse(FrameOverlapRefusal.GdsStore); + host.CommitFrame(); + _gpu.Pump(); + host.Interrupt(2, destination: 0x3000); + host.CommitFrame(); + + // A copy reading 0x2000 two frames on must still be queued behind the refused frame's write. + Assert.True(host.Probe.Owes(0x2000, 4)); + Assert.True(host.Probe.Owes(0x3000, 4)); + _gpu.Signal(1); + Assert.False(host.Probe.Owes(0x2000, 4)); + Assert.False(host.Probe.Owes(0x3000, 4)); + Assert.Equal(["interrupt 1", "interrupt 2"], _log.Entries); + } } From 033de1f81f1ac658a2e2c81eb269c49101f5f696 Mon Sep 17 00:00:00 2001 From: kuba Date: Mon, 16 Nov 2026 08:30:45 +0000 Subject: [PATCH 129/178] [Probe] Frame-overlap probe: a queued copy copies raw guest memory on the completion thread The round-2 copy item called the worker's host-copy path from the completion thread, which can read through the image cache and wait on the worker while the worker waits on completions (the likely hang in probe2-720). Unguarded, measurement only. --- .../Gpu/GpuCommands/FrameOverlapProbe.cs | 5 +++ .../SharpEmu.Gpu.Metal/V2/MetalRenderHost.cs | 33 +++++++++++++++++-- 2 files changed, 36 insertions(+), 2 deletions(-) diff --git a/src/SharpEmu.Libs/Gpu/GpuCommands/FrameOverlapProbe.cs b/src/SharpEmu.Libs/Gpu/GpuCommands/FrameOverlapProbe.cs index 4be9d2a41..c834a1831 100644 --- a/src/SharpEmu.Libs/Gpu/GpuCommands/FrameOverlapProbe.cs +++ b/src/SharpEmu.Libs/Gpu/GpuCommands/FrameOverlapProbe.cs @@ -82,6 +82,7 @@ public sealed class FrameOverlapProbe private readonly List _unfinished = new(); private readonly long _armAt; private long _framesUnarmed; + private long _queuedCopies; private Frame? _lastVisibleFlip; private int _depth; private int _refusalReports; @@ -110,6 +111,9 @@ public FrameOverlapProbe(Action enqueueAtSerial, Func comp _armAt = ArmAfterSeconds > 0 ? _clock() + (long)(ArmAfterSeconds * Stopwatch.Frequency) : long.MinValue; } + /// A copy whose source is a queued publication was queued behind it. + public void NoteQueuedCopy() => Interlocked.Increment(ref _queuedCopies); + /// Whether a publication still queued (not yet run) writes any of these bytes. public bool Owes(ulong address, ulong size) { @@ -381,6 +385,7 @@ public string TakeWindowLine() var line = $"[METAL-V2][OVERLAP-PROBE] frames={_frames} published_early={_framesEarly} " + $"published_at_completion={_framesAtCompletion} refused_frames={_framesRefused} unarmed={_framesUnarmed} " + + $"queued_copies={Interlocked.Exchange(ref _queuedCopies, 0)} " + $"prev_running_at_commit={_framesWaited} items_early={_itemsEarly} " + $"ms_early_p50={Percentile(_earlyMs, 0.5):F1} ms_early_p90={Percentile(_earlyMs, 0.9):F1} " + $"depth_max={_depthMax} flips={_flips} flips_early={_flipsEarly} " + diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.cs index bba8cfb6f..08cf4e99f 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.cs @@ -1789,10 +1789,12 @@ public void CopyGuestMemory(ulong destination, ulong source, ulong size, bool al if (SharpEmu.Libs.Gpu.GpuCommands.FrameOverlapProbe.Enabled && _overlapProbe!.Owes(source, size)) { // SHARPEMU_FRAME_OVERLAP_PROBE=1: the source is a publication still queued, so the copy is one - // too, made on the host behind it in stream order. + // too, made behind it in stream order. It runs on the completion thread, so it copies raw guest + // memory (what the publication before it wrote) and touches nothing the worker owns. + _overlapProbe.NoteQueuedCopy(); QueueCompletion(() => { - CopyGuestBytesOnHost(destination, source, size); + CopyQueuedPublication(destination, source, size); _imageCache.InvalidateMemory(destination, size); }, probeRange: (destination, (int)Math.Min(size, int.MaxValue))); return; @@ -1932,6 +1934,33 @@ private void CopyGuestBytesOnHost(ulong destination, ulong source, ulong size) } } + // SHARPEMU_FRAME_OVERLAP_PROBE=1 only: a copy of a queued publication, from the completion thread. + private void CopyQueuedPublication(ulong destination, ulong source, ulong size) + { + var buffer = System.Buffers.ArrayPool.Shared.Rent((int)Math.Min(size, 64 * 1024)); + try + { + for (var copied = 0UL; copied < size;) + { + var count = (int)Math.Min((ulong)buffer.Length, size - copied); + var span = buffer.AsSpan(0, count); + if (!_memory.TryRead(source + copied, span) || !_memory.TryWrite(destination + copied, span)) + { + MetalV2Diagnostics.WarnOnce("overlap-probe-copy", + $"[OVERLAP-PROBE] a queued copy could not copy guest memory: destination=0x{destination:X16} " + + $"source=0x{source:X16} size=0x{size:X}."); + break; + } + + copied += (ulong)count; + } + } + finally + { + System.Buffers.ArrayPool.Shared.Return(buffer); + } + } + private void CopyGuestBytesOnHostCore(ulong destination, ulong source, ulong size) { var buffer = System.Buffers.ArrayPool.Shared.Rent((int)Math.Min(size, 64 * 1024)); From 440b957d4bb986dbd4ce3566db6e94cc95e64d1f Mon Sep 17 00:00:00 2001 From: kuba Date: Mon, 16 Nov 2026 09:46:36 +0000 Subject: [PATCH 130/178] [Probe] Frame-overlap probe: land publications per command buffer, bounded to one flip outstanding Still SHARPEMU_FRAME_OVERLAP_PROBE=1 only, UNGUARDED and for measurement. Per-frame landing missed the guest's gate: Demon's Souls submits seven buffers right after its flip, after the frame boundary (QENQ kind=3 at flip+0.01 ms), so their labels counted into the next probe frame, which cannot commit before the guest goes on, and landed at real completion behind the whole GPU tail. Publications now land when the buffer carrying them commits, in stream order, once every flip but the newest committed one has really completed (else when that flip completes; counted as held_by_bound). A refused buffer and every buffer after it until it completes publish at their real completion. --- .../Gpu/GpuCommands/FrameOverlapProbe.cs | 313 ++++++++++-------- .../V2/MetalCommandStream.cs | 5 - .../SharpEmu.Gpu.Metal/V2/MetalRenderHost.cs | 6 + .../Gpu/GpuCommands/FrameOverlapProbeTests.cs | 115 ++++--- 4 files changed, 235 insertions(+), 204 deletions(-) diff --git a/src/SharpEmu.Libs/Gpu/GpuCommands/FrameOverlapProbe.cs b/src/SharpEmu.Libs/Gpu/GpuCommands/FrameOverlapProbe.cs index c834a1831..a0326fa23 100644 --- a/src/SharpEmu.Libs/Gpu/GpuCommands/FrameOverlapProbe.cs +++ b/src/SharpEmu.Libs/Gpu/GpuCommands/FrameOverlapProbe.cs @@ -29,14 +29,16 @@ public enum FrameOverlapRefusal /// /// SHARPEMU_FRAME_OVERLAP_PROBE=1: an UNGUARDED measurement probe, default off, never to be -/// shipped. The host-side publications a frame queues for its GPU completion (host-landed -/// labels, end-of-pipe label slots, command-processor writes, end-of-pipe interrupts) are -/// published together, in stream order, once the frame is fully walked and committed and the -/// frame before it has really completed on the GPU, instead of when the frame itself completes. -/// The guest is then at most one frame ahead of the GPU. Nothing protects what the unfinished -/// frame still reads or writes: rendering and guest memory may be corrupted. A frame that queued -/// a publication the probe cannot make early (see ) is -/// published by its real completion, as without the switch. +/// shipped. The host-side publications the stream queues for a GPU completion (host-landed +/// labels, end-of-pipe label slots, command-processor writes, end-of-pipe interrupts, copies of +/// those) land per command buffer: when the buffer that carries them is committed, in stream +/// order, instead of when the GPU completes it. The bound: a buffer's publications land early +/// only once every flip but the newest committed one has really completed on the GPU, so at most +/// one flip's worth of GPU work is outstanding behind what the guest has seen; a buffer held by +/// the bound lands when that flip completes. Nothing protects what unfinished GPU work still reads +/// or writes: rendering and guest memory may be corrupted. A buffer that queued a publication the +/// probe cannot make early (see ), and every buffer after it until +/// it completes, is published by its real completion, as without the switch. /// /// /// The probe only reorders work the host already queues. enqueueAtSerial runs an action @@ -50,12 +52,11 @@ public sealed class FrameOverlapProbe Environment.GetEnvironmentVariable("SHARPEMU_FRAME_OVERLAP_PROBE"), "1", StringComparison.Ordinal); // SHARPEMU_FRAME_OVERLAP_PROBE_WAITS=count: a park on owed bytes is counted (suspended_owed) - // instead of refusing the frame. By the frame's commit the walk is past the wait, so this measures - // what the refusal costs. + // instead of refusing the buffer. public static readonly bool CountOwedWaitsOnly = string.Equals( Environment.GetEnvironmentVariable("SHARPEMU_FRAME_OVERLAP_PROBE_WAITS"), "count", StringComparison.Ordinal); - // SHARPEMU_FRAME_OVERLAP_PROBE_AFTER_S=: frames publish early only that long after the probe + // SHARPEMU_FRAME_OVERLAP_PROBE_AFTER_S=: publications land early only that long after the probe // started (boot and menus publish at real completion); the other probe rules apply from the start. private static readonly double ArmAfterSeconds = double.TryParse(Environment.GetEnvironmentVariable("SHARPEMU_FRAME_OVERLAP_PROBE_AFTER_S"), @@ -76,32 +77,36 @@ public sealed class FrameOverlapProbe private readonly Func _completedSerial; private readonly Func _clock; private readonly object _gate = new(); - private Frame _open = new(0, 1); - private Frame? _committed; - // Committed frames whose real completion has not run yet, oldest first. - private readonly List _unfinished = new(); + private Batch _open = new(0); + // Committed batches whose real completion has not run yet, oldest first. + private readonly List _unfinished = new(); + // Serials of the committed buffers that carried a flip, newest last (the last two are kept). + private ulong _lastFlipSerial; + private ulong _flipBeforeLastSerial; private readonly long _armAt; - private long _framesUnarmed; - private long _queuedCopies; - private Frame? _lastVisibleFlip; - private int _depth; private int _refusalReports; // Window counters, guarded by _gate. - private long _frames; - private long _framesEarly; - private long _framesAtCompletion; - private long _framesRefused; - private long _framesWaited; + private long _commits; + private long _batches; + private long _batchesAtCommit; + private long _batchesHeld; + private long _batchesEarly; + private long _batchesAtCompletion; + private long _batchesRefused; + private long _batchesBehindRefusal; + private long _batchesUnarmed; private long _itemsEarly; - private long _flipsEarly; + private long _itemsHeld; private long _flips; - private int _depthMax; + private long _flipsEarly; private long _suspendedOther; private long _suspendedOwed; + private long _queuedCopies; + private int _flipsOutstandingMax; private readonly long[] _refusals = new long[RefusalCount]; private readonly List _earlyMs = new(); - private readonly List _periodMs = new(); + private readonly List _flipsOutstanding = new(); public FrameOverlapProbe(Action enqueueAtSerial, Func completedSerial, Func? clock = null) { @@ -111,38 +116,8 @@ public FrameOverlapProbe(Action enqueueAtSerial, Func comp _armAt = ArmAfterSeconds > 0 ? _clock() + (long)(ArmAfterSeconds * Stopwatch.Frequency) : long.MinValue; } - /// A copy whose source is a queued publication was queued behind it. - public void NoteQueuedCopy() => Interlocked.Increment(ref _queuedCopies); - - /// Whether a publication still queued (not yet run) writes any of these bytes. - public bool Owes(ulong address, ulong size) - { - lock (_gate) - { - return OwesLocked(address, size); - } - } - - private bool OwesLocked(ulong address, ulong size) - { - if (Owes(_open, address, size)) - { - return true; - } - - foreach (var frame in _unfinished) - { - if (Owes(frame, address, size)) - { - return true; - } - } - - return false; - } - /// - /// A publication the open frame queued for its completion. The result is what the real + /// A publication the open buffer queued for its completion. The result is what the real /// completion runs: the publication unless it already ran early, then /// , which is never published early. /// @@ -163,7 +138,7 @@ public Action Track(Action publish, Action? atRealCompletion = null, ulong addre }; } - /// The open frame carries a flip. + /// The open buffer carries a flip. public void NoteFlip() { lock (_gate) @@ -172,7 +147,10 @@ public void NoteFlip() } } - /// The first serial the open frame's work can carry. + /// A copy whose source is a queued publication was queued behind it. + public void NoteQueuedCopy() => Interlocked.Increment(ref _queuedCopies); + + /// The first serial the open buffer's work can carry. public ulong OpenFrameFirstSerial { get @@ -184,7 +162,34 @@ public ulong OpenFrameFirstSerial } } - /// The open frame queued something the probe cannot publish early. + /// Whether a publication still queued (not yet run) writes any of these bytes. + public bool Owes(ulong address, ulong size) + { + lock (_gate) + { + return OwesLocked(address, size); + } + } + + private bool OwesLocked(ulong address, ulong size) + { + if (Owes(_open, address, size)) + { + return true; + } + + foreach (var batch in _unfinished) + { + if (Owes(batch, address, size)) + { + return true; + } + } + + return false; + } + + /// The open buffer queued something the probe cannot publish early. public void Refuse(FrameOverlapRefusal reason, ulong address = 0) { lock (_gate) @@ -196,15 +201,15 @@ public void Refuse(FrameOverlapRefusal reason, ulong address = 0) { _refusalReports++; Console.Error.WriteLine( - $"[METAL-V2][OVERLAP-PROBE] refused frame={_open.Index} reason={Name(reason)} address=0x{address:X16}; " + - "it publishes at its real completion"); + $"[METAL-V2][OVERLAP-PROBE] refused buffer={_open.Index} reason={Name(reason)} address=0x{address:X16}; " + + "it and the buffers after it publish at their real completion"); } } } /// - /// The command walk parked a submission of the open frame. A wait on bytes a queued, not yet - /// published completion writes is released only by a completion: the frame is refused. + /// The command walk parked a submission. A wait on bytes a queued, not yet published + /// completion writes is released only by a completion: the open buffer is refused. /// public void NoteSuspendedWalk(in CommandWaitCondition wait) { @@ -239,60 +244,86 @@ public void NoteSuspendedWalk(in CommandWaitCondition wait) } /// - /// Everything the open frame recorded is committed; finishes it. - /// Its publications go out once the frame before it has really completed, and the next - /// frame's wait for this one's real completion: the guest is at most one frame ahead. + /// A command buffer was committed with : what the stream queued since + /// the previous commit is carried by it. It lands now if every flip but the newest committed one + /// has completed, else when the flip before the newest completes (or at its own completion). /// - public void OnFrameCommitted(ulong lastSerial) + public void OnCommit(ulong serial) { - Frame frame; - ulong previousLast; + Batch batch; + ulong gate; lock (_gate) { - frame = _open; - frame.LastSerial = Math.Max(lastSerial, frame.FirstSerial - 1); - frame.CommittedAt = _clock(); - previousLast = _committed?.LastSerial ?? 0; - _committed = frame; - _unfinished.Add(frame); - _open = new Frame(frame.Index + 1, frame.LastSerial + 1); - _frames++; - if (previousLast > _completedSerial()) + _commits++; + batch = _open; + _open = new Batch(batch.Index + 1) { FirstSerial = serial + 1 }; + if (batch.Items.Count == 0 && !batch.HasFlip) + { + return; + } + + batch.Serial = serial; + if (batch.HasFlip) + { + _flipBeforeLastSerial = _lastFlipSerial; + _lastFlipSerial = serial; + _flips++; + } + + gate = _flipBeforeLastSerial; + _unfinished.Add(batch); + _batches++; + if (gate > _completedSerial()) { - _framesWaited++; + _batchesHeld++; + _itemsHeld += batch.Items.Count; + } + else + { + _batchesAtCommit++; } } - _enqueueAtSerial(previousLast, () => Publish(frame)); - _enqueueAtSerial(frame.LastSerial, () => Completed(frame)); + _enqueueAtSerial(gate, () => Publish(batch)); + _enqueueAtSerial(serial, () => Completed(batch)); } - // Runs once the frame before it has really completed (completion thread). - private void Publish(Frame frame) + // Runs once the bound allows it (completion thread). + private void Publish(Batch batch) { - if (frame.Refusal is not null) + lock (_gate) { - lock (_gate) + if (batch.Refusal is not null) { - _framesRefused++; + _batchesRefused++; + return; } - return; - } - - if (_clock() < _armAt) - { - lock (_gate) + foreach (var earlier in _unfinished) { - _framesUnarmed++; + if (earlier == batch) + { + break; + } + + if (earlier.Refusal is not null) + { + // Landing now would overtake publications that wait for the GPU. + _batchesBehindRefusal++; + return; + } } - return; + if (_clock() < _armAt) + { + _batchesUnarmed++; + return; + } } - var early = _completedSerial() < frame.LastSerial; + var early = _completedSerial() < batch.Serial; var ran = 0; - foreach (var item in frame.Items) + foreach (var item in batch.Items) { if (item.Run()) { @@ -304,56 +335,49 @@ private void Publish(Frame frame) { if (!early) { - _framesAtCompletion++; + _batchesAtCompletion++; return; } - frame.PublishedEarly = true; - frame.VisibleAt = _clock(); - _framesEarly++; + batch.PublishedEarly = true; + batch.PublishedAt = _clock(); + _batchesEarly++; _itemsEarly += ran; - _flipsEarly += frame.HasFlip ? 1 : 0; - _depth++; - _depthMax = Math.Max(_depthMax, _depth); + _flipsEarly += batch.HasFlip ? 1 : 0; + // The flips committed and not yet completed behind what the guest now sees. + var outstanding = 0; + foreach (var pending in _unfinished) + { + outstanding += pending.HasFlip ? 1 : 0; + } + + _flipsOutstanding.Add(outstanding); + _flipsOutstandingMax = Math.Max(_flipsOutstandingMax, outstanding); } } - // Runs once the frame has really completed (completion thread), after all its items. - private void Completed(Frame frame) + // Runs once the buffer has really completed (completion thread), after all its items. + private void Completed(Batch batch) { var now = _clock(); lock (_gate) { - if (frame.PublishedEarly) + if (batch.PublishedEarly && ran(batch)) { - _depth--; - _earlyMs.Add((now - frame.VisibleAt) * 1000.0 / Stopwatch.Frequency); - } - else - { - frame.VisibleAt = now; - } - - if (frame.HasFlip) - { - _flips++; - if (_lastVisibleFlip is { } previous) - { - _periodMs.Add((frame.VisibleAt - previous.VisibleAt) * 1000.0 / Stopwatch.Frequency); - } - - _lastVisibleFlip = frame; + _earlyMs.Add((now - batch.PublishedAt) * 1000.0 / Stopwatch.Frequency); } // Every item has run: none is owed to a wait any more. - frame.Items.Clear(); - _unfinished.Remove(frame); + batch.Items.Clear(); + _unfinished.Remove(batch); } + + static bool ran(Batch done) => done.Items.Count != 0; } - private static bool Owes(Frame frame, ulong address, ulong size) + private static bool Owes(Batch batch, ulong address, ulong size) { - foreach (var item in frame.Items) + foreach (var item in batch.Items) { if (item.Bytes != 0 && !item.HasRun && address < item.Address + item.Bytes && item.Address < address + size) { @@ -383,20 +407,22 @@ public string TakeWindowLine() var refusals = string.Join(' ', Enumerable.Range(0, RefusalCount).Select(index => $"{Name((FrameOverlapRefusal)index)}={_refusals[index]}")); var line = - $"[METAL-V2][OVERLAP-PROBE] frames={_frames} published_early={_framesEarly} " + - $"published_at_completion={_framesAtCompletion} refused_frames={_framesRefused} unarmed={_framesUnarmed} " + - $"queued_copies={Interlocked.Exchange(ref _queuedCopies, 0)} " + - $"prev_running_at_commit={_framesWaited} items_early={_itemsEarly} " + + $"[METAL-V2][OVERLAP-PROBE] commits={_commits} batches={_batches} at_commit={_batchesAtCommit} " + + $"held_by_bound={_batchesHeld} items_held={_itemsHeld} published_early={_batchesEarly} " + + $"published_at_completion={_batchesAtCompletion} refused={_batchesRefused} " + + $"behind_refusal={_batchesBehindRefusal} unarmed={_batchesUnarmed} items_early={_itemsEarly} " + $"ms_early_p50={Percentile(_earlyMs, 0.5):F1} ms_early_p90={Percentile(_earlyMs, 0.9):F1} " + - $"depth_max={_depthMax} flips={_flips} flips_early={_flipsEarly} " + - $"flip_period_p50={Percentile(_periodMs, 0.5):F1} flip_period_p90={Percentile(_periodMs, 0.9):F1} " + + $"flips={_flips} flips_early={_flipsEarly} " + + $"flips_outstanding_p50={Percentile(_flipsOutstanding, 0.5):F0} flips_outstanding_max={_flipsOutstandingMax} " + + $"queued_copies={Interlocked.Exchange(ref _queuedCopies, 0)} " + $"suspended_other={_suspendedOther} suspended_owed={_suspendedOwed} refusals: {refusals}"; - _frames = _framesEarly = _framesAtCompletion = _framesRefused = _framesWaited = _framesUnarmed = 0; - _itemsEarly = _flipsEarly = _flips = _suspendedOther = _suspendedOwed = 0; - _depthMax = _depth; + _commits = _batches = _batchesAtCommit = _batchesHeld = _batchesEarly = _batchesAtCompletion = 0; + _batchesRefused = _batchesBehindRefusal = _batchesUnarmed = _itemsEarly = _itemsHeld = 0; + _flips = _flipsEarly = _suspendedOther = _suspendedOwed = 0; + _flipsOutstandingMax = 0; Array.Clear(_refusals); _earlyMs.Clear(); - _periodMs.Clear(); + _flipsOutstanding.Clear(); return line; } } @@ -412,17 +438,16 @@ private static double Percentile(List values, double fraction) return values[Math.Min(values.Count - 1, (int)(fraction * values.Count))]; } - private sealed class Frame(long index, ulong firstSerial) + private sealed class Batch(long index) { public long Index { get; } = index; - public ulong FirstSerial { get; } = firstSerial; - public ulong LastSerial { get; set; } + public ulong FirstSerial { get; init; } = 1; + public ulong Serial { get; set; } public List Items { get; } = new(); public FrameOverlapRefusal? Refusal { get; set; } public bool HasFlip { get; set; } public bool PublishedEarly { get; set; } - public long CommittedAt { get; set; } - public long VisibleAt { get; set; } + public long PublishedAt { get; set; } } private sealed class Item(Action publish, ulong address, ulong bytes) diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalCommandStream.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalCommandStream.cs index 81a757340..45aa93e8d 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalCommandStream.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalCommandStream.cs @@ -128,11 +128,6 @@ void ICommandStreamHost.FlushFrame() SharpEmu.HLE.GpuMemory.FrameOverlapDiagnostic.OnFrameCommitted(Volatile.Read(ref _submittedSerial)); } - if (SharpEmu.Libs.Gpu.GpuCommands.FrameOverlapProbe.Enabled) - { - // SHARPEMU_FRAME_OVERLAP_PROBE=1 (unguarded): the frame's publications may go out early. - _overlapProbe!.OnFrameCommitted(Volatile.Read(ref _submittedSerial)); - } } // ---- command-buffer coalescing (SHARPEMU_METAL_V2_FLUSH_COALESCE) ---- diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.cs index 08cf4e99f..7948ee367 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.cs @@ -755,6 +755,12 @@ private ulong FlushCommandBuffer(PassEndCause cause, MetalFlushCause why) _lazyLabelRanges.Clear(); Interlocked.Increment(ref _flushes); _completions.Publish(serial); + if (SharpEmu.Libs.Gpu.GpuCommands.FrameOverlapProbe.Enabled) + { + // SHARPEMU_FRAME_OVERLAP_PROBE=1 (unguarded): what this buffer carries may land now. + _overlapProbe!.OnCommit(serial); + } + return serial; } diff --git a/tests/SharpEmu.Libs.Tests/Gpu/GpuCommands/FrameOverlapProbeTests.cs b/tests/SharpEmu.Libs.Tests/Gpu/GpuCommands/FrameOverlapProbeTests.cs index c675340a5..1d3452ac8 100644 --- a/tests/SharpEmu.Libs.Tests/Gpu/GpuCommands/FrameOverlapProbeTests.cs +++ b/tests/SharpEmu.Libs.Tests/Gpu/GpuCommands/FrameOverlapProbeTests.cs @@ -10,9 +10,10 @@ namespace SharpEmu.Libs.Tests.Gpu.GpuCommands; /// /// SHARPEMU_FRAME_OVERLAP_PROBE's publication rules on the managed host, with a fake GPU timeline -/// standing in for the Metal completion queue: a frame publishes at its commit once the frame -/// before it really completed, in stream order behind anything older; never two frames ahead; -/// a refused frame waits for its real completion; real-completion-only work never runs early. +/// standing in for the Metal completion queue: a buffer's publications land at its commit, in +/// stream order, while no flip but the newest committed one is still on the GPU; the bound holds +/// the rest until that flip completes; a refused buffer and everything behind it wait for their +/// real completion; real-completion-only work never runs early. /// public sealed class FrameOverlapProbeTests { @@ -117,13 +118,13 @@ public void RecordFlip(ulong requestId, int eventId) public void Interrupt(int eventId, ulong destination = 0) => RecordEndOfPipe(new EndOfPipeWrite(EndOfPipeWriteKind.InterruptOnly, 0, Destination: destination, EventId: eventId)); - public override void Flush() => OpenSerial++; + public override void Flush() => Commit(); - // FlushFrame: the frame's last buffer is committed with the open serial. - public void CommitFrame() + // A command buffer is committed with the open serial. + public void Commit() { - var last = OpenSerial++; - Probe.OnFrameCommitted(last); + var serial = OpenSerial++; + Probe.OnCommit(serial); } } @@ -140,75 +141,80 @@ private static string Counter(string line, string name) } [Fact] - public void AFramePublishesAtItsCommitOnceThePreviousFrameIsDone() + public void ABufferLandsAtItsCommitWhileNoEarlierFlipIsOutstanding() { var host = new ProbeHost(_gpu, _log); host.Interrupt(1); - host.Flush(); - host.Interrupt(2); - host.CommitFrame(); + host.Commit(); _gpu.Pump(); + Assert.Equal(["interrupt 1"], _log.Entries); + host.Interrupt(2); + host.Commit(); + _gpu.Pump(); Assert.Equal(["interrupt 1", "interrupt 2"], _log.Entries); - // The real completion finds them published and does not publish them again. + // The real completions find them published and do not publish them again. _gpu.Signal(2); Assert.Equal(["interrupt 1", "interrupt 2"], _log.Entries); var line = host.Probe.TakeWindowLine(); - Assert.Equal("1", Counter(line, "published_early")); - Assert.Equal("2", Counter(line, "items_early")); - Assert.Equal("1", Counter(line, "depth_max")); + Assert.Equal("2", Counter(line, "at_commit")); + Assert.Equal("2", Counter(line, "published_early")); + Assert.Equal("0", Counter(line, "held_by_bound")); } [Fact] - public void TheNextFrameWaitsForThePublishedFrameToReallyComplete() + public void TheBoundHoldsWorkWhileTheFlipBeforeTheNewestIsStillOnTheGpu() { var host = new ProbeHost(_gpu, _log); + host.RecordFlip(requestId: 7, eventId: 10); + host.Commit(); // serial 1: flip 1 host.Interrupt(1); - host.CommitFrame(); + host.Commit(); // serial 2: after flip 1, nothing older outstanding _gpu.Pump(); + Assert.Equal(["interrupt 10", "interrupt 1"], _log.Entries); + + host.RecordFlip(requestId: 8, eventId: 11); + host.Commit(); // serial 3: flip 2, while flip 1 still runs host.Interrupt(2); - host.CommitFrame(); + host.Commit(); // serial 4: after flip 2 _gpu.Pump(); - // Frame 0 is published and still on the GPU: frame 1 is not published, the guest is one ahead. - Assert.Equal(["interrupt 1"], _log.Entries); + // Flip 1 is still on the GPU: what follows flip 2 waits for it. + Assert.Equal(["interrupt 10", "interrupt 1"], _log.Entries); - // Frame 0 completes after frame 1's commit: frame 1 publishes at that completion, still early. + // Flip 1 completes: its own real-completion work, then the held buffers in stream order. _gpu.Signal(1); - Assert.Equal(["interrupt 1", "interrupt 2"], _log.Entries); + Assert.Equal(["interrupt 10", "interrupt 1", "flip 7", "interrupt 11", "interrupt 2"], _log.Entries); var line = host.Probe.TakeWindowLine(); - Assert.Equal("2", Counter(line, "published_early")); - Assert.Equal("1", Counter(line, "prev_running_at_commit")); - Assert.Equal("1", Counter(line, "depth_max")); + Assert.Equal("2", Counter(line, "held_by_bound")); + Assert.Equal("4", Counter(line, "published_early")); + Assert.Equal("1", Counter(line, "flips_outstanding_max")); - _gpu.Signal(2); - Assert.Equal(["interrupt 1", "interrupt 2"], _log.Entries); + _gpu.Signal(4); + Assert.Equal(["interrupt 10", "interrupt 1", "flip 7", "interrupt 11", "interrupt 2", "flip 8"], _log.Entries); } [Fact] - public void ARefusedFramePublishesAtItsRealCompletionAndStreamOrderHolds() + public void ARefusedBufferAndTheBuffersBehindItPublishAtTheirRealCompletionInStreamOrder() { var host = new ProbeHost(_gpu, _log); host.Interrupt(1); host.Probe.Refuse(FrameOverlapRefusal.GdsStore, 0x1000); host.Interrupt(2); - host.CommitFrame(); - _gpu.Pump(); - Assert.Empty(_log.Entries); - + host.Commit(); host.Interrupt(3); - host.Interrupt(4); - host.CommitFrame(); + host.Commit(); _gpu.Pump(); Assert.Empty(_log.Entries); - // Frame 0 completes: its own completions run, then frame 1 publishes behind them. _gpu.Signal(1); - Assert.Equal(["interrupt 1", "interrupt 2", "interrupt 3", "interrupt 4"], _log.Entries); + Assert.Equal(["interrupt 1", "interrupt 2"], _log.Entries); + _gpu.Signal(2); + Assert.Equal(["interrupt 1", "interrupt 2", "interrupt 3"], _log.Entries); var line = host.Probe.TakeWindowLine(); - Assert.Equal("1", Counter(line, "refused_frames")); - Assert.Equal("1", Counter(line, "published_early")); + Assert.Equal("1", Counter(line, "refused")); + Assert.Equal("1", Counter(line, "behind_refusal")); Assert.Equal("1", Counter(line, "gds_store")); } @@ -218,10 +224,10 @@ public void RealCompletionWorkNeverRunsEarly() var host = new ProbeHost(_gpu, _log); host.Interrupt(1); host.RecordFlip(requestId: 7, eventId: 2); - host.CommitFrame(); + host.Commit(); _gpu.Pump(); - // The flip's interrupt goes out with the frame; the flip's GPU completion does not. + // The flip's interrupt goes out with the buffer; the flip's GPU completion does not. Assert.Equal(["interrupt 1", "interrupt 2"], _log.Entries); _gpu.Signal(1); Assert.Equal(["interrupt 1", "interrupt 2", "flip 7"], _log.Entries); @@ -230,27 +236,24 @@ public void RealCompletionWorkNeverRunsEarly() } [Fact] - public void AParkOnBytesACompletionStillOwesRefusesTheFrame() + public void AParkOnBytesACompletionStillOwesRefusesTheOpenBuffer() { var host = new ProbeHost(_gpu, _log); host.Interrupt(1, destination: 0x2000); + host.Commit(); + host.Interrupt(2, destination: 0x2100); + host.Probe.NoteSuspendedWalk(CommandWaitCondition.Memory(0x2000, 4)); host.Probe.NoteSuspendedWalk(CommandWaitCondition.Memory(0x3000, 4)); - host.CommitFrame(); + host.Commit(); _gpu.Pump(); Assert.Equal(["interrupt 1"], _log.Entries); - host.Interrupt(2, destination: 0x2100); - host.Probe.NoteSuspendedWalk(CommandWaitCondition.Memory(0x2100, 4)); - host.CommitFrame(); - _gpu.Signal(1); - Assert.Empty(_log.Entries.Skip(1)); - _gpu.Signal(2); Assert.Equal(["interrupt 1", "interrupt 2"], _log.Entries); var line = host.Probe.TakeWindowLine(); Assert.Equal("1", Counter(line, "suspended_walk")); Assert.Equal("1", Counter(line, "suspended_other")); - Assert.Equal("1", Counter(line, "refused_frames")); + Assert.Equal("1", Counter(line, "refused")); } // The probe's queue side: a pending label noted with no completion tick (the Metal host's tick under @@ -302,21 +305,23 @@ public void LandingAnOlderPublicationKeepsTheNewerQueuedValue() } [Fact] - public void ARefusedFramesQueuedBytesStayOwedUntilItsRealCompletion() + public void QueuedBytesStayOwedUntilTheyArePublished() { var host = new ProbeHost(_gpu, _log); host.Interrupt(1, destination: 0x2000); host.Probe.Refuse(FrameOverlapRefusal.GdsStore); - host.CommitFrame(); - _gpu.Pump(); + host.Commit(); host.Interrupt(2, destination: 0x3000); - host.CommitFrame(); + host.Commit(); + _gpu.Pump(); - // A copy reading 0x2000 two frames on must still be queued behind the refused frame's write. + // A copy reading either range must still be queued behind the write. Assert.True(host.Probe.Owes(0x2000, 4)); Assert.True(host.Probe.Owes(0x3000, 4)); _gpu.Signal(1); Assert.False(host.Probe.Owes(0x2000, 4)); + Assert.True(host.Probe.Owes(0x3000, 4)); + _gpu.Signal(2); Assert.False(host.Probe.Owes(0x3000, 4)); Assert.Equal(["interrupt 1", "interrupt 2"], _log.Entries); } From 3d7eab18fb516c2f4c43c5a73cb6567e9252dc4c Mon Sep 17 00:00:00 2001 From: kuba Date: Mon, 16 Nov 2026 10:12:02 +0000 Subject: [PATCH 131/178] [Diag] Frame-overlap: in-flight mode, what the guest touches while released GPU work still runs SHARPEMU_DIAG_FRAME_OVERLAP=1 SHARPEMU_DIAG_FRAME_OVERLAP_ARM=inflight, with SHARPEMU_FRAME_OVERLAP_PROBE=1 (diagnostic only; off, every hook is the existing static readonly check and the tag scopes are empty structs). Each command buffer's in-place reads and GPU writes are recorded under its serial, tagged vertex/index/indirect/constant/storage/texture/device-address/occlusion/lod-stats. On every Kth frame (SHARPEMU_DIAG_FRAME_OVERLAP_EVERY, default 4), from its gate (the first publication at or past its present commit + 2) to the next frame's gate, each probe publication first arms the buffers it releases that the GPU has not completed: read pages get a write watch, written pages a read watch, and the command buffers of submissions admitted and not yet walked a write watch. A page is let go when the last buffer that armed it completes (or its submission is walked), or at its first fault, which is attributed by byte: a store into a read range (1a, by tag and by the reader's place against the present: thirds of the frame's buffers, present+1..+4, next frame), a store into a command buffer not yet walked (1b), a store into a written range, or a load of a written range (2, by origin, tag and writer's place). Times are from the gate. One [METAL-V2][OVERLAP-INFLIGHT] line per stats window, and up to 80 [METAL-V2][OVERLAP-INFLIGHT-HIT] lines a run. --- .../GpuMemory/FrameOverlapDiagnostic.cs | 123 ++- .../GpuMemory/InFlightOverlapTracker.cs | 825 ++++++++++++++++++ .../Gpu/GpuCommands/CommandStreamQueue.cs | 6 + .../Gpu/GpuCommands/FrameOverlapProbe.cs | 12 + .../Gpu/Rendering/RenderRecorder.cs | 26 +- .../V2/MetalRenderHost.Descriptors.cs | 4 + .../V2/MetalRenderHost.LodStatistics.cs | 5 +- .../V2/MetalRenderHost.Occlusion.cs | 1 + .../V2/MetalRenderHost.ThreadDispatch.cs | 1 + .../HLE/InFlightOverlapTrackerTests.cs | 214 +++++ 10 files changed, 1203 insertions(+), 14 deletions(-) create mode 100644 src/SharpEmu.HLE/GpuMemory/InFlightOverlapTracker.cs create mode 100644 tests/SharpEmu.Libs.Tests/HLE/InFlightOverlapTrackerTests.cs diff --git a/src/SharpEmu.HLE/GpuMemory/FrameOverlapDiagnostic.cs b/src/SharpEmu.HLE/GpuMemory/FrameOverlapDiagnostic.cs index e59cf57dc..639c6cb76 100644 --- a/src/SharpEmu.HLE/GpuMemory/FrameOverlapDiagnostic.cs +++ b/src/SharpEmu.HLE/GpuMemory/FrameOverlapDiagnostic.cs @@ -109,7 +109,54 @@ public static class FrameOverlapDiagnostic public static readonly bool ArmReads = Environment.GetEnvironmentVariable("SHARPEMU_DIAG_FRAME_OVERLAP_READS") != "0"; + /// + /// SHARPEMU_DIAG_FRAME_OVERLAP_ARM=inflight (with SHARPEMU_FRAME_OVERLAP_PROBE=1): instead of the per-frame + /// trap, watch what the guest touches while buffers the probe has already published still run on the GPU + /// (). Page cap default 262144 (1 GiB) unless MAX_PAGES says otherwise. + /// + public static readonly bool ArmInFlight = + Environment.GetEnvironmentVariable("SHARPEMU_DIAG_FRAME_OVERLAP_ARM") == "inflight"; + private static FrameOverlapTracker? _tracker; + private static InFlightOverlapTracker? _inflight; + + public static InFlightOverlapTracker? InFlight => Volatile.Read(ref _inflight); + + [ThreadStatic] + private static OverlapTag t_tag; + + /// While alive, in-place reads and GPU writes noted on this thread carry (in-flight mode). + public static TagScope Tag(OverlapTag tag) + { + if (!Enabled) + { + return default; + } + + var previous = t_tag; + t_tag = tag; + return new TagScope(previous, true); + } + + public readonly struct TagScope(OverlapTag previous, bool active) : IDisposable + { + public void Dispose() + { + if (active) + { + t_tag = previous; + } + } + } + + /// The worker committed a command buffer (: it holds a flip). + public static void OnProbeCommit(ulong serial, bool present) => InFlight?.OnCommit(serial, present); + + /// The probe is about to publish everything up to to the guest. + public static void OnProbeRelease(ulong serial) => InFlight?.OnRelease(serial); + + /// The command stream walked a submission to its end. + public static void OnSubmissionWalked(ulong address, ulong bytes) => InFlight?.OnSubmissionWalked(address, bytes); /// /// The guest process of the two-process split: its read faults go to the GPU process, which @@ -127,6 +174,23 @@ public static void Attach(PageGuard? guard, bool readWatchesShared) return; } + if (ArmInFlight) + { + var reads = ArmReads && !readWatchesShared; + var cap = Environment.GetEnvironmentVariable("SHARPEMU_DIAG_FRAME_OVERLAP_MAX_PAGES") is null ? 262144 : MaxArmedPages; + Volatile.Write(ref _inflight, guard is null + ? null + : new InFlightOverlapTracker(new PageGuardOverlapWatches(guard), Stopwatch.GetTimestamp, SampleEvery, cap, reads)); + if (guard is not null) + { + Console.Error.WriteLine( + $"[METAL-V2][OVERLAP-INFLIGHT] on: every={SampleEvery} max_pages={cap} read_watches={(reads ? 1 : 0)}" + + (ArmReads && readWatchesShared ? " (off: single-copy holds the read-watch bit)" : string.Empty)); + } + + return; + } + var previous = Interlocked.Exchange(ref _tracker, guard is null ? null : new FrameOverlapTracker(new PageGuardOverlapWatches(guard), Stopwatch.GetTimestamp, SampleEvery, MaxArmedPages, @@ -141,10 +205,38 @@ public static void Attach(PageGuard? guard, bool readWatchesShared) } } - public static void MarkGpuRead(ulong address, ulong size, OverlapRead kind, ulong program = 0) => Tracker?.MarkRead(address, size, kind, program); + public static void MarkGpuRead(ulong address, ulong size, OverlapRead kind, ulong program = 0) + { + if (InFlight is { } inflight) + { + // Staged bytes were copied at record time: the guest may rewrite them at once. + if (kind != OverlapRead.Staged) + { + inflight.MarkRead(address, size, kind switch + { + OverlapRead.Upload => OverlapTag.Texture, + OverlapRead.DeviceAddress => OverlapTag.DeviceAddress, + _ => t_tag, + }); + } + + return; + } - public static void NoteGpuWrite(ulong address, ulong size, OverlapWrite origin) => - Tracker?.NoteWrite(address, size, origin, origin is OverlapWrite.Storage or OverlapWrite.Binding or OverlapWrite.DeviceAddress ? TakeWriter() : 0); + Tracker?.MarkRead(address, size, kind, program); + } + + public static void NoteGpuWrite(ulong address, ulong size, OverlapWrite origin) + { + var writer = origin is OverlapWrite.Storage or OverlapWrite.Binding or OverlapWrite.DeviceAddress ? TakeWriter() : 0; + if (InFlight is { } inflight) + { + inflight.NoteWrite(address, size, origin, t_tag, writer); + return; + } + + Tracker?.NoteWrite(address, size, origin, writer); + } [ThreadStatic] private static ulong t_writer; @@ -166,7 +258,11 @@ private static ulong TakeWriter() public static void NoteEndOfPipeAtomicAdd(ulong address) => Tracker?.NoteAtomicAdd(address); - public static void OnAdmission(ulong address, ulong bytes) => Tracker?.OnAdmission(address, bytes); + public static void OnAdmission(ulong address, ulong bytes) + { + InFlight?.OnAdmission(address, bytes); + Tracker?.OnAdmission(address, bytes); + } public static void OnBoundaryAdmitted(int unfinished, int blocked) => Tracker?.OnBoundaryAdmitted(unfinished, blocked); @@ -174,9 +270,17 @@ private static ulong TakeWriter() public static void OnFrameCommitted(ulong lastSerial) => Tracker?.OnFrameCommitted(lastSerial); - public static void OnCompleted(ulong serial) => Tracker?.OnCompleted(serial); + public static void OnCompleted(ulong serial) + { + InFlight?.OnCompleted(serial); + Tracker?.OnCompleted(serial); + } - public static void NoteManagedWrite(ulong address, ulong size) => Tracker?.NoteManagedWrite(address, size); + public static void NoteManagedWrite(ulong address, ulong size) + { + InFlight?.NoteManagedWrite(address, size); + Tracker?.NoteManagedWrite(address, size); + } /// /// A fault on a page the diagnostic armed: counted and released. @@ -185,10 +289,15 @@ private static ulong TakeWriter() public static bool TryHandleFault(FaultKind kind, ulong address, out bool stillBlocked) { stillBlocked = false; + if (InFlight is { } inflight) + { + return inflight.TryHandleFault(kind, address, out stillBlocked); + } + return Tracker is { } tracker && tracker.TryHandleFault(kind, address, out stillBlocked); } - public static string? TakeWindowLine() => Tracker?.TakeWindowLine(); + public static string? TakeWindowLine() => InFlight?.TakeWindowLine() ?? Tracker?.TakeWindowLine(); } /// The guest pages of one frame, one bit per 4 KiB page in 4 MiB blocks. diff --git a/src/SharpEmu.HLE/GpuMemory/InFlightOverlapTracker.cs b/src/SharpEmu.HLE/GpuMemory/InFlightOverlapTracker.cs new file mode 100644 index 000000000..923432f6f --- /dev/null +++ b/src/SharpEmu.HLE/GpuMemory/InFlightOverlapTracker.cs @@ -0,0 +1,825 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using System.Diagnostics; +using System.Globalization; +using System.Text; + +namespace SharpEmu.HLE.GpuMemory; + +/// What a guest range a command buffer reads or writes is used as (attribution only). +public enum OverlapTag : byte +{ + Other, + Vertex, + Index, + Indirect, + Constant, + StorageRead, + StorageWritten, + Texture, + DeviceAddress, + Occlusion, + LodStatistics, +} + +/// +/// SHARPEMU_DIAG_FRAME_OVERLAP_ARM=inflight with SHARPEMU_FRAME_OVERLAP_PROBE=1 (diagnostic only): what the +/// guest touches while GPU work it has already been told is finished still runs. Each command buffer's +/// in-place reads and GPU writes are recorded under its serial. On a sampled frame, from the release of its +/// gate (the first publication at or past its present commit + 2) to the next frame's gate, every release +/// arms the buffers it covers that the GPU has not completed: their read pages get a write watch, their +/// written pages a read watch. A page is let go when the last buffer that armed it completes, or at its +/// first fault, which is attributed byte by byte: a store into a read range (the GPU may still read it), a +/// store into a written range, a load of a written range (the GPU has not produced it), or a store into the +/// command buffer of a submission admitted and not yet walked. Times are from the frame's gate. +/// +public sealed class InFlightOverlapTracker +{ + internal const ulong HugeRangeBytes = 256UL << 20; + private const ulong PageBytes = TrackerLayout.PageBytes; + private const int MaxRefsPerPage = 32; + private const int MaxRetriesPerPage = 256; + private const int OriginCount = (int)OverlapWrite.EopGpuValued + 1; + private const int TagCount = (int)OverlapTag.LodStatistics + 1; + private const int HitLines = 80; + + internal static readonly string[] TagNames = + ["other", "vertex", "index", "indirect", "constant", "storage_read", "storage_written", "texture", "device_address", "occlusion", "lod_stats"]; + + private static readonly string[] OriginNames = + ["storage", "binding", "device_address", "fill", "copy", "writeback", "eop_label", "unbounded", "cp_write", "eop_dest", "eop_gpu_valued"]; + + /// Where a buffer sits relative to the sampled frame's present commit. + internal static readonly string[] EraNames = ["older", "f_first", "f_second", "f_last", "p+1", "p+2", "p+3", "p+4", "next"]; + + internal sealed class Record + { + public ulong Serial; + public bool Armed; + public readonly List<(ulong Address, ulong Size, OverlapTag Tag)> Reads = new(); + public readonly List<(ulong Address, ulong Size, int Origin, OverlapTag Tag, ulong Program)> Writes = new(); + public readonly List OwnedPages = new(); + } + + private sealed class PageState + { + public Window? Window; + public ulong MaxSerial; + public bool InRead, InWrite, Faulted, WriteWatched, ReadWatched, RefsCapped; + public readonly List<(Record Record, int Index, bool Write)> Refs = new(2); + public List<(ulong Address, ulong Bytes)>? CommandBuffers; + } + + internal sealed class Window + { + public long Index; + public ulong PresentSerial, PreviousPresentSerial, GateSerial, MaxArmedSerial; + public long GateTicks, ArmTicks, FinalizedTicks; + public bool Closed; + public int ArmedPages, ReadArmedPages, CapSkipped, SkippedReadWatched, RecordsArmed, HugeRanges, RefsCapped, CommandBufferPages, Managed; + public int RsHit, RsNeighbour, WsStoreHit, WsStoreNeighbour, WsLoadHit, WsLoadNeighbour, CbHit, CbNeighbour; + public readonly long[] RsHitByTag = new long[TagCount]; + public readonly long[] RsHitByEra = new long[EraNames.Length]; + public readonly long[] WsLoadByOrigin = new long[OriginCount]; + public readonly long[] WsLoadByTag = new long[TagCount]; + public readonly long[] WsLoadByEra = new long[EraNames.Length]; + public readonly long[] WsStoreByOrigin = new long[OriginCount]; + public readonly HashSet<(ulong, ulong)> RsHitRanges = new(); + public readonly HashSet<(ulong, ulong)> RsPageRanges = new(); + public readonly HashSet<(ulong, ulong)> WsLoadRanges = new(); + public readonly List RsHitMs = new(), WsLoadMs = new(), CbMs = new(); + } + + private readonly IFrameOverlapWatches _watches; + private readonly Func _clock; + private readonly int _sampleEvery; + private readonly int _maxArmedPages; + private readonly bool _armReads; + private readonly object _gate = new(); + + private Record _open = new(); + private readonly List _inFlight = new(); + private ulong _completedSerial; + private long _frames; + private ulong _lastPresent, _presentBefore; + private ulong _gateOpenedFor; + private Window? _arming; + private readonly List _windows = new(); + private readonly Dictionary _pages = new(); + private readonly Dictionary _retries = new(); + private readonly List<(ulong Address, ulong Bytes)> _admitted = new(); + private volatile bool _anyPages; + private int _hitLines; + private long _lateFaults; + + // Finalized windows since the last stats line. + private readonly List _done = new(); + + public InFlightOverlapTracker(IFrameOverlapWatches watches, Func clock, int sampleEvery, int maxArmedPages, bool armReads) + { + _watches = watches; + _clock = clock; + _sampleEvery = Math.Max(1, sampleEvery); + _maxArmedPages = Math.Max(1, maxArmedPages); + _armReads = armReads; + } + + // ---- recording (worker) --------------------------------------------------------------- + + public void MarkRead(ulong address, ulong size, OverlapTag tag) + { + if (size == 0 || size > ulong.MaxValue - address) + { + return; + } + + lock (_gate) + { + _open.Reads.Add((address, size, tag)); + } + } + + public void NoteWrite(ulong address, ulong size, OverlapWrite origin, OverlapTag tag, ulong program) + { + if (origin == OverlapWrite.Unbounded || size == 0 || size > ulong.MaxValue - address) + { + return; + } + + lock (_gate) + { + _open.Writes.Add((address, size, (int)origin, tag, program)); + } + } + + /// The worker committed : what was recorded since the last commit is its buffer. + public void OnCommit(ulong serial, bool present) + { + lock (_gate) + { + var record = _open; + _open = new Record(); + record.Serial = serial; + if (serial > _completedSerial && (record.Reads.Count != 0 || record.Writes.Count != 0)) + { + _inFlight.Add(record); + } + + if (present) + { + _presentBefore = _lastPresent; + _lastPresent = serial; + _frames++; + } + } + } + + // ---- admission (command stream) ------------------------------------------------------- + + public void OnAdmission(ulong address, ulong bytes) + { + if (bytes == 0) + { + return; + } + + lock (_gate) + { + _admitted.Add((address, bytes)); + if (_arming is { } window) + { + ArmCommandBufferLocked(window, address, bytes); + } + } + } + + public void OnSubmissionWalked(ulong address, ulong bytes) + { + lock (_gate) + { + var index = _admitted.IndexOf((address, bytes)); + if (index >= 0) + { + _admitted.RemoveAt(index); + } + + var masks = new Dictionary<(ulong, bool), PageMask>(); + for (var page = address & ~(PageBytes - 1); page < address + bytes; page += PageBytes) + { + if (_pages.TryGetValue(page, out var state) && state.CommandBuffers is { } buffers) + { + buffers.Remove((address, bytes)); + if (buffers.Count == 0) + { + state.CommandBuffers = null; + if (state.MaxSerial <= _completedSerial) + { + Unwatch(page, state, masks); + } + } + } + } + + Apply(masks, add: false); + } + } + + // ---- release and completion (completion thread) ---------------------------------------- + + /// + /// The probe is about to let the guest see everything up to . Runs before + /// the publication, so the watches are in place before the guest can act on it. + /// + public void OnRelease(ulong serial) + { + var started = _clock(); + lock (_gate) + { + if (_lastPresent != 0 && _gateOpenedFor != _lastPresent && serial >= _lastPresent + 2) + { + // This frame's gate: the window of the previous sampled frame stops taking buffers. + _gateOpenedFor = _lastPresent; + if (_arming is { } previous) + { + previous.Closed = true; + _arming = null; + FinalizeIfDoneLocked(); + } + + if (_frames % _sampleEvery == 0) + { + var window = new Window + { + Index = _frames, + PresentSerial = _lastPresent, + PreviousPresentSerial = _presentBefore, + GateSerial = serial, + GateTicks = started, + }; + _arming = window; + _windows.Add(window); + foreach (var (address, bytes) in _admitted) + { + ArmCommandBufferLocked(window, address, bytes); + } + } + } + + if (_arming is not { } arming) + { + return; + } + + var masks = new Dictionary<(ulong, bool), PageMask>(); + foreach (var record in _inFlight) + { + if (record.Armed || record.Serial > serial || record.Serial <= _completedSerial) + { + continue; + } + + ArmRecordLocked(arming, record, masks); + } + + Apply(masks, add: true); + arming.ArmTicks += _clock() - started; + } + } + + public void OnCompleted(ulong serial) + { + lock (_gate) + { + if (serial <= _completedSerial) + { + return; + } + + _completedSerial = serial; + var masks = new Dictionary<(ulong, bool), PageMask>(); + for (var index = 0; index < _inFlight.Count;) + { + var record = _inFlight[index]; + if (record.Serial > serial) + { + index++; + continue; + } + + _inFlight.RemoveAt(index); + foreach (var page in record.OwnedPages) + { + if (_pages.TryGetValue(page, out var state) && state.MaxSerial == record.Serial && state.CommandBuffers is null) + { + Unwatch(page, state, masks); + } + } + } + + Apply(masks, add: false); + FinalizeIfDoneLocked(); + } + } + + // ---- arming ------------------------------------------------------------------------------- + + private void ArmRecordLocked(Window window, Record record, Dictionary<(ulong, bool), PageMask> masks) + { + record.Armed = true; + window.RecordsArmed++; + window.MaxArmedSerial = Math.Max(window.MaxArmedSerial, record.Serial); + for (var index = 0; index < record.Reads.Count; index++) + { + var read = record.Reads[index]; + AddRange(window, record, index, read.Address, read.Size, write: false, masks); + } + + for (var index = 0; index < record.Writes.Count; index++) + { + var write = record.Writes[index]; + AddRange(window, record, index, write.Address, write.Size, write: true, masks); + } + } + + private void AddRange(Window window, Record record, int index, ulong address, ulong size, bool write, Dictionary<(ulong, bool), PageMask> masks) + { + if (size > HugeRangeBytes) + { + window.HugeRanges++; + return; + } + + var end = address + size; + for (var page = address & ~(PageBytes - 1); page < end; page += PageBytes) + { + if (!_pages.TryGetValue(page, out var state)) + { + if (window.ArmedPages >= _maxArmedPages) + { + window.CapSkipped++; + continue; + } + + state = new PageState(); + _pages[page] = state; + _anyPages = true; + } + + if (!ReferenceEquals(state.Window, window)) + { + state.Window = window; + state.Faulted = false; + state.Refs.Clear(); + state.RefsCapped = false; + state.InRead = state.InWrite = false; + } + + if (state.Refs.Count < MaxRefsPerPage) + { + state.Refs.Add((record, index, write)); + } + else if (!state.RefsCapped) + { + state.RefsCapped = true; + window.RefsCapped++; + } + + if (write) state.InWrite = true; + else state.InRead = true; + if (record.Serial > state.MaxSerial) + { + state.MaxSerial = record.Serial; + record.OwnedPages.Add(page); + } + + if (state.Faulted) + { + continue; + } + + Watch(window, page, state, masks); + } + } + + private void Watch(Window window, ulong page, PageState state, Dictionary<(ulong, bool), PageMask> masks) + { + var wasWatched = state.WriteWatched || state.ReadWatched; + if (state.InWrite && _armReads && !state.ReadWatched) + { + if (_watches.IsReadWatched(page)) + { + if (!wasWatched) + { + window.SkippedReadWatched++; + } + } + else + { + state.ReadWatched = true; + window.ReadArmedPages++; + SetMask(masks, page, reads: true); + } + } + + if (!state.ReadWatched && !state.WriteWatched) + { + state.WriteWatched = true; + SetMask(masks, page, reads: false); + } + + if (!wasWatched) + { + window.ArmedPages++; + } + } + + private void ArmCommandBufferLocked(Window window, ulong address, ulong bytes) + { + var masks = new Dictionary<(ulong, bool), PageMask>(); + for (var page = address & ~(PageBytes - 1); page < address + bytes; page += PageBytes) + { + if (!_pages.TryGetValue(page, out var state)) + { + state = new PageState { Window = window }; + _pages[page] = state; + _anyPages = true; + } + + (state.CommandBuffers ??= new()).Add((address, bytes)); + if (!state.WriteWatched && !state.ReadWatched && !(state.Faulted && ReferenceEquals(state.Window, window))) + { + if (!ReferenceEquals(state.Window, window)) + { + state.Window = window; + state.Refs.Clear(); + state.InRead = state.InWrite = false; + } + + state.Faulted = false; + state.WriteWatched = true; + window.CommandBufferPages++; + window.ArmedPages++; + SetMask(masks, page, reads: false); + } + } + + Apply(masks, add: true); + } + + private void Unwatch(ulong page, PageState state, Dictionary<(ulong, bool), PageMask> masks) + { + if (state.WriteWatched) + { + SetMask(masks, page, reads: false); + state.WriteWatched = false; + } + + if (state.ReadWatched) + { + SetMask(masks, page, reads: true); + state.ReadWatched = false; + } + } + + private static void SetMask(Dictionary<(ulong, bool), PageMask> masks, ulong page, bool reads) + { + var key = (page & ~(TrackerLayout.BlockBytes - 1), reads); + masks.TryGetValue(key, out var mask); + mask.Set((int)((page & (TrackerLayout.BlockBytes - 1)) / PageBytes)); + masks[key] = mask; + } + + private void Apply(Dictionary<(ulong, bool), PageMask> masks, bool add) + { + foreach (var pair in masks) + { + var mask = pair.Value; + if (add) _watches.Add(pair.Key.Item1, mask, pair.Key.Item2); + else _watches.Remove(pair.Key.Item1, mask, pair.Key.Item2); + } + } + + // ---- faults ------------------------------------------------------------------------------- + + public bool TryHandleFault(FaultKind kind, ulong address, out bool stillBlocked) + { + stillBlocked = false; + if (!_anyPages) + { + return false; + } + + var now = _clock(); + var page = address & ~(PageBytes - 1); + lock (_gate) + { + if (!_pages.TryGetValue(page, out var state)) + { + return false; + } + + var ours = kind == FaultKind.Read ? state.ReadWatched : state.ReadWatched || state.WriteWatched; + if (!ours) + { + // Let go already (another thread's fault, or the buffer completed) but the access met the + // protection the watch had: once the release is applied it goes through, so it is retried. + if (!_watches.StillBlocks(page, kind)) + { + var retries = _retries.GetValueOrDefault(page); + if (retries < MaxRetriesPerPage) + { + _retries[page] = retries + 1; + _lateFaults++; + return true; + } + } + + return false; + } + + if (state.Window is { } window) + { + Attribute(window, state, address, write: kind != FaultKind.Read, now); + } + + state.Faulted = true; + var masks = new Dictionary<(ulong, bool), PageMask>(); + Unwatch(page, state, masks); + Apply(masks, add: false); + stillBlocked = _watches.StillBlocks(page, kind); + return true; + } + } + + /// A managed (HLE) write into an armed page: it does not fault, so it is only counted. + public void NoteManagedWrite(ulong address, ulong size) + { + if (!_anyPages || size == 0 || size > ulong.MaxValue - address) + { + return; + } + + lock (_gate) + { + var end = address + size; + var pages = 0; + for (var page = address & ~(PageBytes - 1); page < end && pages < 4096; page += PageBytes, pages++) + { + if (_pages.TryGetValue(page, out var state) && (state.WriteWatched || state.ReadWatched) && state.Window is { } window) + { + window.Managed++; + } + } + } + } + + internal int Era(Window window, ulong serial) + { + if (serial > window.PresentSerial) + { + var after = serial - window.PresentSerial; + return after <= 4 ? 3 + (int)after : 8; + } + + if (serial <= window.PreviousPresentSerial || window.PresentSerial <= window.PreviousPresentSerial) + { + return 0; + } + + var span = window.PresentSerial - window.PreviousPresentSerial; + var position = (double)(serial - window.PreviousPresentSerial) / span; + return position <= 1.0 / 3 ? 1 : position <= 2.0 / 3 ? 2 : 3; + } + + private void Attribute(Window window, PageState state, ulong address, bool write, long now) + { + var ms = (now - window.GateTicks) * 1000.0 / Stopwatch.Frequency; + if (write) + { + foreach (var reference in state.Refs) + { + if (reference.Write) + { + continue; + } + + var read = reference.Record.Reads[reference.Index]; + window.RsPageRanges.Add((read.Address, read.Size)); + } + + foreach (var reference in state.Refs) + { + if (reference.Write) + { + continue; + } + + var read = reference.Record.Reads[reference.Index]; + if (address >= read.Address && address - read.Address < read.Size) + { + window.RsHit++; + window.RsHitByTag[(int)read.Tag]++; + var era = Era(window, reference.Record.Serial); + window.RsHitByEra[era]++; + window.RsHitRanges.Add((read.Address, read.Size)); + window.RsHitMs.Add(ms); + Report(window, "store_rs", address, read.Address, read.Size, TagNames[(int)read.Tag], reference.Record.Serial, era, ms, 0); + return; + } + } + + foreach (var reference in state.Refs) + { + if (!reference.Write) + { + continue; + } + + var written = reference.Record.Writes[reference.Index]; + if (address >= written.Address && address - written.Address < written.Size) + { + window.WsStoreHit++; + window.WsStoreByOrigin[written.Origin]++; + Report(window, "store_ws", address, written.Address, written.Size, OriginNames[written.Origin] + "/" + TagNames[(int)written.Tag], + reference.Record.Serial, Era(window, reference.Record.Serial), ms, written.Program); + return; + } + } + + if (state.CommandBuffers is { } buffers) + { + foreach (var (bufferAddress, bytes) in buffers) + { + if (address >= bufferAddress && address - bufferAddress < bytes) + { + window.CbHit++; + window.CbMs.Add(ms); + Report(window, "store_cb", address, bufferAddress, bytes, "command_buffer", 0, 8, ms, 0); + return; + } + } + } + + if (state.InRead) window.RsNeighbour++; + else if (state.InWrite) window.WsStoreNeighbour++; + else window.CbNeighbour++; + return; + } + + foreach (var reference in state.Refs) + { + if (!reference.Write) + { + continue; + } + + var written = reference.Record.Writes[reference.Index]; + if (address >= written.Address && address - written.Address < written.Size) + { + window.WsLoadHit++; + window.WsLoadByOrigin[written.Origin]++; + window.WsLoadByTag[(int)written.Tag]++; + var era = Era(window, reference.Record.Serial); + window.WsLoadByEra[era]++; + window.WsLoadRanges.Add((written.Address, written.Size)); + window.WsLoadMs.Add(ms); + Report(window, "load_ws", address, written.Address, written.Size, OriginNames[written.Origin] + "/" + TagNames[(int)written.Tag], + reference.Record.Serial, era, ms, written.Program); + return; + } + } + + window.WsLoadNeighbour++; + } + + private void Report(Window window, string what, ulong address, ulong rangeAddress, ulong rangeSize, string kind, ulong serial, int era, double ms, ulong program) + { + if (_hitLines >= HitLines) + { + return; + } + + _hitLines++; + var offset = serial == 0 ? "-" : ((long)serial - (long)window.PresentSerial).ToString(CultureInfo.InvariantCulture); + Console.Error.WriteLine(string.Create(CultureInfo.InvariantCulture, + $"[METAL-V2][OVERLAP-INFLIGHT-HIT] frame={window.Index} {what} addr=0x{address:X} range=0x{rangeAddress:X}+0x{rangeSize:X} kind={kind} " + + $"serial_vs_present={offset} era={EraNames[era]} ms_after_gate={ms:F2} program=0x{program:X16}")); + } + + // ---- windows ------------------------------------------------------------------------------ + + private void FinalizeIfDoneLocked() + { + for (var index = 0; index < _windows.Count;) + { + var window = _windows[index]; + if (!window.Closed || window.MaxArmedSerial > _completedSerial) + { + index++; + continue; + } + + _windows.RemoveAt(index); + window.FinalizedTicks = _clock(); + _done.Add(window); + } + } + + // Pages of windows finalized over half a second ago that hold no watch: a fault that raced their + // release has been retried by then, so they are forgotten (stats-window thread). + private void PruneLocked(long now) + { + var stale = new List(); + foreach (var pair in _pages) + { + var state = pair.Value; + if (!state.ReadWatched && !state.WriteWatched && state.CommandBuffers is null && + (state.Window is null || (state.Window.FinalizedTicks != 0 && now - state.Window.FinalizedTicks > Stopwatch.Frequency / 2))) + { + stale.Add(pair.Key); + } + } + + foreach (var page in stale) + { + _pages.Remove(page); + _retries.Remove(page); + } + + _anyPages = _pages.Count != 0; + } + + internal IReadOnlyList TakeFinished() + { + lock (_gate) + { + var finished = _done.ToArray(); + _done.Clear(); + return finished; + } + } + + /// One line per stats window: per sampled frame, mean (max) and time percentiles from the gate. + public string? TakeWindowLine() + { + var windows = TakeFinished(); + long late; + lock (_gate) + { + late = _lateFaults; + PruneLocked(_clock()); + } + + if (windows.Count == 0) + { + return null; + } + + var culture = CultureInfo.InvariantCulture; + var n = windows.Count; + string M(Func pick) => string.Create(culture, $"{windows.Average(pick):F1}/{windows.Max(pick):F0}"); + string Mb(Func> pick) => + string.Create(culture, $"{windows.Average(w => pick(w).Sum(r => (double)r.Item2)) / (1 << 20):F3}"); + string Split(Func pick, string[] names) + { + var builder = new StringBuilder(); + for (var index = 0; index < names.Length; index++) + { + var total = windows.Sum(w => pick(w)[index]); + if (total != 0) + { + builder.Append(builder.Length == 0 ? string.Empty : ",").Append(names[index]).Append(':') + .Append(((double)total / n).ToString("F1", culture)); + } + } + + return builder.ToString(); + } + + string P(Func> pick) + { + var values = windows.SelectMany(pick).ToList(); + return FrameOverlapTracker.Percentiles(values, culture); + } + + string FirstP(Func> pick) + { + var values = windows.Where(w => pick(w).Count != 0).Select(w => pick(w).Min()).ToList(); + return FrameOverlapTracker.Percentiles(values, culture); + } + + return string.Create(culture, + $"[METAL-V2][OVERLAP-INFLIGHT] frames={n} armed_pages={M(w => w.ArmedPages)} read_armed={M(w => w.ReadArmedPages)} " + + $"cb_pages={M(w => w.CommandBufferPages)} buffers_armed={M(w => w.RecordsArmed)} arm_ms={M(w => w.ArmTicks * 1000.0 / Stopwatch.Frequency)} " + + $"cap_skipped={M(w => w.CapSkipped)} skipped_read_watched={M(w => w.SkippedReadWatched)} huge={M(w => w.HugeRanges)} refs_capped={M(w => w.RefsCapped)} " + + $"| 1a store_rs_hit_pages={M(w => w.RsHit)} ranges={M(w => w.RsHitRanges.Count)} hit_range_mb={Mb(w => w.RsHitRanges)} " + + $"page_range_mb={Mb(w => w.RsPageRanges)} nb_pages={M(w => w.RsNeighbour)} by_tag=[{Split(w => w.RsHitByTag, TagNames)}] " + + $"by_era=[{Split(w => w.RsHitByEra, EraNames)}] first_ms={FirstP(w => w.RsHitMs)} all_ms={P(w => w.RsHitMs)} " + + $"| 1b store_cb_hit_pages={M(w => w.CbHit)} nb={M(w => w.CbNeighbour)} first_ms={FirstP(w => w.CbMs)} " + + $"| ws store_hit_pages={M(w => w.WsStoreHit)} nb={M(w => w.WsStoreNeighbour)} by_origin=[{Split(w => w.WsStoreByOrigin, OriginNames)}] " + + $"| 2 load_ws_hit_pages={M(w => w.WsLoadHit)} ranges={M(w => w.WsLoadRanges.Count)} mb={Mb(w => w.WsLoadRanges)} nb_pages={M(w => w.WsLoadNeighbour)} " + + $"by_origin=[{Split(w => w.WsLoadByOrigin, OriginNames)}] by_tag=[{Split(w => w.WsLoadByTag, TagNames)}] by_era=[{Split(w => w.WsLoadByEra, EraNames)}] " + + $"first_ms={FirstP(w => w.WsLoadMs)} all_ms={P(w => w.WsLoadMs)} | managed={M(w => w.Managed)} late_faults={late}"); + } +} diff --git a/src/SharpEmu.Libs/Gpu/GpuCommands/CommandStreamQueue.cs b/src/SharpEmu.Libs/Gpu/GpuCommands/CommandStreamQueue.cs index d8c71b604..b0f88d6fa 100644 --- a/src/SharpEmu.Libs/Gpu/GpuCommands/CommandStreamQueue.cs +++ b/src/SharpEmu.Libs/Gpu/GpuCommands/CommandStreamQueue.cs @@ -1817,6 +1817,12 @@ submission.Kind is not (CommandSubmissionKind.FlipPreparation or CommandSubmissi $"packet=0x{submission.Commands.CurrentPacketAddress:X16} wait={submission.Wait.Kind}@0x{submission.Wait.Address:X} " + DescribePackets(submission.Address, submission.DwordCount)); + if (result == SliceResult.Completed && SharpEmu.HLE.GpuMemory.FrameOverlapDiagnostic.Enabled && + submission!.Kind != CommandSubmissionKind.FlipPreparation) + { + SharpEmu.HLE.GpuMemory.FrameOverlapDiagnostic.OnSubmissionWalked(submission.Address, (ulong)submission.DwordCount * sizeof(uint)); + } + if (dsSlice) { DsEmitSlice(submission!, result, dsStarted, dsCpuStarted, dsPacketsStarted); diff --git a/src/SharpEmu.Libs/Gpu/GpuCommands/FrameOverlapProbe.cs b/src/SharpEmu.Libs/Gpu/GpuCommands/FrameOverlapProbe.cs index a0326fa23..a69e6a495 100644 --- a/src/SharpEmu.Libs/Gpu/GpuCommands/FrameOverlapProbe.cs +++ b/src/SharpEmu.Libs/Gpu/GpuCommands/FrameOverlapProbe.cs @@ -256,6 +256,12 @@ public void OnCommit(ulong serial) { _commits++; batch = _open; + if (SharpEmu.HLE.GpuMemory.FrameOverlapDiagnostic.Enabled) + { + // SHARPEMU_DIAG_FRAME_OVERLAP_ARM=inflight: the buffer's reads and writes are recorded under its serial. + SharpEmu.HLE.GpuMemory.FrameOverlapDiagnostic.OnProbeCommit(serial, batch.HasFlip); + } + _open = new Batch(batch.Index + 1) { FirstSerial = serial + 1 }; if (batch.Items.Count == 0 && !batch.HasFlip) { @@ -321,6 +327,12 @@ private void Publish(Batch batch) } } + if (SharpEmu.HLE.GpuMemory.FrameOverlapDiagnostic.Enabled) + { + // The in-flight diagnostic arms what this publication releases before the guest can see it. + SharpEmu.HLE.GpuMemory.FrameOverlapDiagnostic.OnProbeRelease(batch.Serial); + } + var early = _completedSerial() < batch.Serial; var ran = 0; foreach (var item in batch.Items) diff --git a/src/SharpEmu.Libs/Gpu/Rendering/RenderRecorder.cs b/src/SharpEmu.Libs/Gpu/Rendering/RenderRecorder.cs index c8fe8d2cb..38553c53f 100644 --- a/src/SharpEmu.Libs/Gpu/Rendering/RenderRecorder.cs +++ b/src/SharpEmu.Libs/Gpu/Rendering/RenderRecorder.cs @@ -642,12 +642,26 @@ private void RecordDrawCommands(ResolvedDraw record, ref DrawState state, bool i _host.BindResources(pixelBindings); } - var vertexBuffers = meshInput is null ? AcquireVertexBuffers(vertexInput) : default; - var indexBuffer = meshInput is null ? AcquireIndexBuffer(in indexSource) : default; - var indirectArguments = meshInput is null && emission.IndirectArgumentsAddress != 0 - ? _host.ObtainBuffer(emission.IndirectArgumentsAddress, - emission.Indexed ? RenderExecutor.IndexedIndirectArgumentsSize : RenderExecutor.AutoIndirectArgumentsSize, isWritten: false) - : default; + ReadOnlySpan vertexBuffers; + PreparedIndexBuffer indexBuffer; + BufferBinding indirectArguments; + using (SharpEmu.HLE.GpuMemory.FrameOverlapDiagnostic.Tag(SharpEmu.HLE.GpuMemory.OverlapTag.Vertex)) + { + vertexBuffers = meshInput is null ? AcquireVertexBuffers(vertexInput) : default; + } + + using (SharpEmu.HLE.GpuMemory.FrameOverlapDiagnostic.Tag(SharpEmu.HLE.GpuMemory.OverlapTag.Index)) + { + indexBuffer = meshInput is null ? AcquireIndexBuffer(in indexSource) : default; + } + + using (SharpEmu.HLE.GpuMemory.FrameOverlapDiagnostic.Tag(SharpEmu.HLE.GpuMemory.OverlapTag.Indirect)) + { + indirectArguments = meshInput is null && emission.IndirectArgumentsAddress != 0 + ? _host.ObtainBuffer(emission.IndirectArgumentsAddress, + emission.Indexed ? RenderExecutor.IndexedIndirectArgumentsSize : RenderExecutor.AutoIndirectArgumentsSize, isWritten: false) + : default; + } RenderExecutor.DropUnwrittenColorTargets(context, ref state, pixelProgram); if (inPlace && TryRestoreAttachments(ref state)) { diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Descriptors.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Descriptors.cs index 5a123ed80..20b14b380 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Descriptors.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Descriptors.cs @@ -1032,6 +1032,10 @@ public void BindResources(IPreparedBindings prepared) var written = info.Buffers[index].Written; var computeStage = stage.Program.Stage == ShaderStageKind.Compute; + using var overlapTag = SharpEmu.HLE.GpuMemory.FrameOverlapDiagnostic.Tag( + written ? SharpEmu.HLE.GpuMemory.OverlapTag.StorageWritten + : info.Buffers[index].Scalar ? SharpEmu.HLE.GpuMemory.OverlapTag.Constant + : SharpEmu.HLE.GpuMemory.OverlapTag.StorageRead); if (written) { _writtenBufferBinds++; diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.LodStatistics.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.LodStatistics.cs index 46820ad89..c7f49ace0 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.LodStatistics.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.LodStatistics.cs @@ -289,7 +289,10 @@ bool ICommandStreamHost.TryRecordLodStatistics(ulong destination, uint size, boo MipStatistics.Shared.ClearBoundSlots(); _imageCache.InvalidateMemoryFromGpu(destination, reportBytes); - NoteGuestMemoryWrite(destination, reportBytes, MetalGpuWriteOrigin.Copy); + using (SharpEmu.HLE.GpuMemory.FrameOverlapDiagnostic.Tag(SharpEmu.HLE.GpuMemory.OverlapTag.LodStatistics)) + { + NoteGuestMemoryWrite(destination, reportBytes, MetalGpuWriteOrigin.Copy); + } // A command processor polling the header suspends until the submission that // writes it completes; the worker commits what it has before it parks. _pendingLabelWrites++; diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Occlusion.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Occlusion.cs index e68b3b86e..a22ada158 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Occlusion.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Occlusion.cs @@ -395,6 +395,7 @@ private bool DumpOcclusionCounterNow(int queueId, ulong address, uint instanceMa // the pass ends below; there is no next slot to initialize. if (batch.Slot < OcclusionIntervalCapacity) InitializeOcclusionSlot(batch); } + using var overlapTag = SharpEmu.HLE.GpuMemory.FrameOverlapDiagnostic.Tag(SharpEmu.HLE.GpuMemory.OverlapTag.Occlusion); _ = EncodeOrderedCopies(copies[..count], address, null, 0, MetalGpuWriteOrigin.Copy, "occlusion dump", null, (ulong)count * sizeof(ulong), sourceIsFinal: false, deferStableGpuResult: batch is not null, noteAsOneRange: CoalesceOcclusionDumps); diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.ThreadDispatch.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.ThreadDispatch.cs index 551092bd9..663f1f3a6 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.ThreadDispatch.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.ThreadDispatch.cs @@ -98,6 +98,7 @@ public unsafe bool TryDispatchThreadsIndirect( var shift = argumentsAddress & 0x3; var alignedAddress = argumentsAddress - shift; + using var overlapTag = SharpEmu.HLE.GpuMemory.FrameOverlapDiagnostic.Tag(SharpEmu.HLE.GpuMemory.OverlapTag.Indirect); var range = _guestMemory.Resolve(alignedAddress, shift + (3 * sizeof(uint))); if (!range.IsValid) { diff --git a/tests/SharpEmu.Libs.Tests/HLE/InFlightOverlapTrackerTests.cs b/tests/SharpEmu.Libs.Tests/HLE/InFlightOverlapTrackerTests.cs new file mode 100644 index 000000000..f427c78c1 --- /dev/null +++ b/tests/SharpEmu.Libs.Tests/HLE/InFlightOverlapTrackerTests.cs @@ -0,0 +1,214 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using SharpEmu.HLE.GpuMemory; +using Xunit; + +namespace SharpEmu.Libs.Tests.HLE; + +/// +/// The in-flight overlap diagnostic without a page guard: a sampled frame's gate arms the released buffers the +/// GPU has not completed (reads for stores, writes for loads), each fault is attributed by byte and let go, +/// a submission's command buffer is watched until it is walked, and every watch is given back. +/// +public sealed class InFlightOverlapTrackerTests +{ + private const ulong Page = TrackerLayout.PageBytes; + + private sealed class FakeWatches : IFrameOverlapWatches + { + public readonly Dictionary<(ulong Page, bool Reads), int> Counts = new(); + + public bool IsReadWatched(ulong page) => false; + + public void Add(ulong blockBase, in PageMask pages, bool blockReads) => Change(blockBase, pages, blockReads, 1); + + public void Remove(ulong blockBase, in PageMask pages, bool blockReads) => Change(blockBase, pages, blockReads, -1); + + public bool StillBlocks(ulong page, FaultKind kind) => + Counts.GetValueOrDefault((page, true)) != 0 || (kind != FaultKind.Read && Counts.GetValueOrDefault((page, false)) != 0); + + private void Change(ulong blockBase, PageMask pages, bool reads, int delta) + { + for (var index = 0; index < TrackerLayout.PagesPerBlock; index++) + { + if (!pages.Get(index)) + { + continue; + } + + var key = (blockBase + (ulong)index * Page, reads); + var count = Counts.GetValueOrDefault(key) + delta; + Assert.True(count >= 0, $"watch count below zero at 0x{key.Item1:X}"); + Counts[key] = count; + } + } + + public int Live => Counts.Values.Sum(); + } + + private long _now = 1; + + private InFlightOverlapTracker Create(FakeWatches watches, int every = 1) => new(watches, () => _now, every, 1000, armReads: true); + + // Present at serial 1, then buffer 2 reads a constant range and has an occlusion result copied into guest memory. + private static void RecordFrame(InFlightOverlapTracker tracker) + { + tracker.OnCommit(1, present: true); + tracker.MarkRead(0x100000, 0x100, OverlapTag.Constant); + tracker.NoteWrite(0x200000, 0x40, OverlapWrite.Copy, OverlapTag.Occlusion, 0); + tracker.OnCommit(2, present: false); + tracker.OnCommit(3, present: false); + } + + // The next present and its gate close the sampled window. + private static void CloseWindow(InFlightOverlapTracker tracker) + { + tracker.OnCommit(4, present: true); + tracker.OnCommit(5, present: false); + tracker.OnCommit(6, present: false); + tracker.OnRelease(6); + tracker.OnCompleted(6); + } + + [Fact] + public void TheGateArmsReleasedBuffersStillRunningReadsForStoresAndWritesForLoads() + { + var watches = new FakeWatches(); + var tracker = Create(watches); + RecordFrame(tracker); + + tracker.OnRelease(3); + + Assert.Equal(1, watches.Counts.GetValueOrDefault((0x100000UL, false))); + Assert.Equal(1, watches.Counts.GetValueOrDefault((0x200000UL, true))); + Assert.Equal(2, watches.Live); + + _now += 1000; + Assert.True(tracker.TryHandleFault(FaultKind.Write, 0x100010, out var blocked)); + Assert.False(blocked); + Assert.True(tracker.TryHandleFault(FaultKind.Read, 0x200008, out _)); + Assert.Equal(0, watches.Live); + + tracker.OnCompleted(3); + CloseWindow(tracker); + var line = tracker.TakeWindowLine(); + Assert.NotNull(line); + Assert.Contains("store_rs_hit_pages=1.0/1", line); + Assert.Contains("by_tag=[constant:1.0]", line); + Assert.Contains("by_era=[p+1:1.0]", line); + Assert.Contains("load_ws_hit_pages=1.0/1", line); + Assert.Contains("by_origin=[copy:1.0] by_tag=[occlusion:1.0]", line); + Assert.Equal(0, watches.Live); + } + + [Fact] + public void NothingIsArmedBeforeTheGateAndCompletionGivesEveryWatchBack() + { + var watches = new FakeWatches(); + var tracker = Create(watches); + RecordFrame(tracker); + + // Present + 1 is not the gate. + tracker.OnRelease(2); + Assert.Equal(0, watches.Live); + + tracker.OnRelease(3); + Assert.Equal(2, watches.Live); + tracker.OnCompleted(3); + Assert.Equal(0, watches.Live); + } + + [Fact] + public void ACompletedBufferIsNotArmed() + { + var watches = new FakeWatches(); + var tracker = Create(watches); + RecordFrame(tracker); + tracker.OnCompleted(2); + + tracker.OnRelease(3); + + Assert.Equal(0, watches.Live); + } + + [Fact] + public void AStoreBesideTheRangeOnItsPageIsANeighbourNotAHit() + { + var watches = new FakeWatches(); + var tracker = Create(watches); + RecordFrame(tracker); + tracker.OnRelease(3); + + Assert.True(tracker.TryHandleFault(FaultKind.Write, 0x100800, out _)); + tracker.OnCompleted(3); + CloseWindow(tracker); + + var line = tracker.TakeWindowLine()!; + Assert.Contains("store_rs_hit_pages=0.0/0", line); + Assert.Contains("ranges=0.0/0 hit_range_mb=0.000 page_range_mb=0.000 nb_pages=1.0/1", line); + } + + [Fact] + public void ACommandBufferAdmittedAndNotWalkedIsWatchedUntilItIsWalked() + { + var watches = new FakeWatches(); + var tracker = Create(watches); + tracker.OnAdmission(0x300000, 2 * Page); + RecordFrame(tracker); + tracker.OnRelease(3); + Assert.Equal(1, watches.Counts.GetValueOrDefault((0x300000UL, false))); + Assert.Equal(1, watches.Counts.GetValueOrDefault((0x300000UL + Page, false))); + + Assert.True(tracker.TryHandleFault(FaultKind.Write, 0x300010, out _)); + tracker.OnSubmissionWalked(0x300000, 2 * Page); + Assert.Equal(0, watches.Counts.GetValueOrDefault((0x300000UL + Page, false))); + + tracker.OnCompleted(3); + Assert.Equal(0, watches.Live); + CloseWindow(tracker); + Assert.Contains("store_cb_hit_pages=1.0/1", tracker.TakeWindowLine()!); + } + + [Fact] + public void AnUnsampledFrameArmsNothing() + { + var watches = new FakeWatches(); + var tracker = Create(watches, every: 2); + RecordFrame(tracker); + + tracker.OnRelease(3); + + Assert.Equal(0, watches.Live); + } + + [Fact] + public void AFaultOnAPageAlreadyLetGoIsRetriedWhileNothingElseBlocksIt() + { + var watches = new FakeWatches(); + var tracker = Create(watches); + RecordFrame(tracker); + tracker.OnRelease(3); + Assert.True(tracker.TryHandleFault(FaultKind.Write, 0x100010, out _)); + + // A second thread's store that met the same protection before the release applied. + Assert.True(tracker.TryHandleFault(FaultKind.Write, 0x100020, out _)); + // A page the diagnostic never armed is not its own. + Assert.False(tracker.TryHandleFault(FaultKind.Write, 0x900000, out _)); + } + + [Fact] + public void ErasPlaceABufferAgainstTheSampledFramesPresent() + { + var watches = new FakeWatches(); + var tracker = Create(watches); + var window = new InFlightOverlapTracker.Window { PreviousPresentSerial = 10, PresentSerial = 40 }; + + Assert.Equal("older", InFlightOverlapTracker.EraNames[tracker.Era(window, 9)]); + Assert.Equal("f_first", InFlightOverlapTracker.EraNames[tracker.Era(window, 15)]); + Assert.Equal("f_second", InFlightOverlapTracker.EraNames[tracker.Era(window, 25)]); + Assert.Equal("f_last", InFlightOverlapTracker.EraNames[tracker.Era(window, 40)]); + Assert.Equal("p+2", InFlightOverlapTracker.EraNames[tracker.Era(window, 42)]); + Assert.Equal("next", InFlightOverlapTracker.EraNames[tracker.Era(window, 45)]); + } +} From 646c914f389e64e99fef6f8fbc6aec6b390b3da3 Mon Sep 17 00:00:00 2001 From: kuba Date: Mon, 16 Nov 2026 10:22:45 +0000 Subject: [PATCH 132/178] [Diag] Frame-overlap in-flight mode: arm at commit on a thread, never delay a publication r infl1 (3d7eab18f) armed at each publication, on the completion thread, before the guest could see it: 86-123 ms per sampled frame for 350-450k pages, so the GPU tail had finished by the time the guest ran and every hit came 136-236 ms after the gate. It also never reset a page's answered-retry count, so a fence page polled by several threads every sampled frame passed 256 retries and a read fault was declined (SIGBUS at 140 s, after the gameplay segment). Now a sampled frame's buffers (from the present before its own to its next frame's gate) are armed as they commit, on a background thread, and let go on that thread once they complete; a publication only opens the frame's window at its gate, stamps the released serial, re-arms the pages a buffer's own guest touched before the buffer was published, and counts released buffers not yet armed (late_buffers). A fault counts as the race only between its buffer's publication and its completion (pre_release and after_completion are counted apart). Page state is a struct and a fault finds its range through a per-buffer sorted index, so arming is a dictionary write per page; a page watched again starts a new retry count, and a declined fault prints a WARN. --- .../GpuMemory/InFlightOverlapTracker.cs | 685 ++++++++++++------ .../HLE/InFlightOverlapTrackerTests.cs | 37 +- 2 files changed, 482 insertions(+), 240 deletions(-) diff --git a/src/SharpEmu.HLE/GpuMemory/InFlightOverlapTracker.cs b/src/SharpEmu.HLE/GpuMemory/InFlightOverlapTracker.cs index 923432f6f..7cc7d23c3 100644 --- a/src/SharpEmu.HLE/GpuMemory/InFlightOverlapTracker.cs +++ b/src/SharpEmu.HLE/GpuMemory/InFlightOverlapTracker.cs @@ -26,23 +26,28 @@ public enum OverlapTag : byte /// /// SHARPEMU_DIAG_FRAME_OVERLAP_ARM=inflight with SHARPEMU_FRAME_OVERLAP_PROBE=1 (diagnostic only): what the /// guest touches while GPU work it has already been told is finished still runs. Each command buffer's -/// in-place reads and GPU writes are recorded under its serial. On a sampled frame, from the release of its -/// gate (the first publication at or past its present commit + 2) to the next frame's gate, every release -/// arms the buffers it covers that the GPU has not completed: their read pages get a write watch, their -/// written pages a read watch. A page is let go when the last buffer that armed it completes, or at its -/// first fault, which is attributed byte by byte: a store into a read range (the GPU may still read it), a -/// store into a written range, a load of a written range (the GPU has not produced it), or a store into the -/// command buffer of a submission admitted and not yet walked. Times are from the frame's gate. +/// in-place reads and GPU writes are recorded under its serial. For a sampled frame F (every Kth), the +/// buffers committed from the present before F's to F's own present and its post-flip buffers are armed +/// as they commit, on a background thread, so the probe's publications are not delayed: read pages get a +/// write watch, written pages a read watch, and the command buffers of submissions admitted and not yet +/// walked a write watch. A buffer's pages are let go once it completes. F's window opens at its gate (the +/// first publication at or past its present + 2) and closes at the next frame's gate. A fault is +/// attributed byte by byte to the buffer whose range holds it and counted once per page: before that +/// buffer was published (pre-release: the page is armed again when it is), after it completed (not a +/// race), or between the two, the race the early publication opens: a store into a read range (1a), a +/// store into a written range, a load of a written range (2), a store into a command buffer not yet +/// walked (1b). Times are from F's gate. /// -public sealed class InFlightOverlapTracker +public sealed class InFlightOverlapTracker : IDisposable { internal const ulong HugeRangeBytes = 256UL << 20; private const ulong PageBytes = TrackerLayout.PageBytes; - private const int MaxRefsPerPage = 32; private const int MaxRetriesPerPage = 256; private const int OriginCount = (int)OverlapWrite.EopGpuValued + 1; private const int TagCount = (int)OverlapTag.LodStatistics + 1; - private const int HitLines = 80; + private const int HitLines = 120; + + private const byte InRead = 1, InWrite = 2, WriteWatched = 4, ReadWatched = 8, Faulted = 16, CommandBuffer = 32; internal static readonly string[] TagNames = ["other", "vertex", "index", "indirect", "constant", "storage_read", "storage_written", "texture", "device_address", "occlusion", "lod_stats"]; @@ -56,37 +61,41 @@ public sealed class InFlightOverlapTracker internal sealed class Record { public ulong Serial; - public bool Armed; + public Window? Window; + public bool Armed, Disarmed, Late; public readonly List<(ulong Address, ulong Size, OverlapTag Tag)> Reads = new(); public readonly List<(ulong Address, ulong Size, int Origin, OverlapTag Tag, ulong Program)> Writes = new(); public readonly List OwnedPages = new(); + public (ulong Start, ulong End, int Index)[]? ReadIndex, WriteIndex; + public ulong[]? ReadMaxEnd, WriteMaxEnd; } - private sealed class PageState + private struct PageState { public Window? Window; public ulong MaxSerial; - public bool InRead, InWrite, Faulted, WriteWatched, ReadWatched, RefsCapped; - public readonly List<(Record Record, int Index, bool Write)> Refs = new(2); - public List<(ulong Address, ulong Bytes)>? CommandBuffers; + public byte Flags; } internal sealed class Window { public long Index; - public ulong PresentSerial, PreviousPresentSerial, GateSerial, MaxArmedSerial; + public ulong PresentSerial, PreviousPresentSerial; public long GateTicks, ArmTicks, FinalizedTicks; - public bool Closed; - public int ArmedPages, ReadArmedPages, CapSkipped, SkippedReadWatched, RecordsArmed, HugeRanges, RefsCapped, CommandBufferPages, Managed; + public bool Open, Closed; + public readonly List Records = new(); + public readonly List PreReleasePages = new(); + public int ArmedPages, ReadArmedPages, CapSkipped, SkippedReadWatched, HugeRanges, CommandBufferPages, Managed, LateRecords, Rearmed; + public int PreReleaseStores, PreReleaseLoads, AfterCompletion; public int RsHit, RsNeighbour, WsStoreHit, WsStoreNeighbour, WsLoadHit, WsLoadNeighbour, CbHit, CbNeighbour; public readonly long[] RsHitByTag = new long[TagCount]; public readonly long[] RsHitByEra = new long[EraNames.Length]; + public readonly long[] PreStoreByTag = new long[TagCount]; public readonly long[] WsLoadByOrigin = new long[OriginCount]; public readonly long[] WsLoadByTag = new long[TagCount]; public readonly long[] WsLoadByEra = new long[EraNames.Length]; public readonly long[] WsStoreByOrigin = new long[OriginCount]; public readonly HashSet<(ulong, ulong)> RsHitRanges = new(); - public readonly HashSet<(ulong, ulong)> RsPageRanges = new(); public readonly HashSet<(ulong, ulong)> WsLoadRanges = new(); public readonly List RsHitMs = new(), WsLoadMs = new(), CbMs = new(); } @@ -97,32 +106,37 @@ internal sealed class Window private readonly int _maxArmedPages; private readonly bool _armReads; private readonly object _gate = new(); + private readonly Queue<(bool Arm, Record? Record, ulong Completed)> _requests = new(); + private readonly Thread? _thread; + private bool _stopping; private Record _open = new(); private readonly List _inFlight = new(); - private ulong _completedSerial; + private ulong _completedSerial, _releasedSerial; private long _frames; - private ulong _lastPresent, _presentBefore; + private ulong _lastPresent; private ulong _gateOpenedFor; - private Window? _arming; private readonly List _windows = new(); private readonly Dictionary _pages = new(); private readonly Dictionary _retries = new(); private readonly List<(ulong Address, ulong Bytes)> _admitted = new(); private volatile bool _anyPages; private int _hitLines; - private long _lateFaults; - - // Finalized windows since the last stats line. + private long _lateFaults, _declined; private readonly List _done = new(); - public InFlightOverlapTracker(IFrameOverlapWatches watches, Func clock, int sampleEvery, int maxArmedPages, bool armReads) + public InFlightOverlapTracker(IFrameOverlapWatches watches, Func clock, int sampleEvery, int maxArmedPages, bool armReads, bool startThread = true) { _watches = watches; _clock = clock; _sampleEvery = Math.Max(1, sampleEvery); _maxArmedPages = Math.Max(1, maxArmedPages); _armReads = armReads; + if (startThread) + { + _thread = new Thread(Run) { IsBackground = true, Name = "SharpEmu in-flight overlap diagnostic" }; + _thread.Start(); + } } // ---- recording (worker) --------------------------------------------------------------- @@ -153,26 +167,58 @@ public void NoteWrite(ulong address, ulong size, OverlapWrite origin, OverlapTag } } + private Window WindowFor(long frame) + { + foreach (var window in _windows) + { + if (window.Index == frame) + { + return window; + } + } + + var created = new Window { Index = frame }; + _windows.Add(created); + return created; + } + /// The worker committed : what was recorded since the last commit is its buffer. public void OnCommit(ulong serial, bool present) { + Record? arm = null; lock (_gate) { var record = _open; _open = new Record(); record.Serial = serial; - if (serial > _completedSerial && (record.Reads.Count != 0 || record.Writes.Count != 0)) + // Frame F (F % K == 0) arms its own buffers (committed while F-1 presents were seen) and its post-flip ones. + long? frame = _frames % _sampleEvery == 0 ? _frames : (_frames + 1) % _sampleEvery == 0 ? _frames + 1 : null; + if (frame is { } index && index > 0 && serial > _completedSerial && (record.Reads.Count != 0 || record.Writes.Count != 0)) { + record.Window = WindowFor(index); + record.Window.Records.Add(record); _inFlight.Add(record); + arm = record; } if (present) { - _presentBefore = _lastPresent; - _lastPresent = serial; _frames++; + if (_frames % _sampleEvery == 0) + { + var window = WindowFor(_frames); + window.PresentSerial = serial; + window.PreviousPresentSerial = _lastPresent; + } + + _lastPresent = serial; } } + + if (arm is not null) + { + Post(arm: true, arm, 0); + } } // ---- admission (command stream) ------------------------------------------------------- @@ -187,9 +233,12 @@ public void OnAdmission(ulong address, ulong bytes) lock (_gate) { _admitted.Add((address, bytes)); - if (_arming is { } window) + foreach (var window in _windows) { - ArmCommandBufferLocked(window, address, bytes); + if (window.Open && !window.Closed) + { + ArmCommandBufferLocked(window, address, bytes); + } } } } @@ -207,16 +256,18 @@ public void OnSubmissionWalked(ulong address, ulong bytes) var masks = new Dictionary<(ulong, bool), PageMask>(); for (var page = address & ~(PageBytes - 1); page < address + bytes; page += PageBytes) { - if (_pages.TryGetValue(page, out var state) && state.CommandBuffers is { } buffers) + ref var state = ref System.Runtime.InteropServices.CollectionsMarshal.GetValueRefOrNullRef(_pages, page); + if (System.Runtime.CompilerServices.Unsafe.IsNullRef(ref state) || (state.Flags & CommandBuffer) == 0) { - buffers.Remove((address, bytes)); - if (buffers.Count == 0) + continue; + } + + if (!StillAdmitted(page)) + { + state.Flags &= unchecked((byte)~CommandBuffer); + if (state.MaxSerial <= _completedSerial) { - state.CommandBuffers = null; - if (state.MaxSerial <= _completedSerial) - { - Unwatch(page, state, masks); - } + Unwatch(page, ref state, masks); } } } @@ -225,65 +276,94 @@ public void OnSubmissionWalked(ulong address, ulong bytes) } } + private bool StillAdmitted(ulong page) + { + foreach (var (address, bytes) in _admitted) + { + if (page < address + bytes && address < page + PageBytes) + { + return true; + } + } + + return false; + } + // ---- release and completion (completion thread) ---------------------------------------- - /// - /// The probe is about to let the guest see everything up to . Runs before - /// the publication, so the watches are in place before the guest can act on it. - /// + /// The probe is about to let the guest see everything up to . public void OnRelease(ulong serial) { - var started = _clock(); + var now = _clock(); lock (_gate) { + _releasedSerial = Math.Max(_releasedSerial, serial); if (_lastPresent != 0 && _gateOpenedFor != _lastPresent && serial >= _lastPresent + 2) { - // This frame's gate: the window of the previous sampled frame stops taking buffers. _gateOpenedFor = _lastPresent; - if (_arming is { } previous) + foreach (var window in _windows) { - previous.Closed = true; - _arming = null; - FinalizeIfDoneLocked(); + if (window.Open && !window.Closed) + { + window.Closed = true; + } } if (_frames % _sampleEvery == 0) { - var window = new Window - { - Index = _frames, - PresentSerial = _lastPresent, - PreviousPresentSerial = _presentBefore, - GateSerial = serial, - GateTicks = started, - }; - _arming = window; - _windows.Add(window); + var window = WindowFor(_frames); + window.Open = true; + window.GateTicks = now; foreach (var (address, bytes) in _admitted) { ArmCommandBufferLocked(window, address, bytes); } } - } - if (_arming is not { } arming) - { - return; + FinalizeIfDoneLocked(); } + // Pages a buffer's own guest touched before it was released are watched again now, and + // released buffers the arming thread has not reached yet are counted. var masks = new Dictionary<(ulong, bool), PageMask>(); - foreach (var record in _inFlight) + foreach (var window in _windows) { - if (record.Armed || record.Serial > serial || record.Serial <= _completedSerial) + if (window.PreReleasePages.Count != 0) { - continue; + for (var index = 0; index < window.PreReleasePages.Count;) + { + var page = window.PreReleasePages[index]; + ref var state = ref System.Runtime.InteropServices.CollectionsMarshal.GetValueRefOrNullRef(_pages, page); + if (System.Runtime.CompilerServices.Unsafe.IsNullRef(ref state) || state.MaxSerial <= _completedSerial) + { + window.PreReleasePages.RemoveAt(index); + continue; + } + + if (state.MaxSerial > serial) + { + index++; + continue; + } + + window.PreReleasePages.RemoveAt(index); + state.Flags &= unchecked((byte)~Faulted); + window.Rearmed++; + Watch(window, page, ref state, masks, count: false); + } } - ArmRecordLocked(arming, record, masks); + foreach (var record in window.Records) + { + if (!record.Armed && !record.Late && record.Serial <= serial && record.Serial > _completedSerial) + { + record.Late = true; + window.LateRecords++; + } + } } Apply(masks, add: true); - arming.ArmTicks += _clock() - started; } } @@ -297,22 +377,100 @@ public void OnCompleted(ulong serial) } _completedSerial = serial; + } + + Post(arm: false, null, serial); + } + + // ---- the arming thread --------------------------------------------------------------------- + + private void Post(bool arm, Record? record, ulong completed) + { + if (_thread is null) + { + Process(arm, record, completed); + return; + } + + lock (_requests) + { + _requests.Enqueue((arm, record, completed)); + Monitor.Pulse(_requests); + } + } + + private void Run() + { + while (true) + { + (bool Arm, Record? Record, ulong Completed) request; + lock (_requests) + { + while (_requests.Count == 0 && !_stopping) + { + Monitor.Wait(_requests); + } + + if (_stopping) + { + return; + } + + request = _requests.Dequeue(); + } + + try + { + Process(request.Arm, request.Record, request.Completed); + } + catch (Exception exception) + { + Console.Error.WriteLine($"[METAL-V2][OVERLAP-INFLIGHT][ERROR] {(request.Arm ? "arm" : "disarm")}: {exception}"); + } + } + } + + private void Process(bool arm, Record? record, ulong completed) + { + if (arm) + { + var started = _clock(); + lock (_gate) + { + if (record!.Serial <= _completedSerial || record.Window is not { } window) + { + return; + } + + var masks = new Dictionary<(ulong, bool), PageMask>(); + ArmRecordLocked(window, record, masks); + Apply(masks, add: true); + window.ArmTicks += _clock() - started; + } + + return; + } + + lock (_gate) + { var masks = new Dictionary<(ulong, bool), PageMask>(); for (var index = 0; index < _inFlight.Count;) { - var record = _inFlight[index]; - if (record.Serial > serial) + var done = _inFlight[index]; + if (done.Serial > completed) { index++; continue; } _inFlight.RemoveAt(index); - foreach (var page in record.OwnedPages) + done.Disarmed = true; + foreach (var page in done.OwnedPages) { - if (_pages.TryGetValue(page, out var state) && state.MaxSerial == record.Serial && state.CommandBuffers is null) + ref var state = ref System.Runtime.InteropServices.CollectionsMarshal.GetValueRefOrNullRef(_pages, page); + if (!System.Runtime.CompilerServices.Unsafe.IsNullRef(ref state) && state.MaxSerial == done.Serial && (state.Flags & CommandBuffer) == 0) { - Unwatch(page, state, masks); + Unwatch(page, ref state, masks); } } } @@ -327,22 +485,18 @@ public void OnCompleted(ulong serial) private void ArmRecordLocked(Window window, Record record, Dictionary<(ulong, bool), PageMask> masks) { record.Armed = true; - window.RecordsArmed++; - window.MaxArmedSerial = Math.Max(window.MaxArmedSerial, record.Serial); - for (var index = 0; index < record.Reads.Count; index++) + foreach (var read in record.Reads) { - var read = record.Reads[index]; - AddRange(window, record, index, read.Address, read.Size, write: false, masks); + AddRange(window, record, read.Address, read.Size, write: false, masks); } - for (var index = 0; index < record.Writes.Count; index++) + foreach (var write in record.Writes) { - var write = record.Writes[index]; - AddRange(window, record, index, write.Address, write.Size, write: true, masks); + AddRange(window, record, write.Address, write.Size, write: true, masks); } } - private void AddRange(Window window, Record record, int index, ulong address, ulong size, bool write, Dictionary<(ulong, bool), PageMask> masks) + private void AddRange(Window window, Record record, ulong address, ulong size, bool write, Dictionary<(ulong, bool), PageMask> masks) { if (size > HugeRangeBytes) { @@ -353,7 +507,8 @@ private void AddRange(Window window, Record record, int index, ulong address, ul var end = address + size; for (var page = address & ~(PageBytes - 1); page < end; page += PageBytes) { - if (!_pages.TryGetValue(page, out var state)) + ref var state = ref System.Runtime.InteropServices.CollectionsMarshal.GetValueRefOrNullRef(_pages, page); + if (System.Runtime.CompilerServices.Unsafe.IsNullRef(ref state)) { if (window.ArmedPages >= _maxArmedPages) { @@ -361,76 +516,68 @@ private void AddRange(Window window, Record record, int index, ulong address, ul continue; } - state = new PageState(); - _pages[page] = state; + state = ref System.Runtime.InteropServices.CollectionsMarshal.GetValueRefOrAddDefault(_pages, page, out _); _anyPages = true; } if (!ReferenceEquals(state.Window, window)) { state.Window = window; - state.Faulted = false; - state.Refs.Clear(); - state.RefsCapped = false; - state.InRead = state.InWrite = false; + state.Flags &= WriteWatched | ReadWatched | CommandBuffer; } - if (state.Refs.Count < MaxRefsPerPage) - { - state.Refs.Add((record, index, write)); - } - else if (!state.RefsCapped) - { - state.RefsCapped = true; - window.RefsCapped++; - } - - if (write) state.InWrite = true; - else state.InRead = true; + state.Flags |= write ? InWrite : InRead; if (record.Serial > state.MaxSerial) { state.MaxSerial = record.Serial; record.OwnedPages.Add(page); } - if (state.Faulted) + if ((state.Flags & Faulted) == 0) { - continue; + Watch(window, page, ref state, masks, count: true); } - - Watch(window, page, state, masks); } } - private void Watch(Window window, ulong page, PageState state, Dictionary<(ulong, bool), PageMask> masks) + private void Watch(Window window, ulong page, ref PageState state, Dictionary<(ulong, bool), PageMask> masks, bool count) { - var wasWatched = state.WriteWatched || state.ReadWatched; - if (state.InWrite && _armReads && !state.ReadWatched) + var wasWatched = (state.Flags & (WriteWatched | ReadWatched)) != 0; + if ((state.Flags & InWrite) != 0 && _armReads && (state.Flags & ReadWatched) == 0) { if (_watches.IsReadWatched(page)) { - if (!wasWatched) + if (!wasWatched && count) { window.SkippedReadWatched++; } } else { - state.ReadWatched = true; - window.ReadArmedPages++; + state.Flags |= ReadWatched; + if (count) + { + window.ReadArmedPages++; + } + SetMask(masks, page, reads: true); } } - if (!state.ReadWatched && !state.WriteWatched) + if ((state.Flags & (WriteWatched | ReadWatched)) == 0) { - state.WriteWatched = true; + state.Flags |= WriteWatched; SetMask(masks, page, reads: false); } if (!wasWatched) { - window.ArmedPages++; + // A page watched again starts a new count of answered retries. + _retries.Remove(page); + if (count) + { + window.ArmedPages++; + } } } @@ -439,27 +586,20 @@ private void ArmCommandBufferLocked(Window window, ulong address, ulong bytes) var masks = new Dictionary<(ulong, bool), PageMask>(); for (var page = address & ~(PageBytes - 1); page < address + bytes; page += PageBytes) { - if (!_pages.TryGetValue(page, out var state)) - { - state = new PageState { Window = window }; - _pages[page] = state; - _anyPages = true; - } - - (state.CommandBuffers ??= new()).Add((address, bytes)); - if (!state.WriteWatched && !state.ReadWatched && !(state.Faulted && ReferenceEquals(state.Window, window))) + ref var state = ref System.Runtime.InteropServices.CollectionsMarshal.GetValueRefOrAddDefault(_pages, page, out _); + _anyPages = true; + state.Flags |= CommandBuffer; + if ((state.Flags & (WriteWatched | ReadWatched)) == 0) { if (!ReferenceEquals(state.Window, window)) { state.Window = window; - state.Refs.Clear(); - state.InRead = state.InWrite = false; + state.Flags &= CommandBuffer; } - state.Faulted = false; - state.WriteWatched = true; + state.Flags = (byte)((state.Flags & ~Faulted) | WriteWatched); + _retries.Remove(page); window.CommandBufferPages++; - window.ArmedPages++; SetMask(masks, page, reads: false); } } @@ -467,19 +607,19 @@ private void ArmCommandBufferLocked(Window window, ulong address, ulong bytes) Apply(masks, add: true); } - private void Unwatch(ulong page, PageState state, Dictionary<(ulong, bool), PageMask> masks) + private static void Unwatch(ulong page, ref PageState state, Dictionary<(ulong, bool), PageMask> masks) { - if (state.WriteWatched) + if ((state.Flags & WriteWatched) != 0) { SetMask(masks, page, reads: false); - state.WriteWatched = false; } - if (state.ReadWatched) + if ((state.Flags & ReadWatched) != 0) { SetMask(masks, page, reads: true); - state.ReadWatched = false; } + + state.Flags &= unchecked((byte)~(WriteWatched | ReadWatched)); } private static void SetMask(Dictionary<(ulong, bool), PageMask> masks, ulong page, bool reads) @@ -514,12 +654,13 @@ public bool TryHandleFault(FaultKind kind, ulong address, out bool stillBlocked) var page = address & ~(PageBytes - 1); lock (_gate) { - if (!_pages.TryGetValue(page, out var state)) + ref var state = ref System.Runtime.InteropServices.CollectionsMarshal.GetValueRefOrNullRef(_pages, page); + if (System.Runtime.CompilerServices.Unsafe.IsNullRef(ref state)) { return false; } - var ours = kind == FaultKind.Read ? state.ReadWatched : state.ReadWatched || state.WriteWatched; + var ours = kind == FaultKind.Read ? (state.Flags & ReadWatched) != 0 : (state.Flags & (ReadWatched | WriteWatched)) != 0; if (!ours) { // Let go already (another thread's fault, or the buffer completed) but the access met the @@ -533,19 +674,27 @@ public bool TryHandleFault(FaultKind kind, ulong address, out bool stillBlocked) _lateFaults++; return true; } + + _declined++; + Console.Error.WriteLine($"[METAL-V2][OVERLAP-INFLIGHT][WARN] page 0x{page:X}: {MaxRetriesPerPage} retries answered since it was armed, declining the fault"); } return false; } + var preRelease = false; if (state.Window is { } window) { - Attribute(window, state, address, write: kind != FaultKind.Read, now); + preRelease = Attribute(window, ref state, address, write: kind != FaultKind.Read, now); + if (preRelease) + { + window.PreReleasePages.Add(page); + } } - state.Faulted = true; + state.Flags |= Faulted; var masks = new Dictionary<(ulong, bool), PageMask>(); - Unwatch(page, state, masks); + Unwatch(page, ref state, masks); Apply(masks, add: false); stillBlocked = _watches.StillBlocks(page, kind); return true; @@ -566,7 +715,7 @@ public void NoteManagedWrite(ulong address, ulong size) var pages = 0; for (var page = address & ~(PageBytes - 1); page < end && pages < 4096; page += PageBytes, pages++) { - if (_pages.TryGetValue(page, out var state) && (state.WriteWatched || state.ReadWatched) && state.Window is { } window) + if (_pages.TryGetValue(page, out var state) && (state.Flags & (WriteWatched | ReadWatched)) != 0 && state.Window is { } window) { window.Managed++; } @@ -576,6 +725,11 @@ public void NoteManagedWrite(ulong address, ulong size) internal int Era(Window window, ulong serial) { + if (window.PresentSerial == 0) + { + return 3; + } + if (serial > window.PresentSerial) { var after = serial - window.PresentSerial; @@ -592,105 +746,182 @@ internal int Era(Window window, ulong serial) return position <= 1.0 / 3 ? 1 : position <= 2.0 / 3 ? 2 : 3; } - private void Attribute(Window window, PageState state, ulong address, bool write, long now) + private static void BuildIndex(Record record) { - var ms = (now - window.GateTicks) * 1000.0 / Stopwatch.Frequency; - if (write) + if (record.ReadIndex is not null) { - foreach (var reference in state.Refs) + return; + } + + static ((ulong, ulong, int)[], ulong[]) Index(IEnumerable<(ulong Start, ulong End, int Index)> ranges) + { + var sorted = ranges.OrderBy(range => range.Start).ToArray(); + var maxEnd = new ulong[sorted.Length]; + ulong running = 0; + for (var index = 0; index < sorted.Length; index++) { - if (reference.Write) - { - continue; - } + running = Math.Max(running, sorted[index].End); + maxEnd[index] = running; + } + + return (sorted, maxEnd); + } - var read = reference.Record.Reads[reference.Index]; - window.RsPageRanges.Add((read.Address, read.Size)); + (record.ReadIndex, record.ReadMaxEnd) = Index(record.Reads.Select((read, index) => (read.Address, read.Address + read.Size, index))); + (record.WriteIndex, record.WriteMaxEnd) = Index(record.Writes.Select((write, index) => (write.Address, write.Address + write.Size, index))); + } + + // The newest range of the record that holds the byte, or -1. + private static int Find((ulong Start, ulong End, int Index)[] sorted, ulong[] maxEnd, ulong address) + { + int low = 0, high = sorted.Length - 1, last = -1; + while (low <= high) + { + var middle = (low + high) >> 1; + if (sorted[middle].Start <= address) + { + last = middle; + low = middle + 1; } + else + { + high = middle - 1; + } + } - foreach (var reference in state.Refs) + for (var index = last; index >= 0 && maxEnd[index] > address; index--) + { + if (sorted[index].End > address) { - if (reference.Write) - { - continue; - } + return sorted[index].Index; + } + } - var read = reference.Record.Reads[reference.Index]; - if (address >= read.Address && address - read.Address < read.Size) - { - window.RsHit++; - window.RsHitByTag[(int)read.Tag]++; - var era = Era(window, reference.Record.Serial); - window.RsHitByEra[era]++; - window.RsHitRanges.Add((read.Address, read.Size)); - window.RsHitMs.Add(ms); - Report(window, "store_rs", address, read.Address, read.Size, TagNames[(int)read.Tag], reference.Record.Serial, era, ms, 0); - return; - } + return -1; + } + + // Returns true when the fault came before the buffer it hit was published (the page is armed again then). + private bool Attribute(Window window, ref PageState state, ulong address, bool write, long now) + { + var ms = window.GateTicks == 0 ? double.NaN : (now - window.GateTicks) * 1000.0 / Stopwatch.Frequency; + Record? readHit = null, writeHit = null; + int readIndex = -1, writeIndex = -1; + foreach (var record in window.Records) + { + if (!record.Armed) + { + continue; } - foreach (var reference in state.Refs) + BuildIndex(record); + if (readHit is null || record.Serial > readHit.Serial) { - if (!reference.Write) + var found = Find(record.ReadIndex!, record.ReadMaxEnd!, address); + if (found >= 0 && (readHit is null || record.Serial < readHit.Serial || readHit.Serial <= _completedSerial)) { - continue; + readHit = record; + readIndex = found; } + } + + var foundWrite = Find(record.WriteIndex!, record.WriteMaxEnd!, address); + if (foundWrite >= 0 && (writeHit is null || writeHit.Serial <= _completedSerial)) + { + writeHit = record; + writeIndex = foundWrite; + } + } - var written = reference.Record.Writes[reference.Index]; - if (address >= written.Address && address - written.Address < written.Size) + var owner = write ? readHit ?? writeHit : writeHit; + if (owner is null && write && (state.Flags & CommandBuffer) != 0) + { + foreach (var (bufferAddress, bytes) in _admitted) + { + if (address >= bufferAddress && address - bufferAddress < bytes) { - window.WsStoreHit++; - window.WsStoreByOrigin[written.Origin]++; - Report(window, "store_ws", address, written.Address, written.Size, OriginNames[written.Origin] + "/" + TagNames[(int)written.Tag], - reference.Record.Serial, Era(window, reference.Record.Serial), ms, written.Program); - return; + window.CbHit++; + window.CbMs.Add(ms); + Report(window, "store_cb", address, bufferAddress, bytes, "command_buffer", 0, 8, ms, 0); + return false; } } - if (state.CommandBuffers is { } buffers) + window.CbNeighbour++; + return false; + } + + var serial = owner?.Serial ?? state.MaxSerial; + if (serial <= _completedSerial) + { + window.AfterCompletion++; + return false; + } + + if (serial > _releasedSerial) + { + if (write) { - foreach (var (bufferAddress, bytes) in buffers) + window.PreReleaseStores++; + if (readHit is not null) { - if (address >= bufferAddress && address - bufferAddress < bytes) - { - window.CbHit++; - window.CbMs.Add(ms); - Report(window, "store_cb", address, bufferAddress, bytes, "command_buffer", 0, 8, ms, 0); - return; - } + window.PreStoreByTag[(int)readHit.Reads[readIndex].Tag]++; } } + else + { + window.PreReleaseLoads++; + } - if (state.InRead) window.RsNeighbour++; - else if (state.InWrite) window.WsStoreNeighbour++; - else window.CbNeighbour++; - return; + return true; } - foreach (var reference in state.Refs) + if (write) { - if (!reference.Write) + if (readHit is not null) { - continue; + var read = readHit.Reads[readIndex]; + window.RsHit++; + window.RsHitByTag[(int)read.Tag]++; + var era = Era(window, readHit.Serial); + window.RsHitByEra[era]++; + window.RsHitRanges.Add((read.Address, read.Size)); + window.RsHitMs.Add(ms); + Report(window, "store_rs", address, read.Address, read.Size, TagNames[(int)read.Tag], readHit.Serial, era, ms, 0); + return false; } - var written = reference.Record.Writes[reference.Index]; - if (address >= written.Address && address - written.Address < written.Size) + if (writeHit is not null) { - window.WsLoadHit++; - window.WsLoadByOrigin[written.Origin]++; - window.WsLoadByTag[(int)written.Tag]++; - var era = Era(window, reference.Record.Serial); - window.WsLoadByEra[era]++; - window.WsLoadRanges.Add((written.Address, written.Size)); - window.WsLoadMs.Add(ms); - Report(window, "load_ws", address, written.Address, written.Size, OriginNames[written.Origin] + "/" + TagNames[(int)written.Tag], - reference.Record.Serial, era, ms, written.Program); - return; + var written = writeHit.Writes[writeIndex]; + window.WsStoreHit++; + window.WsStoreByOrigin[written.Origin]++; + Report(window, "store_ws", address, written.Address, written.Size, OriginNames[written.Origin] + "/" + TagNames[(int)written.Tag], + writeHit.Serial, Era(window, writeHit.Serial), ms, written.Program); + return false; } + + if ((state.Flags & InRead) != 0) window.RsNeighbour++; + else window.WsStoreNeighbour++; + return false; + } + + if (writeHit is not null) + { + var written = writeHit.Writes[writeIndex]; + window.WsLoadHit++; + window.WsLoadByOrigin[written.Origin]++; + window.WsLoadByTag[(int)written.Tag]++; + var era = Era(window, writeHit.Serial); + window.WsLoadByEra[era]++; + window.WsLoadRanges.Add((written.Address, written.Size)); + window.WsLoadMs.Add(ms); + Report(window, "load_ws", address, written.Address, written.Size, OriginNames[written.Origin] + "/" + TagNames[(int)written.Tag], + writeHit.Serial, era, ms, written.Program); + return false; } window.WsLoadNeighbour++; + return false; } private void Report(Window window, string what, ulong address, ulong rangeAddress, ulong rangeSize, string kind, ulong serial, int era, double ms, ulong program) @@ -704,7 +935,7 @@ private void Report(Window window, string what, ulong address, ulong rangeAddres var offset = serial == 0 ? "-" : ((long)serial - (long)window.PresentSerial).ToString(CultureInfo.InvariantCulture); Console.Error.WriteLine(string.Create(CultureInfo.InvariantCulture, $"[METAL-V2][OVERLAP-INFLIGHT-HIT] frame={window.Index} {what} addr=0x{address:X} range=0x{rangeAddress:X}+0x{rangeSize:X} kind={kind} " + - $"serial_vs_present={offset} era={EraNames[era]} ms_after_gate={ms:F2} program=0x{program:X16}")); + $"serial_vs_present={offset} era={EraNames[era]} ms_after_gate={ms:F2} completed_vs_present={(long)_completedSerial - (long)window.PresentSerial} program=0x{program:X16}")); } // ---- windows ------------------------------------------------------------------------------ @@ -714,7 +945,7 @@ private void FinalizeIfDoneLocked() for (var index = 0; index < _windows.Count;) { var window = _windows[index]; - if (!window.Closed || window.MaxArmedSerial > _completedSerial) + if (!window.Closed || window.Records.Any(record => !record.Disarmed)) { index++; continue; @@ -727,14 +958,14 @@ private void FinalizeIfDoneLocked() } // Pages of windows finalized over half a second ago that hold no watch: a fault that raced their - // release has been retried by then, so they are forgotten (stats-window thread). + // release has been retried by then, so they are forgotten. private void PruneLocked(long now) { var stale = new List(); foreach (var pair in _pages) { var state = pair.Value; - if (!state.ReadWatched && !state.WriteWatched && state.CommandBuffers is null && + if ((state.Flags & (ReadWatched | WriteWatched | CommandBuffer)) == 0 && (state.Window is null || (state.Window.FinalizedTicks != 0 && now - state.Window.FinalizedTicks > Stopwatch.Frequency / 2))) { stale.Add(pair.Key); @@ -760,14 +991,15 @@ internal IReadOnlyList TakeFinished() } } - /// One line per stats window: per sampled frame, mean (max) and time percentiles from the gate. + /// One line per stats window: per sampled frame, mean/max and time percentiles from the gate. public string? TakeWindowLine() { var windows = TakeFinished(); - long late; + long late, declined; lock (_gate) { late = _lateFaults; + declined = _declined; PruneLocked(_clock()); } @@ -797,29 +1029,34 @@ string Split(Func pick, string[] names) return builder.ToString(); } - string P(Func> pick) - { - var values = windows.SelectMany(pick).ToList(); - return FrameOverlapTracker.Percentiles(values, culture); - } + string P(Func> pick) => + FrameOverlapTracker.Percentiles(windows.SelectMany(pick).Where(value => !double.IsNaN(value)).ToList(), culture); - string FirstP(Func> pick) - { - var values = windows.Where(w => pick(w).Count != 0).Select(w => pick(w).Min()).ToList(); - return FrameOverlapTracker.Percentiles(values, culture); - } + string FirstP(Func> pick) => + FrameOverlapTracker.Percentiles(windows.Where(w => pick(w).Count != 0).Select(w => pick(w).Min()).Where(value => !double.IsNaN(value)).ToList(), culture); return string.Create(culture, $"[METAL-V2][OVERLAP-INFLIGHT] frames={n} armed_pages={M(w => w.ArmedPages)} read_armed={M(w => w.ReadArmedPages)} " + - $"cb_pages={M(w => w.CommandBufferPages)} buffers_armed={M(w => w.RecordsArmed)} arm_ms={M(w => w.ArmTicks * 1000.0 / Stopwatch.Frequency)} " + - $"cap_skipped={M(w => w.CapSkipped)} skipped_read_watched={M(w => w.SkippedReadWatched)} huge={M(w => w.HugeRanges)} refs_capped={M(w => w.RefsCapped)} " + + $"cb_pages={M(w => w.CommandBufferPages)} buffers={M(w => w.Records.Count)} late_buffers={M(w => w.LateRecords)} " + + $"arm_ms={M(w => w.ArmTicks * 1000.0 / Stopwatch.Frequency)} cap_skipped={M(w => w.CapSkipped)} skipped_read_watched={M(w => w.SkippedReadWatched)} " + + $"huge={M(w => w.HugeRanges)} rearmed={M(w => w.Rearmed)} " + + $"| pre_release stores={M(w => w.PreReleaseStores)} by_tag=[{Split(w => w.PreStoreByTag, TagNames)}] loads={M(w => w.PreReleaseLoads)} after_completion={M(w => w.AfterCompletion)} " + $"| 1a store_rs_hit_pages={M(w => w.RsHit)} ranges={M(w => w.RsHitRanges.Count)} hit_range_mb={Mb(w => w.RsHitRanges)} " + - $"page_range_mb={Mb(w => w.RsPageRanges)} nb_pages={M(w => w.RsNeighbour)} by_tag=[{Split(w => w.RsHitByTag, TagNames)}] " + + $"nb_pages={M(w => w.RsNeighbour)} by_tag=[{Split(w => w.RsHitByTag, TagNames)}] " + $"by_era=[{Split(w => w.RsHitByEra, EraNames)}] first_ms={FirstP(w => w.RsHitMs)} all_ms={P(w => w.RsHitMs)} " + $"| 1b store_cb_hit_pages={M(w => w.CbHit)} nb={M(w => w.CbNeighbour)} first_ms={FirstP(w => w.CbMs)} " + $"| ws store_hit_pages={M(w => w.WsStoreHit)} nb={M(w => w.WsStoreNeighbour)} by_origin=[{Split(w => w.WsStoreByOrigin, OriginNames)}] " + $"| 2 load_ws_hit_pages={M(w => w.WsLoadHit)} ranges={M(w => w.WsLoadRanges.Count)} mb={Mb(w => w.WsLoadRanges)} nb_pages={M(w => w.WsLoadNeighbour)} " + $"by_origin=[{Split(w => w.WsLoadByOrigin, OriginNames)}] by_tag=[{Split(w => w.WsLoadByTag, TagNames)}] by_era=[{Split(w => w.WsLoadByEra, EraNames)}] " + - $"first_ms={FirstP(w => w.WsLoadMs)} all_ms={P(w => w.WsLoadMs)} | managed={M(w => w.Managed)} late_faults={late}"); + $"first_ms={FirstP(w => w.WsLoadMs)} all_ms={P(w => w.WsLoadMs)} | managed={M(w => w.Managed)} late_faults={late} declined={declined}"); + } + + public void Dispose() + { + lock (_requests) + { + _stopping = true; + Monitor.PulseAll(_requests); + } } } diff --git a/tests/SharpEmu.Libs.Tests/HLE/InFlightOverlapTrackerTests.cs b/tests/SharpEmu.Libs.Tests/HLE/InFlightOverlapTrackerTests.cs index f427c78c1..73456fd00 100644 --- a/tests/SharpEmu.Libs.Tests/HLE/InFlightOverlapTrackerTests.cs +++ b/tests/SharpEmu.Libs.Tests/HLE/InFlightOverlapTrackerTests.cs @@ -7,9 +7,10 @@ namespace SharpEmu.Libs.Tests.HLE; /// -/// The in-flight overlap diagnostic without a page guard: a sampled frame's gate arms the released buffers the -/// GPU has not completed (reads for stores, writes for loads), each fault is attributed by byte and let go, -/// a submission's command buffer is watched until it is walked, and every watch is given back. +/// The in-flight overlap diagnostic without a page guard or thread: a sampled frame's buffers are armed as they +/// commit (reads for stores, writes for loads), a fault is attributed by byte and counted as the race only between +/// the buffer's publication and its completion, a page touched before the publication is armed again at it, a +/// submission's command buffer is watched until it is walked, and every watch is given back. /// public sealed class InFlightOverlapTrackerTests { @@ -49,7 +50,7 @@ private void Change(ulong blockBase, PageMask pages, bool reads, int delta) private long _now = 1; - private InFlightOverlapTracker Create(FakeWatches watches, int every = 1) => new(watches, () => _now, every, 1000, armReads: true); + private InFlightOverlapTracker Create(FakeWatches watches, int every = 1) => new(watches, () => _now, every, 1000, armReads: true, startThread: false); // Present at serial 1, then buffer 2 reads a constant range and has an occlusion result copied into guest memory. private static void RecordFrame(InFlightOverlapTracker tracker) @@ -103,33 +104,37 @@ public void TheGateArmsReleasedBuffersStillRunningReadsForStoresAndWritesForLoad } [Fact] - public void NothingIsArmedBeforeTheGateAndCompletionGivesEveryWatchBack() + public void ABufferIsArmedAtCommitAndCompletionGivesEveryWatchBack() { var watches = new FakeWatches(); var tracker = Create(watches); RecordFrame(tracker); + Assert.Equal(2, watches.Live); - // Present + 1 is not the gate. - tracker.OnRelease(2); - Assert.Equal(0, watches.Live); + tracker.OnCompleted(2); - tracker.OnRelease(3); - Assert.Equal(2, watches.Live); - tracker.OnCompleted(3); Assert.Equal(0, watches.Live); } [Fact] - public void ACompletedBufferIsNotArmed() + public void AStoreBeforeThePublicationIsNotTheRaceAndThePageIsArmedAgainAtIt() { var watches = new FakeWatches(); var tracker = Create(watches); RecordFrame(tracker); - tracker.OnCompleted(2); + Assert.True(tracker.TryHandleFault(FaultKind.Write, 0x100010, out _)); + Assert.Equal(0, watches.Counts.GetValueOrDefault((0x100000UL, false))); tracker.OnRelease(3); + Assert.Equal(1, watches.Counts.GetValueOrDefault((0x100000UL, false))); + Assert.True(tracker.TryHandleFault(FaultKind.Write, 0x100020, out _)); - Assert.Equal(0, watches.Live); + tracker.OnCompleted(3); + CloseWindow(tracker); + var line = tracker.TakeWindowLine()!; + Assert.Contains("pre_release stores=1.0/1 by_tag=[constant:1.0]", line); + Assert.Contains("rearmed=1.0/1", line); + Assert.Contains("store_rs_hit_pages=1.0/1", line); } [Fact] @@ -146,7 +151,7 @@ public void AStoreBesideTheRangeOnItsPageIsANeighbourNotAHit() var line = tracker.TakeWindowLine()!; Assert.Contains("store_rs_hit_pages=0.0/0", line); - Assert.Contains("ranges=0.0/0 hit_range_mb=0.000 page_range_mb=0.000 nb_pages=1.0/1", line); + Assert.Contains("ranges=0.0/0 hit_range_mb=0.000 nb_pages=1.0/1", line); } [Fact] @@ -174,7 +179,7 @@ public void ACommandBufferAdmittedAndNotWalkedIsWatchedUntilItIsWalked() public void AnUnsampledFrameArmsNothing() { var watches = new FakeWatches(); - var tracker = Create(watches, every: 2); + var tracker = Create(watches, every: 4); RecordFrame(tracker); tracker.OnRelease(3); From 7a9d09b1ffa1ee1902f4919b808c5712f8d669a9 Mon Sep 17 00:00:00 2001 From: kuba Date: Mon, 16 Nov 2026 10:39:07 +0000 Subject: [PATCH 133/178] [Diag] Frame-overlap in-flight census: the writer op of an early-read range and its inputs' last writers In the in-flight mode, each draw or dispatch the worker records is now an op (closed when its Draw*/Dispatch*/TryDispatchIndirect call returns) carrying its programs (every stage bound for it), the guest queue whose submission was being walked, its in-place reads and GPU writes, and, for the census only (never armed), the GPU images it samples and the colour, depth or storage images it writes, by guest address. When the guest loads a GPU-written range after its buffer was published and before it completed, the first time each (range, write program, op program) is seen (80 at most) prints one [METAL-V2][OVERLAP-CENSUS] line: the range, its origin and tag, the bytes before the GPU wrote them, and the writer (serial against the frame's present, op index in its buffer, draw or dispatch, queue, programs); then each of the op's inputs (24 at most) with its last writer in stream order within the window's buffers (program, serial, op, how: storage, copy, image target...), or none_in_window; and, once the buffer completes, the bytes the GPU wrote. Default path: the existing static readonly switch; the op scope is an empty struct when off. --- .../GpuMemory/FrameOverlapDiagnostic.cs | 35 +++ .../GpuMemory/InFlightOverlapTracker.cs | 199 +++++++++++++++++- .../Gpu/GpuCommands/CommandStreamQueue.cs | 5 + .../V2/MetalRenderHost.Descriptors.cs | 10 + .../V2/MetalRenderHost.Images.cs | 10 + .../V2/MetalRenderHost.Rendering.cs | 6 + .../SharpEmu.Gpu.Metal/V2/MetalRenderHost.cs | 4 + .../HLE/InFlightOverlapTrackerTests.cs | 32 +++ 8 files changed, 296 insertions(+), 5 deletions(-) diff --git a/src/SharpEmu.HLE/GpuMemory/FrameOverlapDiagnostic.cs b/src/SharpEmu.HLE/GpuMemory/FrameOverlapDiagnostic.cs index 639c6cb76..95c39bf54 100644 --- a/src/SharpEmu.HLE/GpuMemory/FrameOverlapDiagnostic.cs +++ b/src/SharpEmu.HLE/GpuMemory/FrameOverlapDiagnostic.cs @@ -149,6 +149,41 @@ public void Dispose() } } + public delegate bool GuestReader(ulong address, Span destination); + + /// The GPU host's view of guest memory, for the in-flight census values (bytes before and after the GPU wrote them). + public static void SetReader(GuestReader reader) + { + if (InFlight is { } inflight) + { + inflight.Reader = reader; + } + } + + [ThreadStatic] + private static int t_queue; + + /// The guest queue whose submission the calling (worker) thread is walking. + public static void SetQueue(int queue) => t_queue = queue; + + public static void NoteOpProgram(ulong hash) => InFlight?.NoteOpProgram(hash); + + public static void NoteImage(ulong address, ulong size, bool written) => InFlight?.NoteImage(address, size, written); + + /// While alive, a draw or dispatch is being recorded; its end closes the in-flight census op. + public static OpScope Op(bool dispatch) => new(Enabled && InFlight is not null, dispatch); + + public readonly struct OpScope(bool active, bool dispatch) : IDisposable + { + public void Dispose() + { + if (active) + { + InFlight?.EndOp(dispatch, t_queue); + } + } + } + /// The worker committed a command buffer (: it holds a flip). public static void OnProbeCommit(ulong serial, bool present) => InFlight?.OnCommit(serial, present); diff --git a/src/SharpEmu.HLE/GpuMemory/InFlightOverlapTracker.cs b/src/SharpEmu.HLE/GpuMemory/InFlightOverlapTracker.cs index 7cc7d23c3..07ca23a5a 100644 --- a/src/SharpEmu.HLE/GpuMemory/InFlightOverlapTracker.cs +++ b/src/SharpEmu.HLE/GpuMemory/InFlightOverlapTracker.cs @@ -63,9 +63,15 @@ internal sealed class Record public ulong Serial; public Window? Window; public bool Armed, Disarmed, Late; - public readonly List<(ulong Address, ulong Size, OverlapTag Tag)> Reads = new(); - public readonly List<(ulong Address, ulong Size, int Origin, OverlapTag Tag, ulong Program)> Writes = new(); + public readonly List<(ulong Address, ulong Size, OverlapTag Tag, int Op)> Reads = new(); + public readonly List<(ulong Address, ulong Size, int Origin, OverlapTag Tag, ulong Program, int Op)> Writes = new(); public readonly List OwnedPages = new(); + + // Census only (never armed): GPU images an op samples and the images it renders or stores into, + // by guest address, and each op's kind, guest queue and programs. + public readonly List<(ulong Address, ulong Size, int Op)> ImageReads = new(), ImageWrites = new(); + public readonly List<(bool Dispatch, int Queue, ulong[] Programs)> Ops = new(); + public List<(ulong Address, ulong Size)>? CensusRanges; public (ulong Start, ulong End, int Index)[]? ReadIndex, WriteIndex; public ulong[]? ReadMaxEnd, WriteMaxEnd; } @@ -150,7 +156,7 @@ public void MarkRead(ulong address, ulong size, OverlapTag tag) lock (_gate) { - _open.Reads.Add((address, size, tag)); + _open.Reads.Add((address, size, tag, _open.Ops.Count)); } } @@ -163,10 +169,51 @@ public void NoteWrite(ulong address, ulong size, OverlapWrite origin, OverlapTag lock (_gate) { - _open.Writes.Add((address, size, (int)origin, tag, program)); + _open.Writes.Add((address, size, (int)origin, tag, program, _open.Ops.Count)); + } + } + + private readonly List _opPrograms = new(); + + /// A program bound for the draw or dispatch being recorded. + public void NoteOpProgram(ulong hash) + { + lock (_gate) + { + if (!_opPrograms.Contains(hash)) + { + _opPrograms.Add(hash); + } + } + } + + /// A GPU image the op being recorded samples (: renders or stores into). + public void NoteImage(ulong address, ulong size, bool written) + { + if (address == 0 || size == 0) + { + return; + } + + lock (_gate) + { + (written ? _open.ImageWrites : _open.ImageReads).Add((address, size, _open.Ops.Count)); + } + } + + /// The draw or dispatch being recorded ended: what was noted since the last one is its op. + public void EndOp(bool dispatch, int queue) + { + lock (_gate) + { + _open.Ops.Add((dispatch, queue, _opPrograms.ToArray())); + _opPrograms.Clear(); } } + /// Reads guest bytes for the census values (set by the GPU host; null: no values). + public FrameOverlapDiagnostic.GuestReader? Reader { get; set; } + private Window WindowFor(long frame) { foreach (var window in _windows) @@ -193,7 +240,8 @@ public void OnCommit(ulong serial, bool present) record.Serial = serial; // Frame F (F % K == 0) arms its own buffers (committed while F-1 presents were seen) and its post-flip ones. long? frame = _frames % _sampleEvery == 0 ? _frames : (_frames + 1) % _sampleEvery == 0 ? _frames + 1 : null; - if (frame is { } index && index > 0 && serial > _completedSerial && (record.Reads.Count != 0 || record.Writes.Count != 0)) + if (frame is { } index && index > 0 && serial > _completedSerial && + (record.Reads.Count != 0 || record.Writes.Count != 0 || record.ImageWrites.Count != 0 || record.ImageReads.Count != 0)) { record.Window = WindowFor(index); record.Window.Records.Add(record); @@ -465,6 +513,14 @@ private void Process(bool arm, Record? record, ulong completed) _inFlight.RemoveAt(index); done.Disarmed = true; + if (done.CensusRanges is { } ranges) + { + foreach (var (address, size) in ranges) + { + Console.Error.WriteLine(string.Create(CultureInfo.InvariantCulture, + $"[METAL-V2][OVERLAP-CENSUS] value serial={done.Serial} range=0x{address:X}+0x{size:X} after_gpu={Bytes(address, size)}")); + } + } foreach (var page in done.OwnedPages) { ref var state = ref System.Runtime.InteropServices.CollectionsMarshal.GetValueRefOrNullRef(_pages, page); @@ -917,6 +973,7 @@ private bool Attribute(Window window, ref PageState state, ulong address, bool w window.WsLoadMs.Add(ms); Report(window, "load_ws", address, written.Address, written.Size, OriginNames[written.Origin] + "/" + TagNames[(int)written.Tag], writeHit.Serial, era, ms, written.Program); + Census(window, writeHit, writeIndex, address, era, ms); return false; } @@ -924,6 +981,138 @@ private bool Attribute(Window window, ref PageState state, ulong address, bool w return false; } + private const int CensusWriters = 80; + private const int CensusInputs = 24; + private readonly HashSet<(ulong, ulong, ulong)> _censused = new(); + + private string Bytes(ulong address, ulong size) + { + if (Reader is not { } reader) + { + return "-"; + } + + Span bytes = stackalloc byte[32]; + var length = (int)Math.Min(32UL, size); + return reader(address, bytes[..length]) ? Convert.ToHexString(bytes[..length]) : "unreadable"; + } + + private static string Programs(ulong[] programs) => string.Join(",", programs.Select(program => program.ToString("X16", CultureInfo.InvariantCulture))); + + private string DescribeOp(Window window, Record record, int op) + { + var position = $"op={op}/{record.Ops.Count}"; + if (op >= record.Ops.Count) + { + return $"serial={record.Serial} vs_present={(long)record.Serial - (long)window.PresentSerial} {position} kind=packet_or_unended"; + } + + var (dispatch, queue, programs) = record.Ops[op]; + return $"serial={record.Serial} vs_present={(long)record.Serial - (long)window.PresentSerial} {position} kind={(dispatch ? "dispatch" : "draw")} " + + $"queue={queue} programs=[{Programs(programs)}]"; + } + + // The newest write in stream order before (record, op) that overlaps the range, within the window's buffers. + internal string LastWriterOf(long frame, ulong serial, int op, ulong address, ulong size) + { + lock (_gate) + { + var window = _windows.Concat(_done).First(candidate => candidate.Index == frame); + return LastWriter(window, window.Records.First(record => record.Serial == serial), op, address, size); + } + } + + internal Record RecordOf(long frame, ulong serial) + { + lock (_gate) + { + return _windows.Concat(_done).First(candidate => candidate.Index == frame).Records.First(record => record.Serial == serial); + } + } + + private string LastWriter(Window window, Record record, int op, ulong address, ulong size) + { + var end = address + size; + var start = window.Records.IndexOf(record); + for (var at = start; at >= 0; at--) + { + var candidate = window.Records[at]; + var limit = ReferenceEquals(candidate, record) ? op : int.MaxValue; + (int Op, string How, ulong Program)? best = null; + foreach (var write in candidate.Writes) + { + if (write.Op < limit && write.Address < end && address < write.Address + write.Size && (best is null || write.Op >= best.Value.Op)) + { + best = (write.Op, OriginNames[write.Origin] + "/" + TagNames[(int)write.Tag], write.Program); + } + } + + foreach (var image in candidate.ImageWrites) + { + if (image.Op < limit && image.Address < end && address < image.Address + image.Size && (best is null || image.Op >= best.Value.Op)) + { + best = (image.Op, "image_target", 0); + } + } + + if (best is { } found) + { + return $"last_writer {DescribeOp(window, candidate, found.Op)} how={found.How} write_program={found.Program:X16}"; + } + } + + return "last_writer=none_in_window (an earlier frame, the CPU, or a GPU image never written by these buffers)"; + } + + private void Census(Window window, Record record, int writeIndex, ulong address, int era, double ms) + { + var written = record.Writes[writeIndex]; + var programs = written.Op < record.Ops.Count ? record.Ops[written.Op].Programs : []; + var key = (written.Address, written.Program, programs.Length == 0 ? 0 : programs[0]); + if (_censused.Count >= CensusWriters || !_censused.Add(key)) + { + return; + } + + (record.CensusRanges ??= new()).Add((written.Address, written.Size)); + var culture = CultureInfo.InvariantCulture; + Console.Error.WriteLine(string.Create(culture, + $"[METAL-V2][OVERLAP-CENSUS] frame={window.Index} load=0x{address:X} range=0x{written.Address:X}+0x{written.Size:X} " + + $"how={OriginNames[written.Origin]}/{TagNames[(int)written.Tag]} write_program={written.Program:X16} era={EraNames[era]} ms_after_gate={ms:F2} " + + $"completed_vs_present={(long)_completedSerial - (long)window.PresentSerial} before_gpu={Bytes(written.Address, written.Size)} " + + $"writer {DescribeOp(window, record, written.Op)}")); + var inputs = 0; + var seen = new HashSet(); + foreach (var read in record.Reads) + { + if (read.Op != written.Op || !seen.Add(read.Address) || inputs++ >= CensusInputs) + { + continue; + } + + Console.Error.WriteLine( + $"[METAL-V2][OVERLAP-CENSUS] input 0x{read.Address:X}+0x{read.Size:X} tag={TagNames[(int)read.Tag]} " + + LastWriter(window, record, written.Op, read.Address, read.Size)); + } + + foreach (var image in record.ImageReads) + { + if (image.Op != written.Op || !seen.Add(image.Address) || inputs++ >= CensusInputs) + { + continue; + } + + Console.Error.WriteLine( + $"[METAL-V2][OVERLAP-CENSUS] input 0x{image.Address:X}+0x{image.Size:X} tag=image " + + LastWriter(window, record, written.Op, image.Address, image.Size)); + } + + if (inputs > CensusInputs) + { + Console.Error.WriteLine($"[METAL-V2][OVERLAP-CENSUS] inputs_not_listed={inputs - CensusInputs}"); + } + } + private void Report(Window window, string what, ulong address, ulong rangeAddress, ulong rangeSize, string kind, ulong serial, int era, double ms, ulong program) { if (_hitLines >= HitLines) diff --git a/src/SharpEmu.Libs/Gpu/GpuCommands/CommandStreamQueue.cs b/src/SharpEmu.Libs/Gpu/GpuCommands/CommandStreamQueue.cs index b0f88d6fa..c1d38365e 100644 --- a/src/SharpEmu.Libs/Gpu/GpuCommands/CommandStreamQueue.cs +++ b/src/SharpEmu.Libs/Gpu/GpuCommands/CommandStreamQueue.cs @@ -1672,6 +1672,11 @@ submission.Kind is not (CommandSubmissionKind.FlipPreparation or CommandSubmissi } var dsPacketsStarted = 0UL; + if (SharpEmu.HLE.GpuMemory.FrameOverlapDiagnostic.Enabled) + { + SharpEmu.HLE.GpuMemory.FrameOverlapDiagnostic.SetQueue((int)submission!.QueueId); + } + if (dsSlice) { DsCurrentSubmissionId = submission!.SubmissionId; diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Descriptors.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Descriptors.cs index 20b14b380..e5f3c16b2 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Descriptors.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Descriptors.cs @@ -663,6 +663,11 @@ private void ResolveImageBinding(MetalStageBindings prepared, ImageResource imag ? packet.Resolutions![index] : ImageRequestBuilders.Texture(words, ShapeOf(image)); var request = resolution.Request; + if (SharpEmu.HLE.GpuMemory.FrameOverlapDiagnostic.Enabled) + { + SharpEmu.HLE.GpuMemory.FrameOverlapDiagnostic.NoteImage(request.Description.Data.Address, (ulong)request.Description.Data.Size, image.Written); + } + if (prepared.MemoWanted[index]) { prepared.MemoPages[index] = _imageCache.RequestPageVersions(in request); @@ -936,6 +941,11 @@ public void BindResources(IPreparedBindings prepared) _writtenViewRanges.Clear(); using var phaseScope = SharpEmu.Libs.VideoOut.RenderPhaseProfile.MeasureDetail(SharpEmu.Libs.VideoOut.RenderPhaseProfile.Phase.ResourceBinding); var stage = (MetalStageBindings)prepared; + if (SharpEmu.HLE.GpuMemory.FrameOverlapDiagnostic.Enabled) + { + SharpEmu.HLE.GpuMemory.FrameOverlapDiagnostic.NoteOpProgram(stage.Program.Hash); + } + var info = stage.Program.Resources!.Info; var snapshot = stage.StageResources.Resources; NoteBindShape(stage, snapshot); diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Images.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Images.cs index 923205c30..097c7e674 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Images.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Images.cs @@ -31,6 +31,11 @@ public void BindRenderTarget(ResourceSlotIdentifier image) ColorAttachmentAcquisition IRenderHost.AcquireColorAttachment(in ColorTargetState target) { var request = target.Resolution.Request; + if (SharpEmu.HLE.GpuMemory.FrameOverlapDiagnostic.Enabled) + { + SharpEmu.HLE.GpuMemory.FrameOverlapDiagnostic.NoteImage(request.Description.Data.Address, (ulong)request.Description.Data.Size, written: true); + } + var imageIdentifier = target.Image; if (!_imageCache.TryGetImage(imageIdentifier, out _)) { @@ -119,6 +124,11 @@ DepthAttachmentAcquisition IRenderHost.AcquireDepthAttachment(in DepthAttachment { var resolution = depth.Target.Target; var request = resolution.Request; + if (SharpEmu.HLE.GpuMemory.FrameOverlapDiagnostic.Enabled) + { + SharpEmu.HLE.GpuMemory.FrameOverlapDiagnostic.NoteImage(request.Description.Data.Address, (ulong)request.Description.Data.Size, written: true); + } + var imageIdentifier = depth.Image; if (!_imageCache.TryGetImage(imageIdentifier, out _)) { diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Rendering.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Rendering.cs index 7f61094f0..61f531f35 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Rendering.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Rendering.cs @@ -1898,6 +1898,7 @@ private void ApplyViewportAndScissor() public void Draw(uint vertexCount, uint instanceCount, uint firstVertex, uint firstInstance) { + using var overlapOp = SharpEmu.HLE.GpuMemory.FrameOverlapDiagnostic.Op(dispatch: false); var started = DrawTimingStart(); ApplyGraphicsState(); var entry = _boundGraphicsPipeline!; @@ -1950,6 +1951,7 @@ public void Draw(uint vertexCount, uint instanceCount, uint firstVertex, uint fi void IRenderHost.DrawIndexed(uint indexCount, uint instanceCount, uint firstIndex, int vertexOffset, uint firstInstance) { + using var overlapOp = SharpEmu.HLE.GpuMemory.FrameOverlapDiagnostic.Op(dispatch: false); var started = DrawTimingStart(); if (_indexBuffer == 0) { @@ -2012,6 +2014,7 @@ void IRenderHost.DrawIndexed(uint indexCount, uint instanceCount, uint firstInde void IRenderHost.DrawIndirect(BufferBinding arguments) { + using var overlapOp = SharpEmu.HLE.GpuMemory.FrameOverlapDiagnostic.Op(dispatch: false); var started = DrawTimingStart(); // The guest's argument layout is (vertexCount, instanceCount, firstVertex, // firstInstance), which is exactly MTLDrawPrimitivesIndirectArguments. @@ -2077,6 +2080,7 @@ private unsafe bool TryForceIndirectDraw(MetalPipelineEntry entry, uint instance void IRenderHost.DrawIndexedIndirect(BufferBinding arguments) { + using var overlapOp = SharpEmu.HLE.GpuMemory.FrameOverlapDiagnostic.Op(dispatch: false); var started = DrawTimingStart(); if (_indexBuffer == 0) { @@ -2150,6 +2154,7 @@ void IRenderHost.DrawIndexedIndirect(BufferBinding arguments) public void Dispatch(uint groupsX, uint groupsY, uint groupsZ) { + using var overlapOp = SharpEmu.HLE.GpuMemory.FrameOverlapDiagnostic.Op(dispatch: true); var started = DrawTimingStart(); // A persistent-thread kernel spins on memory other work publishes, which can be what a // label copy held for the commit writes: the copy would land only after the kernel had @@ -2254,6 +2259,7 @@ private void TraceDispatchGds() // indirect counts are dispatched as the guest wrote them, as before; the order is not used. public bool TryDispatchIndirect(ulong argumentsAddress, ReadOnlySpan physicalAxisOfLogical) { + using var overlapOp = SharpEmu.HLE.GpuMemory.FrameOverlapDiagnostic.Op(dispatch: true); var range = _guestMemory.Resolve(argumentsAddress, 3 * sizeof(uint)); if (!range.IsValid) { diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.cs index 7948ee367..04a9bb3ed 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.cs @@ -196,6 +196,10 @@ public MetalRenderHost( } // SHARPEMU_DIAG_FRAME_OVERLAP=1: single-copy holds the one read-watch bit, so the diagnostic then arms writes only. SharpEmu.HLE.GpuMemory.FrameOverlapDiagnostic.Attach(pages, readWatchesShared: _singleCopy is not null); + if (SharpEmu.HLE.GpuMemory.FrameOverlapDiagnostic.Enabled) + { + SharpEmu.HLE.GpuMemory.FrameOverlapDiagnostic.SetReader((address, destination) => _guestMemory.TryPeek(address, destination)); + } if (MetalStagedRangeCache.Enabled) { _stagedRanges = new MetalStagedRangeCache( diff --git a/tests/SharpEmu.Libs.Tests/HLE/InFlightOverlapTrackerTests.cs b/tests/SharpEmu.Libs.Tests/HLE/InFlightOverlapTrackerTests.cs index 73456fd00..5829e3efe 100644 --- a/tests/SharpEmu.Libs.Tests/HLE/InFlightOverlapTrackerTests.cs +++ b/tests/SharpEmu.Libs.Tests/HLE/InFlightOverlapTrackerTests.cs @@ -202,6 +202,38 @@ public void AFaultOnAPageAlreadyLetGoIsRetriedWhileNothingElseBlocksIt() Assert.False(tracker.TryHandleFault(FaultKind.Write, 0x900000, out _)); } + [Fact] + public void ACensusFindsTheWriterOpAndTheLastWriterOfItsInputsInStreamOrder() + { + var watches = new FakeWatches(); + var tracker = Create(watches); + tracker.OnCommit(1, present: true); + // Op 0, a draw: renders the image at 0x500000. + tracker.NoteOpProgram(0xA0); + tracker.NoteImage(0x500000, 0x1000, written: true); + tracker.EndOp(dispatch: false, queue: 0); + tracker.OnCommit(2, present: false); + // Op 0 of buffer 3, a dispatch on queue 9: samples that image, reads a constant range, stores a result. + tracker.NoteOpProgram(0xB0); + tracker.NoteImage(0x500000, 0x1000, written: false); + tracker.MarkRead(0x600000, 0x40, OverlapTag.Constant); + tracker.NoteWrite(0x200000, 0x40, OverlapWrite.Storage, OverlapTag.StorageWritten, 0xB0); + tracker.EndOp(dispatch: true, queue: 9); + tracker.OnCommit(3, present: false); + tracker.OnRelease(3); + + var image = tracker.LastWriterOf(1, 3, 0, 0x500000, 0x1000); + Assert.Contains("serial=2 vs_present=1 op=0/1 kind=draw queue=0 programs=[00000000000000A0]", image); + Assert.Contains("how=image_target", image); + Assert.Contains("last_writer=none_in_window", tracker.LastWriterOf(1, 3, 0, 0x600000, 0x40)); + + // The guest loads the result before buffer 3 completes: the census keeps the range for its value. + Assert.True(tracker.TryHandleFault(FaultKind.Read, 0x200010, out _)); + Assert.Single(tracker.RecordOf(1, 3).CensusRanges!); + tracker.OnCompleted(3); + Assert.Equal(0, watches.Live); + } + [Fact] public void ErasPlaceABufferAgainstTheSampledFramesPresent() { From 5fc0b1e544f61e0ea0693278d8b87366f22130f2 Mon Sep 17 00:00:00 2001 From: kuba Date: Mon, 16 Nov 2026 10:50:17 +0000 Subject: [PATCH 134/178] [Diag] Frame-overlap probe: arm on a run of draw-heavy frames (AFTER_DRAWS) and key the census on the writer, not the address --- .../GpuMemory/InFlightOverlapTracker.cs | 4 +- .../Gpu/GpuCommands/FrameOverlapProbe.cs | 90 ++++++++++++++++++- .../V2/MetalRenderHost.Rendering.cs | 4 + .../Gpu/GpuCommands/FrameOverlapProbeTests.cs | 56 +++++++++++- 4 files changed, 148 insertions(+), 6 deletions(-) diff --git a/src/SharpEmu.HLE/GpuMemory/InFlightOverlapTracker.cs b/src/SharpEmu.HLE/GpuMemory/InFlightOverlapTracker.cs index 07ca23a5a..536ffe18a 100644 --- a/src/SharpEmu.HLE/GpuMemory/InFlightOverlapTracker.cs +++ b/src/SharpEmu.HLE/GpuMemory/InFlightOverlapTracker.cs @@ -1068,7 +1068,9 @@ private void Census(Window window, Record record, int writeIndex, ulong address, { var written = record.Writes[writeIndex]; var programs = written.Op < record.Ops.Count ? record.Ops[written.Op].Programs : []; - var key = (written.Address, written.Program, programs.Length == 0 ? 0 : programs[0]); + // One entry per writer (write program, op program, range size): ring addresses rotate every frame, so + // keying on the address would spend the budget on the same writer frame after frame. + var key = (written.Size, written.Program, programs.Length == 0 ? 0 : programs[0]); if (_censused.Count >= CensusWriters || !_censused.Add(key)) { return; diff --git a/src/SharpEmu.Libs/Gpu/GpuCommands/FrameOverlapProbe.cs b/src/SharpEmu.Libs/Gpu/GpuCommands/FrameOverlapProbe.cs index a69e6a495..98908d1fd 100644 --- a/src/SharpEmu.Libs/Gpu/GpuCommands/FrameOverlapProbe.cs +++ b/src/SharpEmu.Libs/Gpu/GpuCommands/FrameOverlapProbe.cs @@ -64,6 +64,32 @@ public sealed class FrameOverlapProbe ? seconds : 0; + /// + /// SHARPEMU_FRAME_OVERLAP_PROBE_AFTER_DRAWS=: publications land early only once + /// SHARPEMU_FRAME_OVERLAP_PROBE_AFTER_FLIPS (default 60) consecutive frames each recorded at least that + /// many draws, plus SHARPEMU_FRAME_OVERLAP_PROBE_SETTLE_S (default 10) seconds. It replaces + /// SHARPEMU_FRAME_OVERLAP_PROBE_AFTER_S and keys the arming to gameplay-sized frames rather than to the + /// GPU host's start time. + /// + public readonly record struct ArmTrigger(int Draws, int Flips, double SettleSeconds) + { + public static ArmTrigger? FromEnvironment() + { + var culture = System.Globalization.CultureInfo.InvariantCulture; + if (!int.TryParse(Environment.GetEnvironmentVariable("SHARPEMU_FRAME_OVERLAP_PROBE_AFTER_DRAWS"), + System.Globalization.NumberStyles.Integer, culture, out var draws) || draws <= 0) + { + return null; + } + + var flips = int.TryParse(Environment.GetEnvironmentVariable("SHARPEMU_FRAME_OVERLAP_PROBE_AFTER_FLIPS"), + System.Globalization.NumberStyles.Integer, culture, out var parsedFlips) && parsedFlips > 0 ? parsedFlips : 60; + var settle = double.TryParse(Environment.GetEnvironmentVariable("SHARPEMU_FRAME_OVERLAP_PROBE_SETTLE_S"), + System.Globalization.NumberStyles.Float, culture, out var parsedSettle) && parsedSettle >= 0 ? parsedSettle : 10; + return new ArmTrigger(draws, flips, settle); + } + } + public const string WarningLine = "unguarded frame-overlap probe: rendering and guest memory are not protected; measurement only"; @@ -83,7 +109,12 @@ public sealed class FrameOverlapProbe // Serials of the committed buffers that carried a flip, newest last (the last two are kept). private ulong _lastFlipSerial; private ulong _flipBeforeLastSerial; - private readonly long _armAt; + private long _armAt; + private readonly ArmTrigger? _trigger; + private long _drawsOpen; + private long _drawsSinceFlip; + private int _heavyFlips; + private bool _landingReported; private int _refusalReports; // Window counters, guarded by _gate. @@ -108,12 +139,56 @@ public sealed class FrameOverlapProbe private readonly List _earlyMs = new(); private readonly List _flipsOutstanding = new(); - public FrameOverlapProbe(Action enqueueAtSerial, Func completedSerial, Func? clock = null) + public FrameOverlapProbe(Action enqueueAtSerial, Func completedSerial, Func? clock = null, + ArmTrigger? trigger = null) { _enqueueAtSerial = enqueueAtSerial; _completedSerial = completedSerial; _clock = clock ?? Stopwatch.GetTimestamp; - _armAt = ArmAfterSeconds > 0 ? _clock() + (long)(ArmAfterSeconds * Stopwatch.Frequency) : long.MinValue; + _trigger = trigger ?? ArmTrigger.FromEnvironment(); + _armAt = _trigger is not null + ? long.MaxValue + : ArmAfterSeconds > 0 ? _clock() + (long)(ArmAfterSeconds * Stopwatch.Frequency) : long.MinValue; + } + + /// The open buffer recorded a draw (counted only for the arming trigger). + public void NoteDraw() + { + if (_trigger is not null) + { + Interlocked.Increment(ref _drawsOpen); + } + } + + // Under _gate, at every commit: a flip closes a frame; enough heavy frames in a row arm the probe. + private void CountDrawsForTrigger(bool flip) + { + if (_trigger is not { } trigger) + { + return; + } + + _drawsSinceFlip += Interlocked.Exchange(ref _drawsOpen, 0); + if (!flip) + { + return; + } + + if (_armAt == long.MaxValue) + { + _heavyFlips = _drawsSinceFlip >= trigger.Draws ? _heavyFlips + 1 : 0; + if (_heavyFlips >= trigger.Flips) + { + _armAt = _clock() + (long)(trigger.SettleSeconds * Stopwatch.Frequency); + Console.Error.WriteLine(string.Create(System.Globalization.CultureInfo.InvariantCulture, + $"[METAL-V2][OVERLAP-PROBE] armed: {_heavyFlips} consecutive frames with >= {trigger.Draws} draws " + + $"(last {_drawsSinceFlip}); publications land early in {trigger.SettleSeconds:0.#} s; " + + $"wall={DateTime.Now:HH:mm:ss.fff} host_uptime_s={Environment.TickCount64 / 1000.0:0.0} " + + $"process_s={(DateTime.Now - Process.GetCurrentProcess().StartTime).TotalSeconds:0.0}")); + } + } + + _drawsSinceFlip = 0; } /// @@ -262,6 +337,7 @@ public void OnCommit(ulong serial) SharpEmu.HLE.GpuMemory.FrameOverlapDiagnostic.OnProbeCommit(serial, batch.HasFlip); } + CountDrawsForTrigger(batch.HasFlip); _open = new Batch(batch.Index + 1) { FirstSerial = serial + 1 }; if (batch.Items.Count == 0 && !batch.HasFlip) { @@ -325,6 +401,14 @@ private void Publish(Batch batch) _batchesUnarmed++; return; } + + if (_trigger is not null && !_landingReported) + { + _landingReported = true; + Console.Error.WriteLine(string.Create(System.Globalization.CultureInfo.InvariantCulture, + $"[METAL-V2][OVERLAP-PROBE] landing early from serial={batch.Serial}; wall={DateTime.Now:HH:mm:ss.fff} " + + $"process_s={(DateTime.Now - Process.GetCurrentProcess().StartTime).TotalSeconds:0.0}")); + } } if (SharpEmu.HLE.GpuMemory.FrameOverlapDiagnostic.Enabled) diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Rendering.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Rendering.cs index 61f531f35..21353e8eb 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Rendering.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Rendering.cs @@ -1899,6 +1899,7 @@ private void ApplyViewportAndScissor() public void Draw(uint vertexCount, uint instanceCount, uint firstVertex, uint firstInstance) { using var overlapOp = SharpEmu.HLE.GpuMemory.FrameOverlapDiagnostic.Op(dispatch: false); + _overlapProbe?.NoteDraw(); var started = DrawTimingStart(); ApplyGraphicsState(); var entry = _boundGraphicsPipeline!; @@ -1952,6 +1953,7 @@ public void Draw(uint vertexCount, uint instanceCount, uint firstVertex, uint fi void IRenderHost.DrawIndexed(uint indexCount, uint instanceCount, uint firstIndex, int vertexOffset, uint firstInstance) { using var overlapOp = SharpEmu.HLE.GpuMemory.FrameOverlapDiagnostic.Op(dispatch: false); + _overlapProbe?.NoteDraw(); var started = DrawTimingStart(); if (_indexBuffer == 0) { @@ -2015,6 +2017,7 @@ void IRenderHost.DrawIndexed(uint indexCount, uint instanceCount, uint firstInde void IRenderHost.DrawIndirect(BufferBinding arguments) { using var overlapOp = SharpEmu.HLE.GpuMemory.FrameOverlapDiagnostic.Op(dispatch: false); + _overlapProbe?.NoteDraw(); var started = DrawTimingStart(); // The guest's argument layout is (vertexCount, instanceCount, firstVertex, // firstInstance), which is exactly MTLDrawPrimitivesIndirectArguments. @@ -2081,6 +2084,7 @@ private unsafe bool TryForceIndirectDraw(MetalPipelineEntry entry, uint instance void IRenderHost.DrawIndexedIndirect(BufferBinding arguments) { using var overlapOp = SharpEmu.HLE.GpuMemory.FrameOverlapDiagnostic.Op(dispatch: false); + _overlapProbe?.NoteDraw(); var started = DrawTimingStart(); if (_indexBuffer == 0) { diff --git a/tests/SharpEmu.Libs.Tests/Gpu/GpuCommands/FrameOverlapProbeTests.cs b/tests/SharpEmu.Libs.Tests/Gpu/GpuCommands/FrameOverlapProbeTests.cs index 1d3452ac8..fb73c1056 100644 --- a/tests/SharpEmu.Libs.Tests/Gpu/GpuCommands/FrameOverlapProbeTests.cs +++ b/tests/SharpEmu.Libs.Tests/Gpu/GpuCommands/FrameOverlapProbeTests.cs @@ -1,6 +1,7 @@ // Copyright (C) 2026 SharpEmu Emulator Project // SPDX-License-Identifier: GPL-2.0-or-later +using System.Diagnostics; using SharpEmu.HLE; using SharpEmu.Libs.Gpu.GpuCommands; using SharpEmu.Libs.Gpu.Scheduling; @@ -87,10 +88,11 @@ private sealed class NullMemory : ICpuMemory // the way the Metal host queues it, and serials advancing at every commit. private sealed class ProbeHost : ManagedCommandStreamHost { - public ProbeHost(FakeGpu gpu, Log log) : base(new NullMemory(), log, log) + public ProbeHost(FakeGpu gpu, Log log, Func? clock = null, FrameOverlapProbe.ArmTrigger? trigger = null) + : base(new NullMemory(), log, log) { Gpu = gpu; - Probe = new FrameOverlapProbe(gpu.Enqueue, () => gpu.Signaled); + Probe = new FrameOverlapProbe(gpu.Enqueue, () => gpu.Signaled, clock, trigger); } public FakeGpu Gpu { get; } @@ -140,6 +142,56 @@ private static string Counter(string line, string name) return end < 0 ? line[start..] : line[start..end]; } + // One frame: `draws` draws spread over two buffers, the second carrying the flip, each completed at once. + private static void Frame(ProbeHost host, int draws, ref ulong flipId) + { + for (var draw = 0; draw < draws; draw++) + { + host.Probe.NoteDraw(); + if (draw == draws / 2) + { + host.Interrupt(1); + host.Commit(); + } + } + + host.RecordFlip(++flipId, 2); + host.Commit(); + host.Gpu.Pump(); + host.Gpu.Signal(host.OpenSerial - 1); + } + + [Fact] + public void TheDrawTriggerArmsAfterEnoughHeavyFramesInARowAndThenTheSettleDelay() + { + long now = 0; + var host = new ProbeHost(_gpu, _log, () => now, new FrameOverlapProbe.ArmTrigger(Draws: 10, Flips: 3, SettleSeconds: 1)); + ulong flipId = 0; + + // Two heavy frames, a light one (menu or loading) resets the run, then two heavy again: not armed. + Frame(host, 12, ref flipId); + Frame(host, 12, ref flipId); + Frame(host, 4, ref flipId); + Frame(host, 12, ref flipId); + Frame(host, 12, ref flipId); + var line = host.Probe.TakeWindowLine(); + Assert.Equal("0", Counter(line, "published_early")); + + // The third heavy frame in a row arms it; within the settle delay nothing lands early yet. + Frame(host, 12, ref flipId); + now += Stopwatch.Frequency / 2; + Frame(host, 12, ref flipId); + line = host.Probe.TakeWindowLine(); + Assert.Equal("0", Counter(line, "published_early")); + + // Past the delay buffers land early again, and a later light frame does not disarm it. + now += Stopwatch.Frequency; + Frame(host, 4, ref flipId); + Frame(host, 4, ref flipId); + line = host.Probe.TakeWindowLine(); + Assert.NotEqual("0", Counter(line, "published_early")); + } + [Fact] public void ABufferLandsAtItsCommitWhileNoEarlierFlipIsOutstanding() { From 3fbcdbe77a7f521d8eb7d349c99f1617d04fb0f2 Mon Sep 17 00:00:00 2001 From: kuba Date: Mon, 16 Nov 2026 11:06:17 +0000 Subject: [PATCH 135/178] [Diag] Frame-overlap census: search the last writer over the recent stream history, not only the sampled window --- .../GpuMemory/InFlightOverlapTracker.cs | 26 ++++++++++++++++--- .../HLE/InFlightOverlapTrackerTests.cs | 26 ++++++++++++++++++- 2 files changed, 48 insertions(+), 4 deletions(-) diff --git a/src/SharpEmu.HLE/GpuMemory/InFlightOverlapTracker.cs b/src/SharpEmu.HLE/GpuMemory/InFlightOverlapTracker.cs index 536ffe18a..960b45c5a 100644 --- a/src/SharpEmu.HLE/GpuMemory/InFlightOverlapTracker.cs +++ b/src/SharpEmu.HLE/GpuMemory/InFlightOverlapTracker.cs @@ -238,6 +238,14 @@ public void OnCommit(ulong serial, bool present) var record = _open; _open = new Record(); record.Serial = serial; + // Every committed buffer, sampled or not, for the census's last-writer search: a buffer early in + // the frame being built reads what the previous frame's tail wrote, and that tail belongs to an + // unsampled window. + _history.Add(record); + if (_history.Count > HistoryBuffers) + { + _history.RemoveAt(0); + } // Frame F (F % K == 0) arms its own buffers (committed while F-1 presents were seen) and its post-flip ones. long? frame = _frames % _sampleEvery == 0 ? _frames : (_frames + 1) % _sampleEvery == 0 ? _frames + 1 : null; if (frame is { } index && index > 0 && serial > _completedSerial && @@ -1030,13 +1038,23 @@ internal Record RecordOf(long frame, ulong serial) } } + // The last HistoryBuffers committed buffers in stream order (about three gameplay frames). + private const int HistoryBuffers = 192; + private readonly List _history = new(); + private string LastWriter(Window window, Record record, int op, ulong address, ulong size) { var end = address + size; - var start = window.Records.IndexOf(record); + var start = _history.IndexOf(record); + var source = start >= 0 ? _history : window.Records; + if (start < 0) + { + start = window.Records.IndexOf(record); + } + for (var at = start; at >= 0; at--) { - var candidate = window.Records[at]; + var candidate = source[at]; var limit = ReferenceEquals(candidate, record) ? op : int.MaxValue; (int Op, string How, ulong Program)? best = null; foreach (var write in candidate.Writes) @@ -1061,7 +1079,9 @@ private string LastWriter(Window window, Record record, int op, ulong address, u } } - return "last_writer=none_in_window (an earlier frame, the CPU, or a GPU image never written by these buffers)"; + return source == _history + ? $"last_writer=none_in_history (no write in the {start + 1} buffers back to serial {_history[0].Serial}: the CPU or older)" + : "last_writer=none_in_window (an earlier frame, the CPU, or a GPU image never written by these buffers)"; } private void Census(Window window, Record record, int writeIndex, ulong address, int era, double ms) diff --git a/tests/SharpEmu.Libs.Tests/HLE/InFlightOverlapTrackerTests.cs b/tests/SharpEmu.Libs.Tests/HLE/InFlightOverlapTrackerTests.cs index 5829e3efe..d769f3e44 100644 --- a/tests/SharpEmu.Libs.Tests/HLE/InFlightOverlapTrackerTests.cs +++ b/tests/SharpEmu.Libs.Tests/HLE/InFlightOverlapTrackerTests.cs @@ -202,6 +202,30 @@ public void AFaultOnAPageAlreadyLetGoIsRetriedWhileNothingElseBlocksIt() Assert.False(tracker.TryHandleFault(FaultKind.Write, 0x900000, out _)); } + [Fact] + public void ACensusFindsALastWriterInAnUnsampledFrameThroughTheStreamHistory() + { + var watches = new FakeWatches(); + var tracker = Create(watches, every: 4); + tracker.OnCommit(1, present: true); + // Buffer 2 belongs to no sampled window: the previous frame's tail, storing 0x700000. + tracker.NoteOpProgram(0xC0); + tracker.NoteWrite(0x700000, 0x40, OverlapWrite.Storage, OverlapTag.StorageWritten, 0xC0); + tracker.EndOp(dispatch: true, queue: 0); + tracker.OnCommit(2, present: true); + tracker.OnCommit(3, present: true); + // Buffer 4 opens window 4 and reads it. + tracker.NoteOpProgram(0xD0); + tracker.MarkRead(0x700000, 0x40, OverlapTag.StorageRead); + tracker.NoteWrite(0x200000, 0x40, OverlapWrite.Storage, OverlapTag.StorageWritten, 0xD0); + tracker.EndOp(dispatch: true, queue: 0); + tracker.OnCommit(4, present: false); + + var writer = tracker.LastWriterOf(4, 4, 0, 0x700000, 0x40); + Assert.Contains("serial=2 ", writer); + Assert.Contains("op=0/1 kind=dispatch queue=0 programs=[00000000000000C0]", writer); + } + [Fact] public void ACensusFindsTheWriterOpAndTheLastWriterOfItsInputsInStreamOrder() { @@ -225,7 +249,7 @@ public void ACensusFindsTheWriterOpAndTheLastWriterOfItsInputsInStreamOrder() var image = tracker.LastWriterOf(1, 3, 0, 0x500000, 0x1000); Assert.Contains("serial=2 vs_present=1 op=0/1 kind=draw queue=0 programs=[00000000000000A0]", image); Assert.Contains("how=image_target", image); - Assert.Contains("last_writer=none_in_window", tracker.LastWriterOf(1, 3, 0, 0x600000, 0x40)); + Assert.Contains("last_writer=none_in_history", tracker.LastWriterOf(1, 3, 0, 0x600000, 0x40)); // The guest loads the result before buffer 3 completes: the census keeps the range for its value. Assert.True(tracker.TryHandleFault(FaultKind.Read, 0x200010, out _)); From d05a6fd6cd7bf9c7d0658854354131183deb4df5 Mon Sep 17 00:00:00 2001 From: kuba Date: Mon, 16 Nov 2026 11:08:19 +0000 Subject: [PATCH 136/178] [Metal] Gate-hoist timing probe: buffers after a present on a second queue, with contiguous completion through main-queue stand-ins (SHARPEMU_GATE_HOIST_PROBE=1, default off) --- .../SharpEmu.Gpu.Metal/V2/MetalGpuWorker.cs | 17 +- .../V2/MetalRenderHost.EncoderStatus.cs | 4 +- .../V2/MetalRenderHost.GateHoist.cs | 160 ++++++++++++++++++ .../V2/MetalRenderHost.Rendering.cs | 4 + .../SharpEmu.Gpu.Metal/V2/MetalRenderHost.cs | 19 ++- 5 files changed, 198 insertions(+), 6 deletions(-) create mode 100644 src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.GateHoist.cs diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalGpuWorker.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalGpuWorker.cs index 41d4bdadd..7b53635a0 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalGpuWorker.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalGpuWorker.cs @@ -208,11 +208,13 @@ internal sealed class MetalCompletionQueue : IDisposable private long _handlerWakeups; private volatile bool _stopping; - public MetalCompletionQueue(nint sharedEvent) + // bindHandler=false: a second queue (SHARPEMU_GATE_HOIST_PROBE) polls its event and leaves the one + // global completed-handler binding with the host's queue. + public MetalCompletionQueue(nint sharedEvent, bool bindHandler = true) { _sharedEvent = sharedEvent; _wakeHandler = OnGpuCompleted; - _handlerBound = !PollCompletions && MetalCompletionSignal.TryBind(_wakeHandler); + _handlerBound = bindHandler && !PollCompletions && MetalCompletionSignal.TryBind(_wakeHandler); Console.Error.WriteLine( _handlerBound ? "[METAL-V2][INFO] Submission completions wake the host through a command-buffer handler." @@ -284,6 +286,14 @@ public void NoteSignaled(ulong value) /// Runs the work once the submission with this serial completes. public void Enqueue(ulong serial, Action work) { + // SHARPEMU_GATE_HOIST_PROBE=1: the work of a command buffer committed on the second queue runs when + // that buffer completes, not when everything before it has. + if (Route is { } route && route(serial) is { } other && !ReferenceEquals(other, this)) + { + other.Enqueue(serial, work); + return; + } + lock (_gate) { _pending.Add((serial, work)); @@ -291,6 +301,9 @@ public void Enqueue(ulong serial, Action work) } } + /// Another queue that takes the completion work of some serials (null: none). + public Func? Route { get; set; } + private long _lastSignalObserved; /// When the completion thread last saw the event reach a new value. diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.EncoderStatus.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.EncoderStatus.cs index 5eef22318..28fdf7da8 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.EncoderStatus.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.EncoderStatus.cs @@ -30,8 +30,8 @@ internal sealed partial class MetalRenderHost private static long _labelledEncoders; private nint NewCommandBuffer() => EncoderStatusEnabled - ? MetalNative.Send(_queue, SelCommandBufferWithDescriptor, EncoderStatusDescriptor.Value) - : MetalNative.Send(_queue, SelCommandBuffer); + ? MetalNative.Send(RecordQueue, SelCommandBufferWithDescriptor, EncoderStatusDescriptor.Value) + : MetalNative.Send(RecordQueue, SelCommandBuffer); private static void LabelEncoder(nint encoder, string kind) { diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.GateHoist.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.GateHoist.cs new file mode 100644 index 000000000..9e8a9dd3a --- /dev/null +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.GateHoist.cs @@ -0,0 +1,160 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using System.Collections.Concurrent; +using System.Globalization; +using SharpEmu.Libs.Gpu.Scheduling; + +namespace SharpEmu.Gpu.Metal.V2; + +/// +/// SHARPEMU_GATE_HOIST_PROBE=1 (timing probe, unguarded, default off): the command buffers recorded after a +/// present go to a second MTLCommandQueue, so the GPU can run them while the previous frame's lighting and +/// post-processing buffers are still queued or running on the main queue. A phase ends at the commit of the +/// first buffer with at least SHARPEMU_GATE_HOIST_PROBE_DRAWS draws (default 64) or after +/// SHARPEMU_GATE_HOIST_PROBE_MAX buffers (default 8). +/// +/// A hoisted buffer signals its own shared event. Its completion work (label writes, end-of-pipe +/// interrupts) runs on a second completion thread when that buffer completes, so its labels can land +/// before earlier buffers on the main queue have finished. +/// Completed serials stay contiguous: after committing each hoisted buffer, an empty buffer on the +/// main queue waits for the hoisted buffer's event value and then signals the main event with the same +/// serial. The main event therefore reaches a hoisted serial only once all earlier main-queue work and that +/// buffer are done, and every main buffer committed later starts after it. +/// Nothing orders a hoisted buffer against the main-queue work still running before it: no hazard +/// tracking across queues, and no guard on what the tail reads or writes. The image is not guaranteed. +/// +/// +internal sealed partial class MetalRenderHost +{ + internal static readonly bool GateHoistProbe = string.Equals( + Environment.GetEnvironmentVariable("SHARPEMU_GATE_HOIST_PROBE"), "1", StringComparison.Ordinal); + + private static readonly int GateHoistDraws = ReadHoistSetting("SHARPEMU_GATE_HOIST_PROBE_DRAWS", 64); + private static readonly int GateHoistMaxBuffers = ReadHoistSetting("SHARPEMU_GATE_HOIST_PROBE_MAX", 8); + private static readonly nint SelNewCommandQueueForHoist = MetalNative.Selector("newCommandQueue"); + private const int MaxHoistReports = 400; + + private nint _hoistQueue; + private nint _hoistEvent; + private MetalCompletionQueue? _hoistCompletions; + private readonly ConcurrentDictionary _hoistedSerials = new(); + private bool _hoistPhase; + private bool _openOnHoist; + private int _drawsInBuffer; + private int _hoistPhaseBuffers; + private ulong _hoistPhasePresent; + private System.Text.StringBuilder? _hoistPhaseLine; + private int _hoistReports; + private long _hoistedBuffers; + private long _hoistedPresents; + + private nint RecordQueue => _openOnHoist ? _hoistQueue : _queue; + + private static int ReadHoistSetting(string name, int fallback) => + int.TryParse(Environment.GetEnvironmentVariable(name), NumberStyles.Integer, CultureInfo.InvariantCulture, out var value) && value > 0 + ? value + : fallback; + + private void InitGateHoist(nint device) + { + _hoistQueue = MetalNative.Send(device, SelNewCommandQueueForHoist); + _hoistEvent = MetalNative.Send(device, SelNewSharedEvent); + if (_hoistQueue == 0 || _hoistEvent == 0) + { + throw GpuFatal.Fatal("SHARPEMU_GATE_HOIST_PROBE: a second Metal command queue or shared event could not be created."); + } + + _hoistCompletions = new MetalCompletionQueue(_hoistEvent, bindHandler: false); + _completions.Route = serial => _hoistedSerials.ContainsKey(serial) ? _hoistCompletions : null; + Console.Error.WriteLine( + "[METAL-V2][GATE-HOIST][WARN] timing probe: buffers after a present run on a second queue, unordered " + + $"against the main queue's earlier work; measurement only (draws={GateHoistDraws} max={GateHoistMaxBuffers})"); + } + + // Before the command buffer for `serial` is created. + private void BeginGateHoistBuffer(ulong serial) + { + _openOnHoist = _hoistPhase; + _drawsInBuffer = 0; + if (_openOnHoist) + { + foreach (var old in _hoistedSerials.Keys) + { + if (old + 1024 < serial) + { + _hoistedSerials.TryRemove(old, out _); + } + } + + _hoistedSerials[serial] = 0; + } + } + + // After the command buffer for `serial` was committed. + private void AfterGateHoistCommit(ulong serial, bool present) + { + if (_openOnHoist) + { + _hoistedBuffers++; + _hoistPhaseBuffers++; + _hoistCompletions!.Publish(serial); + // The main queue's stand-in: the main event reaches this serial once everything before it on the + // main queue and the hoisted buffer itself are done. + var shadow = MetalNative.Send(_queue, SelCommandBuffer); + if (shadow == 0) + { + throw GpuFatal.Fatal("SHARPEMU_GATE_HOIST_PROBE: a Metal command buffer could not be created."); + } + + MetalV2Native.SendEventValue(shadow, SelEncodeWaitForEvent, _hoistEvent, serial); + MetalV2Native.SendEventValue(shadow, SelEncodeSignalEvent, _sharedEvent, serial); + if (_completions.WantsCompletionHandler) + { + MetalNative.SendVoid(shadow, SelAddCompletedHandler, MetalCompletionSignal.Block); + } + + MetalNative.SendVoid(shadow, SelCommit); + _hoistPhaseLine?.Append(CultureInfo.InvariantCulture, $" {serial}:{_drawsInBuffer}"); + string? end = present ? "present" : _drawsInBuffer >= GateHoistDraws ? "draws" : _hoistPhaseBuffers >= GateHoistMaxBuffers ? "max" : null; + if (present) + { + _hoistedPresents++; + } + + if (end is not null) + { + _hoistPhase = false; + ReportHoistPhase(end); + } + } + + _openOnHoist = false; + _drawsInBuffer = 0; + if (present) + { + if (_hoistPhase) + { + ReportHoistPhase("next_present"); + } + + _hoistPhase = true; + _hoistPhaseBuffers = 0; + _hoistPhasePresent = serial; + _hoistPhaseLine = _hoistReports < MaxHoistReports ? new System.Text.StringBuilder() : null; + } + } + + private void ReportHoistPhase(string end) + { + if (_hoistPhaseLine is { } line && _hoistReports < MaxHoistReports) + { + _hoistReports++; + Console.Error.WriteLine(string.Create(CultureInfo.InvariantCulture, + $"[METAL-V2][GATE-HOIST] present={_hoistPhasePresent} end={end} hoisted_total={_hoistedBuffers} " + + $"hoisted_presents={_hoistedPresents} buffers(serial:draws)={line}")); + } + + _hoistPhaseLine = null; + } +} diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Rendering.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Rendering.cs index 21353e8eb..b6be83633 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Rendering.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Rendering.cs @@ -1900,6 +1900,7 @@ public void Draw(uint vertexCount, uint instanceCount, uint firstVertex, uint fi { using var overlapOp = SharpEmu.HLE.GpuMemory.FrameOverlapDiagnostic.Op(dispatch: false); _overlapProbe?.NoteDraw(); + _drawsInBuffer++; var started = DrawTimingStart(); ApplyGraphicsState(); var entry = _boundGraphicsPipeline!; @@ -1954,6 +1955,7 @@ void IRenderHost.DrawIndexed(uint indexCount, uint instanceCount, uint firstInde { using var overlapOp = SharpEmu.HLE.GpuMemory.FrameOverlapDiagnostic.Op(dispatch: false); _overlapProbe?.NoteDraw(); + _drawsInBuffer++; var started = DrawTimingStart(); if (_indexBuffer == 0) { @@ -2018,6 +2020,7 @@ void IRenderHost.DrawIndirect(BufferBinding arguments) { using var overlapOp = SharpEmu.HLE.GpuMemory.FrameOverlapDiagnostic.Op(dispatch: false); _overlapProbe?.NoteDraw(); + _drawsInBuffer++; var started = DrawTimingStart(); // The guest's argument layout is (vertexCount, instanceCount, firstVertex, // firstInstance), which is exactly MTLDrawPrimitivesIndirectArguments. @@ -2085,6 +2088,7 @@ void IRenderHost.DrawIndexedIndirect(BufferBinding arguments) { using var overlapOp = SharpEmu.HLE.GpuMemory.FrameOverlapDiagnostic.Op(dispatch: false); _overlapProbe?.NoteDraw(); + _drawsInBuffer++; var started = DrawTimingStart(); if (_indexBuffer == 0) { diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.cs index 04a9bb3ed..0341272b5 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.cs @@ -207,6 +207,10 @@ public MetalRenderHost( _imageCache.StagedRanges = _stagedRanges; } _completions = new MetalCompletionQueue(_sharedEvent); + if (GateHoistProbe) + { + InitGateHoist(device); + } if (SharpEmu.Libs.Gpu.GpuCommands.FrameOverlapProbe.Enabled) { Console.Error.WriteLine("[METAL-V2][OVERLAP-PROBE][WARN] " + SharpEmu.Libs.Gpu.GpuCommands.FrameOverlapProbe.WarningLine); @@ -359,6 +363,11 @@ private static bool SupportsApple10Features(nint device) [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] private nint OpenCommandBuffer() { + if (GateHoistProbe) + { + BeginGateHoistBuffer(_nextSerial + 1); + } + _commandBuffer = NewCommandBuffer(); MetalMemoryTelemetry.CommandBuffers.Add(); if (_commandBuffer == 0) @@ -675,8 +684,8 @@ private ulong FlushCommandBuffer(PassEndCause cause, MetalFlushCause why) // this watch exists for was lost twice. _slotTrap?.Verify(CompletedSerial); var serial = _submissionSerial; - MetalV2Native.SendEventValue(_commandBuffer, SelEncodeSignalEvent, _sharedEvent, serial); - if (_completions.WantsCompletionHandler) + MetalV2Native.SendEventValue(_commandBuffer, SelEncodeSignalEvent, _openOnHoist ? _hoistEvent : _sharedEvent, serial); + if (_completions.WantsCompletionHandler && !_openOnHoist) { // The handler is a global block with no state: it only wakes whoever waits // on the shared event, which the signal above has already advanced. @@ -695,6 +704,11 @@ private ulong FlushCommandBuffer(PassEndCause cause, MetalFlushCause why) MetalMemoryTelemetry.Commits.Add(); Volatile.Write(ref _submittedSerial, serial); MetalNative.SendVoid(_commandBuffer, SelCommit); + if (GateHoistProbe) + { + AfterGateHoistCommit(serial, cause == PassEndCause.Present); + } + if (DsTrace.Gpu && DsTrace.Armed) { DsTrace.Emit(DsEv.MCOMMIT, serial, (ulong)cause, _pendingLabelWrites, @@ -3252,6 +3266,7 @@ public void Dispose() } _completions.Dispose(); + _hoistCompletions?.Dispose(); DisposeNativeOcclusion(); DisposeLabelScatter(); DisposeThreadDispatch(); From 80d99a449eed1726ebc4b2d7b908b4140b36e26c Mon Sep 17 00:00:00 2001 From: kuba Date: Mon, 16 Nov 2026 11:36:46 +0000 Subject: [PATCH 137/178] [Shader] Fuse legacy multiply-add by default, SHARPEMU_MSL_FUSE_MAD=0 restores the exact form --- docs/macos/configuration.md | 2 +- .../Gen5MslCodegenOptions.cs | 9 ++++--- .../Conformance/ConformanceRunner.cs | 3 ++- .../Gen5ComputeFixtures.cs | 5 ++-- .../Gen5MslFloatSemanticsTests.cs | 25 +++++++++++++++---- .../MetalRuntimeTests.cs | 10 +++++--- 6 files changed, 37 insertions(+), 17 deletions(-) diff --git a/docs/macos/configuration.md b/docs/macos/configuration.md index c52a8bb9c..31e0cc6bf 100644 --- a/docs/macos/configuration.md +++ b/docs/macos/configuration.md @@ -103,7 +103,7 @@ undoes an optimization to isolate a miscompile: | `SHARPEMU_MSL_PERSISTENT_FENCES` | on | Leaves `S_WAITCNT` a no-op in persistent-thread kernels. | | `SHARPEMU_MSL_PERSISTENT_RECORDS` | on | Accesses multi-dword records of persistent-thread kernels dword by dword. | | `SHARPEMU_MSL_BYTEBIAS` | off | `1` keeps the per-buffer byte bias. | -| `SHARPEMU_MSL_FUSE_MAD` | off | `1` emits the guest's legacy multiply-adds (`V_MAD_F32`, `V_MAC_F32`) as one fused operation in compute programs and pixel programs without depth export. Faster (about 5 ms of an 82 ms Demon's Souls frame) but not bit-exact: the guest rounds the product first. | +| `SHARPEMU_MSL_FUSE_MAD` | on | Emits the guest's legacy multiply-adds (`V_MAD_F32`, `V_MAC_F32`) as one fused operation in compute programs and pixel programs without depth export. Faster (about 5 ms of an 82 ms Demon's Souls frame) but not bit-exact for MAD/MAC: the guest rounds the product first. `0` restores the exact two-op form. | | `SHARPEMU_LOD_STATS` | guarded | `always` compiles the LOD statistics counters into every pixel pipeline. | ## Diagnostics diff --git a/src/SharpEmu.ShaderCompiler.Metal/Gen5MslCodegenOptions.cs b/src/SharpEmu.ShaderCompiler.Metal/Gen5MslCodegenOptions.cs index 175ea007d..2bab70069 100644 --- a/src/SharpEmu.ShaderCompiler.Metal/Gen5MslCodegenOptions.cs +++ b/src/SharpEmu.ShaderCompiler.Metal/Gen5MslCodegenOptions.cs @@ -129,11 +129,12 @@ namespace SharpEmu.ShaderCompiler.Metal; /// multiply-add in compute programs and in pixel programs that export no depth. The guest rounds the /// product before the add, so the fused result differs wherever that rounding mattered: by at most half /// an ULP of the product in the sum, and a result just under the smallest normal flushes to zero where -/// the guest kept the addend (Rdna2AluConformanceTests fails the MAD/MAC forms with this on). It never +/// the guest kept the addend (Rdna2AluConformanceTests, which runs with this off, would fail the MAD/MAC forms with it on). It never /// touches compares, NaN ordering or any other instruction, unlike . /// Vertex, mesh and depth-exporting pixel programs, which feed positions and depth, never fuse. The heavy /// Demon's Souls kernels are mostly V_MAD_F32, each two operations unfused: about 5 ms of an 82 ms frame. -/// Off by default; SHARPEMU_MSL_FUSE_MAD=1 turns it on. +/// The fused form is not bit-exact for MAD/MAC. On by default; SHARPEMU_MSL_FUSE_MAD=0 restores +/// the exact two-operation form. public sealed record Gen5MslCodegenOptions( bool StructuredControlFlow = true, bool RegisterAllocation = true, @@ -160,7 +161,7 @@ public sealed record Gen5MslCodegenOptions( bool ContractPixelCompute = false, bool RuntimeDwordFormatLoads = true, bool FusedLaneReads = true, - bool FuseLegacyMultiplyAdd = false) + bool FuseLegacyMultiplyAdd = true) { /// Diagnostic threshold for moving mesh LDS from threadgroup memory to the /// device pool, in bytes. The supported mesh allocation is at most 16 KiB. Zero @@ -348,7 +349,7 @@ public sealed record Gen5MslCodegenOptions( ContractPixelCompute: Environment.GetEnvironmentVariable("SHARPEMU_MSL_CONTRACT") == "1", RuntimeDwordFormatLoads: Environment.GetEnvironmentVariable("SHARPEMU_MSL_RUNTIME_DWORD_FORMAT") != "0", FusedLaneReads: Environment.GetEnvironmentVariable("SHARPEMU_MSL_READLANE_FUSE") != "0", - FuseLegacyMultiplyAdd: Environment.GetEnvironmentVariable("SHARPEMU_MSL_FUSE_MAD") == "1") + FuseLegacyMultiplyAdd: Environment.GetEnvironmentVariable("SHARPEMU_MSL_FUSE_MAD") != "0") { UnobservedAluWrites = Environment.GetEnvironmentVariable("SHARPEMU_MSL_UNOBSERVED_ALU") is "1" or "all", UnobservedAluAllStages = Environment.GetEnvironmentVariable("SHARPEMU_MSL_UNOBSERVED_ALU") == "all", diff --git a/tests/SharpEmu.ShaderCompiler.Metal.Tests/Conformance/ConformanceRunner.cs b/tests/SharpEmu.ShaderCompiler.Metal.Tests/Conformance/ConformanceRunner.cs index d27f2f758..5d5a82a95 100644 --- a/tests/SharpEmu.ShaderCompiler.Metal.Tests/Conformance/ConformanceRunner.cs +++ b/tests/SharpEmu.ShaderCompiler.Metal.Tests/Conformance/ConformanceRunner.cs @@ -69,7 +69,8 @@ public static ShaderCompileRequest Request(uint[] words, int wave, AluMode mode) return "decode: " + exception.Message; } - if (!Gen5MslTranslator.TryCompileProgram(request, out var compiled, out var error)) + if (!Gen5MslTranslator.TryCompileProgram(request, out var compiled, out var error, + Gen5MslCodegenOptions.FromEnvironment with { FuseLegacyMultiplyAdd = false })) { return "translate: " + error; } diff --git a/tests/SharpEmu.ShaderCompiler.Metal.Tests/Gen5ComputeFixtures.cs b/tests/SharpEmu.ShaderCompiler.Metal.Tests/Gen5ComputeFixtures.cs index 39ce1eb5f..2fed3d96c 100644 --- a/tests/SharpEmu.ShaderCompiler.Metal.Tests/Gen5ComputeFixtures.cs +++ b/tests/SharpEmu.ShaderCompiler.Metal.Tests/Gen5ComputeFixtures.cs @@ -934,10 +934,11 @@ public static ShaderCompileRequest RequestOrThrow(Gen5ShaderProgram program, Sha } public static Gen5MslShader CompileRequestOrThrow(Gen5ComputeFixture fixture, uint waveLaneCount = 32, uint localSizeX = 32, - uint localDataShareDwords = 0, uint pushDataStartDword = 0, uint floatMode = ShaderCompileRequest.DefaultFloatMode) + uint localDataShareDwords = 0, uint pushDataStartDword = 0, uint floatMode = ShaderCompileRequest.DefaultFloatMode, + Gen5MslCodegenOptions? options = null) { var request = CreateComputeRequest(fixture, waveLaneCount, localSizeX, localDataShareDwords, pushDataStartDword, floatMode); - if (!Gen5MslTranslator.TryCompileProgram(request, out var shader, out var error)) + if (!Gen5MslTranslator.TryCompileProgram(request, out var shader, out var error, options)) { throw new InvalidOperationException($"[{fixture.Name}] MSL request emit failed: {error}"); } diff --git a/tests/SharpEmu.ShaderCompiler.Metal.Tests/Gen5MslFloatSemanticsTests.cs b/tests/SharpEmu.ShaderCompiler.Metal.Tests/Gen5MslFloatSemanticsTests.cs index 2fa48a101..5db59912f 100644 --- a/tests/SharpEmu.ShaderCompiler.Metal.Tests/Gen5MslFloatSemanticsTests.cs +++ b/tests/SharpEmu.ShaderCompiler.Metal.Tests/Gen5MslFloatSemanticsTests.cs @@ -130,13 +130,14 @@ public void MadFormsRoundTheProductBeforeTheAdd(string opcode, Gen5ShaderEncodin var instruction = encoding == Gen5ShaderEncoding.Vop3 ? Vop3(opcode, V012) : new Gen5ShaderInstruction(28, encoding, opcode, [], [Gen5Operand.Vector(0), Gen5Operand.Vector(1)], [Gen5Operand.Vector(3)], null); - var shader = Compile([instruction], Factor, Factor, Addend, Addend); + var exact = Gen5MslCodegenOptions.FromEnvironment with { FuseLegacyMultiplyAdd = false }; + Assert.True(TryCompile([instruction], Factor, Factor, Addend, Addend, out var shader, out var error, options: exact), error); if (!RequireDevice()) return; - Assert.Equal(expected, Execute(shader)); + Assert.Equal(expected, Execute(shader!)); } // Gen5MslCodegenOptions.FuseLegacyMultiplyAdd trades that rounding for one operation in a compute - // program: the same inputs keep the 2^-46 a fused multiply-add keeps. Off, the default, it is lost. + // program: the same inputs keep the 2^-46 a fused multiply-add keeps. Off, it is lost. [Theory] [InlineData("VMadF32", Gen5ShaderEncoding.Vop3)] [InlineData("VMacF32", Gen5ShaderEncoding.Vop2)] @@ -149,10 +150,24 @@ public void FusedLegacyMultiplyAddKeepsTheProductUnrounded(string opcode, Gen5Sh var options = Gen5MslCodegenOptions.FromEnvironment with { FuseLegacyMultiplyAdd = true }; Assert.True(TryCompile([instruction], Factor, Factor, Addend, Addend, out var fused, out var error, options: options), error); Assert.Contains("fma(", fused!.Source); - var unfused = Compile([instruction], Factor, Factor, Addend, Addend); + var exact = options with { FuseLegacyMultiplyAdd = false }; + Assert.True(TryCompile([instruction], Factor, Factor, Addend, Addend, out var unfused, out error, options: exact), error); if (!RequireDevice()) return; Assert.Equal(0x28800000u, Execute(fused)); - Assert.Equal(0u, Execute(unfused)); + Assert.Equal(0u, Execute(unfused!)); + } + + // Fusing is the default; SHARPEMU_MSL_FUSE_MAD=0 (FuseLegacyMultiplyAdd false) restores the exact form. + [Fact] + public void LegacyMultiplyAddFusesByDefaultAndNotInExactMode() + { + Assert.True(new Gen5MslCodegenOptions().FuseLegacyMultiplyAdd); + var instruction = Vop3("VMadF32", V012); + Assert.True(TryCompile([instruction], 0u, 0u, 0u, 0u, out var byDefault, out var error, options: new Gen5MslCodegenOptions()), error); + Assert.Contains("fma(", byDefault!.Source); + var exact = new Gen5MslCodegenOptions { FuseLegacyMultiplyAdd = false }; + Assert.True(TryCompile([instruction], 0u, 0u, 0u, 0u, out var unfused, out error, options: exact), error); + Assert.DoesNotContain("fma(", unfused!.Source); } // V_MAD_LEGACY_F32 flushes its denormal sources, so a denormal factor takes the DX9 zero diff --git a/tests/SharpEmu.ShaderCompiler.Metal.Tests/MetalRuntimeTests.cs b/tests/SharpEmu.ShaderCompiler.Metal.Tests/MetalRuntimeTests.cs index ac5d58ef5..5db948f39 100644 --- a/tests/SharpEmu.ShaderCompiler.Metal.Tests/MetalRuntimeTests.cs +++ b/tests/SharpEmu.ShaderCompiler.Metal.Tests/MetalRuntimeTests.cs @@ -556,13 +556,14 @@ public void OnlyAQueueDrainingLoopIsMarkedPersistentThreads() [Fact] public void LegacyMadRoundsTheProductAndFmaDoesNot() { - var shader = Gen5ComputeFixtures.CompileRequestOrThrow(Gen5ComputeFixtures.MadVersusFma); + var exact = Gen5MslCodegenOptions.FromEnvironment with { FuseLegacyMultiplyAdd = false }; + var shader = Gen5ComputeFixtures.CompileRequestOrThrow(Gen5ComputeFixtures.MadVersusFma, options: exact); Assert.Contains("#pragma clang fp contract(off)", shader.Source, StringComparison.Ordinal); if (SkipWithoutMetalDevice("the execution test")) return; var result = ExecuteRequestOrThrow(Gen5ComputeFixtures.MadVersusFma, new byte[256], - waveLaneCount: 32, localSizeX: 32, threadsPerThreadgroup: 32); + waveLaneCount: 32, localSizeX: 32, threadsPerThreadgroup: 32, options: exact); for (var lane = 0; lane < 32; lane++) { Assert.Equal(0u, ReadDword(result, lane * 8)); @@ -832,9 +833,10 @@ public void TypedLoadFixtureReturnsInstructionFormatComponentsThroughTheArgument } private static byte[] ExecuteRequestOrThrow(Gen5ComputeFixture fixture, byte[] buffer, - uint waveLaneCount = 32, uint localSizeX = 32, uint threadsPerThreadgroup = 1, uint localDataShareDwords = 0) + uint waveLaneCount = 32, uint localSizeX = 32, uint threadsPerThreadgroup = 1, uint localDataShareDwords = 0, + Gen5MslCodegenOptions? options = null) { - var shader = Gen5ComputeFixtures.CompileRequestOrThrow(fixture, waveLaneCount, localSizeX, localDataShareDwords); + var shader = Gen5ComputeFixtures.CompileRequestOrThrow(fixture, waveLaneCount, localSizeX, localDataShareDwords, options: options); if (!MetalNative.TryCompileLibrary(shader.Source, out var library, out var compileError)) { throw new InvalidOperationException($"[{fixture.Name}] {compileError}\n{shader.Source}"); From 12f6aadd1d068fd2ed7a1399eaedbbbe8de0a137 Mon Sep 17 00:00:00 2001 From: kuba Date: Mon, 16 Nov 2026 13:37:33 +0000 Subject: [PATCH 138/178] [Docs] Document SHARPEMU_TITLE_SCENE_RESOLUTION with measured frame times --- docs/macos/configuration.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/macos/configuration.md b/docs/macos/configuration.md index 31e0cc6bf..f030be5e2 100644 --- a/docs/macos/configuration.md +++ b/docs/macos/configuration.md @@ -40,6 +40,7 @@ them for measurements or to isolate a problem. | `SHARPEMU_GUEST_BACKING` | chunked | `shm` backs guest memory with one POSIX shared-memory object instead of 2 MiB purgeable memory objects. The default allows memory the guest frees to return to the OS. | | `SHARPEMU_GUEST_BACKING_SHAREABLE` | unset | `1` makes the guest backing shareable with another process, and keeps a shared table and log of guest views. This is groundwork for the two-process split (`SHARPEMU_GPU_PROCESS=1` sets it too). See [Guest memory for the two-process split](split-shared-memory.md). | | `SHARPEMU_HLE_FAST_PATH` | on | `0` disables the native stubs for `pthread_self` and `pthread_getspecific`. They are also off while import or pthread tracing is active. | +| `SHARPEMU_TITLE_SCENE_RESOLUTION` | unset | Demon's Souls only (known build). Caps the game's internal scene size below the display: `900p`, `720p`, `540p` (any `p`, 16:9) or `WIDTHxHEIGHT`, at least 640x360. The game renders the scene at that size and upscales it itself; the output, display buffers and UI keep their sizes. Lowers image quality for frame time: on a base M4 at a 1080p display, about 78 ms per frame uncapped, 69 ms at `900p`, 63 ms at `720p`, 55 ms at `540p`. Below `540p` the picture breaks and nothing more is gained. | | `SHARPEMU_STALL_WATCHDOG_SECONDS` | `20` | Seconds without import progress before the stall watchdog acts. `0` disables it. | | `SHARPEMU_FLIP_AHEAD` | off | Experimental. `1` tells the game a GPU flip is done once the flip is recorded and the flip before it has really finished on the GPU, instead of when the frame is shown, so the game can build its next frame while the GPU draws this one (at most one flip ahead). Each such frame is copied in the GPU stream into a presenter-owned texture (up to 7 textures the size of the display buffer), so what is shown is unchanged; a flip whose frame cannot be copied keeps the usual timing, and the refusal is logged once. Pacing, interrupts and labels are unchanged. Counters: `[VIDEOOUT][FLIP-AHEAD]` and the `flip_copy*` fields of `[METAL-PRESENT]`. | From 24a9ef427a06a1746156969b4da4488c77d6fea3 Mon Sep 17 00:00:00 2001 From: kuba Date: Mon, 16 Nov 2026 14:48:49 +0000 Subject: [PATCH 139/178] [Shader] Widen the half-local EXEC branch proof: exact operand widths, flow-sensitive restores, row-local DPP Scalar liveness counts the registers an operand really reads (32-bit ALU operand 1, buffer resource 4, image sampler 4, s_load base 2) and the registers a load lists; a restored EXEC pair counts as a subset when every path's last write of it was one; DPP16 row-local controls and DPP8 stay in the half. A body holding a whole-wave S_CBRANCH_EXECZ is refused instead of retranslating the program without any. DS corpus: wave64 exchanges 7844 -> 5234 over 461 programs; heavy kernels -3.1% offline. SHARPEMU_MSL_HALF_BRANCH_REPORT=1 prints each branch's verdict. --- docs/macos/configuration.md | 2 + .../Gen5MslTranslator.HalfBranches.cs | 362 +++++++++++++++--- .../Gen5MslTranslator.Resources.cs | 5 + .../MslHalfLocalBranchTests.cs | 76 ++++ 4 files changed, 397 insertions(+), 48 deletions(-) diff --git a/docs/macos/configuration.md b/docs/macos/configuration.md index f030be5e2..833da6678 100644 --- a/docs/macos/configuration.md +++ b/docs/macos/configuration.md @@ -100,6 +100,7 @@ undoes an optimization to isolate a miscompile: | `SHARPEMU_MSL_CONSTANTTABLES` | on | Reads uniform tables through the device address space. | | `SHARPEMU_MSL_LDSSIZE` | on | Declares all 32 KB of threadgroup memory. | | `SHARPEMU_MSL_MASKBALLOT` | on | Materializes every wave ballot. | +| `SHARPEMU_MSL_HALF_BRANCHES` | on | Tests the whole wave64 (an exchange between its two simdgroups) at every forward `S_CBRANCH_EXECZ` of a one-wave compute group, instead of letting each half skip a body that only touches its own lanes. | | `SHARPEMU_MSL_SPILLCOPY` | on | Reads spilled scalar registers through the lane exchange. | | `SHARPEMU_MSL_PERSISTENT_FENCES` | on | Leaves `S_WAITCNT` a no-op in persistent-thread kernels. | | `SHARPEMU_MSL_PERSISTENT_RECORDS` | on | Accesses multi-dword records of persistent-thread kernels dword by dword. | @@ -122,6 +123,7 @@ undoes an optimization to isolate a miscompile: | `SHARPEMU_METAL_V2_DUMP_MAX=` | Maximum dumps. Default 240. | | `SHARPEMU_METAL_V2_DUMP_EVERY=` | Dump one frame's targets every `n` flips. | | `SHARPEMU_METAL_V2_DUMP_AFTER_SECONDS=`, `SHARPEMU_METAL_V2_DUMP_AFTER_FLIPS=` | Hold dumps back until the game has run that long, or flipped that many times. | +| `SHARPEMU_MSL_HALF_BRANCH_REPORT=1` | Prints, for each forward `S_CBRANCH_EXECZ` of a wave64 compute program, whether each half may take it alone and the first reason it may not (`[MSL][HALF-BRANCH]`). Works with the shader corpus replay. | | `SHARPEMU_SHADER_MSL_DUMP_DIR=` | Writes each translated program as `-.metal` with a `-.gen5` listing of the guest instructions. `1` writes to `msl-dumps` under the logs folder. | | `SHARPEMU_SHADER_MSL_DUMP_HASH=` | Restricts the dump to a comma-separated list of shader hashes. | | `SHARPEMU_METAL_V2_IGNORE_TESTS=1` | Drops culling, depth and stencil tests from every draw, to tell an empty pass from a rejected one. | diff --git a/src/SharpEmu.ShaderCompiler.Metal/Gen5MslTranslator.HalfBranches.cs b/src/SharpEmu.ShaderCompiler.Metal/Gen5MslTranslator.HalfBranches.cs index be4e9210f..88f06b770 100644 --- a/src/SharpEmu.ShaderCompiler.Metal/Gen5MslTranslator.HalfBranches.cs +++ b/src/SharpEmu.ShaderCompiler.Metal/Gen5MslTranslator.HalfBranches.cs @@ -14,12 +14,16 @@ namespace SharpEmu.ShaderCompiler.Metal; // A half whose own lanes are all off can skip such a body by itself when running it could not // have changed anything the other half or the code after it sees: // - every lane of that half is off throughout, so the body's vector work writes nothing there; -// - the body holds no cross-lane read, LDS access or exchange, so the running half waits on -// nobody, and no EXEC write that could turn on a lane that was off when it began: only -// narrowing writes and restores of masks the body saved itself; +// - the body holds no read of the other half's lanes, LDS access or exchange, so the running +// half waits on nobody (DPP and its row-local shuffles stay inside the half), and no EXEC +// write that could turn on a lane that was off when it began: only narrowing writes and +// restores of masks that, on every path to the restore, the body last wrote with lanes of +// its own EXEC; // - every scalar register, VCC or SCC value the body writes is dead where it joins the code -// after it, so the halves differ only in values nothing reads; -// - the body is entered only through the branch and leaves only to the join. +// after it, so the halves differ only in values nothing reads (each operand counts the +// registers it really reads: one for a 32-bit operand, a buffer resource's four); +// - the body is entered only through the branch and leaves only to the join, and every +// S_CBRANCH_EXECZ inside it is half-local too (one the wave takes as a whole exchanges). // Then the branch tests this half's EXEC (simd_ballot) and the mask-ballot elision drops the // exchange no reader is left for. The body's emitted text is checked again once the ballots // are resolved; one that still exchanges has the program translated without these branches. @@ -39,6 +43,26 @@ private sealed partial class CompilationContext /// resolved; the program is then compiled again without half-local branches. internal bool HalfLocalBranchExchanged { get; private set; } + private static readonly bool HalfBranchReport = + Environment.GetEnvironmentVariable("SHARPEMU_MSL_HALF_BRANCH_REPORT") == "1"; + + /// Why the last body was refused, for . + private string? _halfBranchRefusal; + + private bool RefuseHalfBranch(string reason) + { + _halfBranchRefusal = reason; + return false; + } + + private void ReportHalfBranch(Gen5ShaderInstruction branch, string verdict) + { + if (HalfBranchReport) + { + Console.Error.WriteLine($"[MSL][HALF-BRANCH] 0x{_request.Hash:X16} pc=0x{branch.Pc:X4} {verdict}"); + } + } + private bool IsHalfLocalBranchBlock(int block) => _halfLocalBranchBlocks is { } blocks && block < blocks.Length && blocks[block]; @@ -50,6 +74,13 @@ private void FindHalfLocalBranches(IReadOnlyList blocks) { if (!HalfLocalBranchesApply) { + if (HalfBranchReport && _stage == Gen5MslStage.Compute && IsWave64) + { + Console.Error.WriteLine( + $"[MSL][HALF-BRANCH] 0x{_request.Hash:X16} program not applicable: threads={ComputeThreads} " + + $"bridged={IsBridgedComputeWaves} option={_options.HalfLocalExecBranches}"); + } + return; } @@ -59,6 +90,11 @@ private void FindHalfLocalBranches(IReadOnlyList blocks) if (instruction.Opcode.StartsWith("SMovrel", StringComparison.Ordinal) || instruction.Opcode is "SSetpcB64" or "SSwappcB64" or "SRfeB64" or "SGetpcB64") { + if (HalfBranchReport) + { + Console.Error.WriteLine($"[MSL][HALF-BRANCH] 0x{_request.Hash:X16} program refused: {instruction.Opcode}"); + } + return; } } @@ -91,6 +127,11 @@ private void FindHalfLocalBranches(IReadOnlyList blocks) } else if (!TryGetBranchTargetBlock(blocks, last, out taken)) { + if (HalfBranchReport) + { + Console.Error.WriteLine($"[MSL][HALF-BRANCH] 0x{_request.Hash:X16} program refused: unresolved branch target"); + } + return; } @@ -110,22 +151,72 @@ private void FindHalfLocalBranches(IReadOnlyList blocks) } var (liveIn, sccLiveIn) = ScalarLiveness(blocks, successors); - bool[]? branches = null; - bool[]? bodies = null; + var accepted = new bool[count]; + var candidate = new bool[count]; for (var block = 0; block + 1 < count; block++) { var last = instructions[blocks[block].EndIndex - 1]; var join = takenTargets[block]; - if (last.Opcode != "SCbranchExecz" || join <= block + 1 || - !IsHalfLocalBody(blocks, successors, block + 1, join, liveIn, sccLiveIn)) + if (last.Opcode != "SCbranchExecz") + { + continue; + } + + candidate[block] = true; + if (join <= block + 1) + { + ReportHalfBranch(last, "backward or empty body"); + continue; + } + + if (!IsHalfLocalBody(blocks, successors, block + 1, join, liveIn, sccLiveIn)) + { + ReportHalfBranch(last, _halfBranchRefusal ?? "unrecorded"); + continue; + } + + accepted[block] = true; + } + + // A body that holds an S_CBRANCH_EXECZ the wave still takes as a whole holds that + // branch's exchange, so it cannot be skipped by one half either. + for (var changed = true; changed;) + { + changed = false; + for (var block = 0; block < count; block++) + { + if (!accepted[block]) + { + continue; + } + + for (var inside = block + 1; inside < takenTargets[block]; inside++) + { + if (candidate[inside] && !accepted[inside]) + { + accepted[block] = false; + changed = true; + ReportHalfBranch(instructions[blocks[block].EndIndex - 1], "nested whole-wave execz"); + break; + } + } + } + } + + bool[]? branches = null; + bool[]? bodies = null; + for (var block = 0; block < count; block++) + { + if (!accepted[block]) { continue; } + ReportHalfBranch(instructions[blocks[block].EndIndex - 1], "accepted"); branches ??= new bool[count]; bodies ??= new bool[count]; branches[block] = true; - for (var inside = block + 1; inside < join; inside++) + for (var inside = block + 1; inside < takenTargets[block]; inside++) { bodies[inside] = true; } @@ -149,22 +240,20 @@ private bool IsHalfLocalBody(IReadOnlyList blocks, int[][] successo if (inside ? successor < first || successor > join : successor > first && successor < join || (successor == first && block != first - 1)) { - return false; + return RefuseHalfBranch(inside ? "body leaves other than to the join" : "body entered other than by the branch"); } } if (inside && successors[block].Length == 0) { // An exit in the body would end the half that ran it, and the guest wave with it. - return false; + return RefuseHalfBranch("exit in body"); } } - // The SGPR pairs the body writes, and those it writes only with a subset of the EXEC it - // began with (a saved EXEC, a compare, an AND with EXEC or such a pair). + // The scalar registers and SCC the body may write. UInt128 writes = 0; var writesScc = false; - UInt128 pairs = 0; for (var block = first; block < join; block++) { for (var index = blocks[block].StartIndex; index < blocks[block].EndIndex; index++) @@ -172,60 +261,137 @@ private bool IsHalfLocalBody(IReadOnlyList blocks, int[][] successo var instruction = instructions[index]; if (!IsHalfLocalBodyInstruction(instruction)) { - return false; + return RefuseHalfBranch($"instruction {instruction.Encoding}:{instruction.Opcode}{(instruction.Control is Gen5DppControl or Gen5Dpp8Control ? "+dpp" : string.Empty)}"); } var (_, _, mayWrite, mayWriteScc) = ScalarEffects(instruction); writes |= mayWrite; writesScc |= mayWriteScc; - pairs |= mayWrite; } } - var subset = pairs & ~(UInt128.One << (int)ExecLoRegister | UInt128.One << (int)ExecHiRegister); + // Every EXEC write must leave EXEC a subset of what it was when the body began. A write + // may restore a pair only where that pair is known to hold such a subset: on every path + // from the body's start to the write, the pair's last write is one with lanes of EXEC + // (WritesExecSubsetPair). That is a must-analysis over the body's blocks: nothing is + // known at the start (a pair from outside the body may hold anything), the paths meet + // by intersection, and any other write of a register forgets its pair. + var bodyCount = join - first; + var predecessors = new List[bodyCount]; + for (var block = first; block < join; block++) + { + predecessors[block - first] = []; + } + + for (var block = first; block < join; block++) + { + foreach (var successor in successors[block]) + { + if (successor >= first && successor < join) + { + predecessors[successor - first].Add(block); + } + } + } + + var known = new UInt128[bodyCount]; + Array.Fill(known, UInt128.MaxValue); + known[0] = 0; for (var changed = true; changed;) { changed = false; for (var block = first; block < join; block++) { - for (var index = blocks[block].StartIndex; index < blocks[block].EndIndex; index++) + var state = block == first ? 0 : UInt128.MaxValue; + foreach (var predecessor in predecessors[block - first]) { - var instruction = instructions[index]; - var (_, _, mayWrite, _) = ScalarEffects(instruction); - var nonExec = mayWrite & ~(UInt128.One << (int)ExecLoRegister | UInt128.One << (int)ExecHiRegister); - if (nonExec == 0 || (nonExec & subset) == 0) - { - continue; - } + state &= SubsetPairsAfter(blocks[predecessor], known[predecessor - first], out _); + } - if (!WritesExecSubsetPair(instruction, subset, out var pair) || - (nonExec & ~(UInt128.One << (int)pair | UInt128.One << (int)(pair + 1))) != 0) - { - if ((subset & nonExec) != 0) - { - subset &= ~nonExec; - changed = true; - } - } + if (state != known[block - first]) + { + known[block - first] = state; + changed = true; } } } - // A subset pair the body reads must be one it wrote first: none may be live into it. - subset &= ~liveIn[first]; for (var block = first; block < join; block++) { - for (var index = blocks[block].StartIndex; index < blocks[block].EndIndex; index++) + SubsetPairsAfter(blocks[block], known[block - first], out var widening); + if (widening is not null) + { + return RefuseHalfBranch($"widening exec write {widening.Opcode}"); + } + } + + var execBits = UInt128.One << (int)ExecLoRegister | UInt128.One << (int)ExecHiRegister; + var liveWrites = writes & ~execBits & liveIn[join]; + if (liveWrites != 0 || (writesScc && sccLiveIn[join])) + { + if (HalfBranchReport) { - if (WritesExec(instructions[index]) && !NarrowsOrRestoresExec(instructions[index], subset)) + var names = new List(); + for (var register = 0; register < 128; register++) { - return false; + if ((liveWrites & (UInt128.One << register)) != 0) + { + names.Add($"s{register}"); + } } + + if (writesScc && sccLiveIn[join]) + { + names.Add("scc"); + } + + return RefuseHalfBranch($"scalar writes live at join: {string.Join(',', names)}"); } + + return false; } + return true; + } + + /// Runs one block of a half-local body over , the register + /// pairs known to hold a subset of the body's starting EXEC on entry, and returns the pairs + /// known after it. is the first EXEC write that could turn on a + /// lane the body began without, or null. + private UInt128 SubsetPairsAfter(ShaderBlock block, UInt128 subset, out Gen5ShaderInstruction? widening) + { + widening = null; + var instructions = _request.Program.Instructions; var execBits = UInt128.One << (int)ExecLoRegister | UInt128.One << (int)ExecHiRegister; - return (writes & ~execBits & liveIn[join]) == 0 && !(writesScc && sccLiveIn[join]); + for (var index = block.StartIndex; index < block.EndIndex; index++) + { + var instruction = instructions[index]; + if (WritesExec(instruction) && !NarrowsOrRestoresExec(instruction, subset)) + { + widening ??= instruction; + } + + var (_, _, mayWrite, _) = ScalarEffects(instruction); + var nonExec = mayWrite & ~execBits; + if (nonExec == 0) + { + continue; + } + + if (WritesExecSubsetPair(instruction, subset, out var pair)) + { + var pairBits = UInt128.One << (int)pair | UInt128.One << (int)(pair + 1); + if ((nonExec & ~pairBits) == 0) + { + subset = (subset & ~nonExec) | pairBits; + continue; + } + } + + subset &= ~nonExec; + } + + return subset; } /// Work a half may run, or skip, without its partner in a forward EXEC body. @@ -256,7 +422,11 @@ private static bool IsHalfLocalBodyInstruction(Gen5ShaderInstruction instruction case Gen5ShaderEncoding.Vop3: case Gen5ShaderEncoding.Vop3p: case Gen5ShaderEncoding.Vopc: - return instruction.Control is not (Gen5DppControl or Gen5Dpp8Control) && + // DPP8 reads lanes of its own group of eight and the RDNA DPP16 controls lanes of + // its own row of sixteen, so they stay in the half and are emitted as shuffles + // inside that half's simdgroup. Other DPP16 controls (GFX9's wave shifts and + // row broadcasts) are not taken. + return (instruction.Control is not Gen5DppControl dpp || IsRowLocalDppControl(dpp.Control)) && !opcode.StartsWith("VReadlane", StringComparison.Ordinal) && !opcode.StartsWith("VReadfirstlane", StringComparison.Ordinal) && !opcode.StartsWith("VWritelane", StringComparison.Ordinal) && @@ -277,6 +447,12 @@ private static bool IsHalfLocalBodyInstruction(Gen5ShaderInstruction instruction } } + /// quad_perm, row_shl, row_shr, row_ror, row_mirror, row_half_mirror, row_share and + /// row_xmask: the DPP16 controls whose source lane is in the reading lane's row. + private static bool IsRowLocalDppControl(uint control) => + control is <= 0xFF or (>= 0x101 and <= 0x10F) or (>= 0x111 and <= 0x11F) or (>= 0x121 and <= 0x12F) or + 0x140 or 0x141 or (>= 0x150 and <= 0x16F); + private static bool WritesExec(Gen5ShaderInstruction instruction) { var opcode = instruction.Opcode; @@ -488,11 +664,12 @@ private static (UInt128 Reads, bool ReadsScc, UInt128 Writes, bool WritesScc) Sc Gen5ShaderEncoding.Mtbuf or Gen5ShaderEncoding.Mimg or Gen5ShaderEncoding.Flat or Gen5ShaderEncoding.Ds; UInt128 reads = 0; var readsScc = false; - foreach (var source in instruction.Sources) + for (var sourceIndex = 0; sourceIndex < instruction.Sources.Count; sourceIndex++) { + var source = instruction.Sources[sourceIndex]; if (source.Kind == Gen5OperandKind.ScalarRegister) { - reads |= Bits(source.Value, memory ? 8u : 2u); + reads |= Bits(source.Value, ScalarSourceWidth(instruction, sourceIndex, memory)); } else if (source.Kind == Gen5OperandKind.EncodedConstant) { @@ -525,11 +702,20 @@ private static (UInt128 Reads, bool ReadsScc, UInt128 Writes, bool WritesScc) Sc var (writes, _) = DefiniteScalarWrites(instruction); var width = MayScalarDestinationWidth(opcode); - foreach (var destination in instruction.Destinations) + if (IsEnumeratedScalarDestination(instruction, width, out var firstDestination)) { - if (destination.Kind == Gen5OperandKind.ScalarRegister) + // A load that lists every register it writes (S_LOAD_DWORDX4 s16..s19) writes + // those and no more: the width already counts them. + writes |= Bits(firstDestination, width); + } + else + { + foreach (var destination in instruction.Destinations) { - writes |= Bits(destination.Value, width); + if (destination.Kind == Gen5OperandKind.ScalarRegister) + { + writes |= Bits(destination.Value, width); + } } } @@ -538,6 +724,82 @@ private static (UInt128 Reads, bool ReadsScc, UInt128 Writes, bool WritesScc) Sc return (reads, readsScc, writes, writesScc); } + /// How many registers from a scalar source operand an instruction may read, at most. + /// A 32-bit ALU operand reads one register, a 64-bit one (an opcode naming 64 anywhere, a + /// lane mask, a carry, the SAD family's packed operands) two. A memory operand reads its + /// descriptor or address in full: an S_LOAD base pair, an S_BUFFER_LOAD or MUBUF/MTBUF + /// buffer resource (4), an image resource (8) and sampler (4), and one register for a + /// scalar offset or M0. Anything else reads eight. Under-reading would let a body's write + /// go unseen, so every shape not named here keeps the wider count. + private static uint ScalarSourceWidth(Gen5ShaderInstruction instruction, int sourceIndex, bool memory) + { + var opcode = instruction.Opcode; + if (memory) + { + switch (instruction.Encoding) + { + case Gen5ShaderEncoding.Smrd or Gen5ShaderEncoding.Smem + when opcode.StartsWith("SLoad", StringComparison.Ordinal): + return sourceIndex == 0 ? 2u : 1u; + case Gen5ShaderEncoding.Smrd or Gen5ShaderEncoding.Smem + when opcode.StartsWith("SBufferLoad", StringComparison.Ordinal): + return sourceIndex == 0 ? 4u : 1u; + case Gen5ShaderEncoding.Mubuf or Gen5ShaderEncoding.Mtbuf when sourceIndex >= 1: + // Vector address, buffer resource, scalar offset, then M0 for an LDS load. + return sourceIndex == 1 ? 4u : 1u; + case Gen5ShaderEncoding.Mimg when instruction.Control is Gen5ImageControl && + sourceIndex >= instruction.Sources.Count - 2 && + instruction.Sources[^2].Kind == Gen5OperandKind.ScalarRegister && + instruction.Sources[^1].Kind == Gen5OperandKind.ScalarRegister: + // The vector addresses, then the image resource and the sampler. + return sourceIndex == instruction.Sources.Count - 2 ? 8u : 4u; + default: + return 8u; + } + } + + if (opcode.Contains("64", StringComparison.Ordinal) || + opcode.StartsWith("VCndmask", StringComparison.Ordinal) || + opcode.Contains("Co", StringComparison.Ordinal) || + opcode.Contains("Addc", StringComparison.Ordinal) || + opcode.Contains("Subb", StringComparison.Ordinal) || + opcode.Contains("DivFmas", StringComparison.Ordinal) || + opcode.Contains("sad", StringComparison.OrdinalIgnoreCase)) + { + return 2u; + } + + return instruction.Encoding is Gen5ShaderEncoding.Sop1 or Gen5ShaderEncoding.Sop2 or Gen5ShaderEncoding.Sopc or + Gen5ShaderEncoding.Sopk or Gen5ShaderEncoding.Vop1 or Gen5ShaderEncoding.Vop2 or Gen5ShaderEncoding.Vop3 or + Gen5ShaderEncoding.Vop3p or Gen5ShaderEncoding.Vopc + ? 1u + : 2u; + } + + /// Whether the destinations are exactly consecutive scalar + /// registers, the whole write the opcode makes, listed one by one. + private static bool IsEnumeratedScalarDestination(Gen5ShaderInstruction instruction, uint width, out uint first) + { + first = 0; + var destinations = instruction.Destinations; + if (width < 2 || destinations.Count != width) + { + return false; + } + + for (var index = 0; index < destinations.Count; index++) + { + if (destinations[index].Kind != Gen5OperandKind.ScalarRegister || + destinations[index].Value != destinations[0].Value + (uint)index) + { + return false; + } + } + + first = destinations[0].Value; + return true; + } + /// The scalar registers an instruction certainly writes (its named destinations, /// a VOP3 scalar destination, the VCC a compare or carry writes unnamed), and whether it /// certainly writes SCC. @@ -601,9 +863,13 @@ private bool HalfLocalBranchesHoldNoExchange() _blockText[block].Contains(Wave64Barrier, StringComparison.Ordinal) || _blockText[block].Contains("threadgroup_barrier", StringComparison.Ordinal) || _blockText[block].Contains("sharpemu_wave_scratch", StringComparison.Ordinal) || - _blockText[block].Contains("simd_shuffle", StringComparison.Ordinal) || _blockText[block].Contains("simd_broadcast", StringComparison.Ordinal))) { + if (HalfBranchReport) + { + Console.Error.WriteLine($"[MSL][HALF-BRANCH] 0x{_request.Hash:X16} body block {block} still exchanges"); + } + HalfLocalBranchExchanged = true; return false; } diff --git a/src/SharpEmu.ShaderCompiler.Metal/Gen5MslTranslator.Resources.cs b/src/SharpEmu.ShaderCompiler.Metal/Gen5MslTranslator.Resources.cs index 562624da5..a8a5b82da 100644 --- a/src/SharpEmu.ShaderCompiler.Metal/Gen5MslTranslator.Resources.cs +++ b/src/SharpEmu.ShaderCompiler.Metal/Gen5MslTranslator.Resources.cs @@ -102,6 +102,11 @@ public static bool TryCompileProgram( if (!compiled && context.HalfLocalBranchExchanged) { + if (Environment.GetEnvironmentVariable("SHARPEMU_MSL_HALF_BRANCH_REPORT") == "1") + { + Console.Error.WriteLine($"[MSL][HALF-BRANCH] 0x{request.Hash:X16} program retranslated: an accepted body exchanged"); + } + options = options with { HalfLocalExecBranches = false }; context = new CompilationContext(request, options); compiled = context.TryCompile(out shader, out error); diff --git a/tests/SharpEmu.ShaderCompiler.Metal.Tests/MslHalfLocalBranchTests.cs b/tests/SharpEmu.ShaderCompiler.Metal.Tests/MslHalfLocalBranchTests.cs index d10a954bf..aaccc8e15 100644 --- a/tests/SharpEmu.ShaderCompiler.Metal.Tests/MslHalfLocalBranchTests.cs +++ b/tests/SharpEmu.ShaderCompiler.Metal.Tests/MslHalfLocalBranchTests.cs @@ -138,6 +138,82 @@ public void ABodyThatReadsAnotherLane_KeepsTheWholeWaveTest() Assert.DoesNotContain(HalfLocalTest, Compile(fixture, new Gen5MslCodegenOptions()).Source); } + // Lanes 0..19 take an if whose body is `body` (the high half has none of them); `after` runs + // at the join, then every lane stores v5. `pre` runs before the if. + private static uint[] IfProgram(uint[] pre, uint[] body, uint[] after) => + [ + 0xD7650000, 0x000100C1, // v_mbcnt_lo_u32_b32 v0, -1, 0 + 0xD7660000, 0x000200C1, // v_mbcnt_hi_u32_b32 v0, -1, v0 + 0x34080082, // v_lshlrev_b32 v4, 2, v0 + 0x7E0A0280, // v_mov_b32 v5, 0 + 0xBE840383, // s_mov_b32 s4, 3 + 0xBE8E0383, // s_mov_b32 s14, 3 + .. pre, + 0x7D880094, // v_cmp_gt_u32 vcc, 20, v0 + 0xBE82246A, // s_and_saveexec_b64 s[2:3], vcc + 0xBF880000 | (uint)body.Length, // s_cbranch_execz join + .. body, + 0xBEFE0402, // join: s_mov_b64 exec, s[2:3] + .. after, + 0xE0701000, 0x80020504, // buffer_store_dword v5, v4, s[8:11], 0 offen + 0xBF810000, // s_endpgm + ]; + + private const uint AddFiveToV5 = 0x4A0A0085; // v_add_nc_u32 v5, 5, v0 + + public static TheoryData ProofShapes => new() + { + // The body writes s5 and the join reads only s4, as a 32-bit operand. + { "s4-read-alone", IfProgram([], [0xBE850387, AddFiveToV5], [0x4A0A0A04]), true }, + // The join reads s[4:5] as a pair (s_mov_b64 s[6:7], s[4:5]), so s5 is live. + { "s4-read-as-pair", IfProgram([], [0xBE850387, AddFiveToV5], [0xBE860404, 0x4A0A0A07]), false }, + // The body writes s12; the store after the join reads only its buffer resource s[8:11]. + { "beside-the-resource", IfProgram([], [0xBE8C0387, AddFiveToV5], []), true }, + // The body writes s11 (with its own value), inside that resource. + { "inside-the-resource", IfProgram([], [0xBE8B030B, AddFiveToV5], []), false }, + // s_buffer_load_dwordx2 s[12:13] writes two registers; the join reads s14. + { "past-the-load", IfProgram([], [0xF4240304, 0xFA000000, 0xBF8CC07F, AddFiveToV5], [0x4A0A0A0E]), true }, + // The join reads s13, which the load wrote. + { "inside-the-load", IfProgram([], [0xF4240304, 0xFA000000, 0xBF8CC07F, AddFiveToV5], [0x4A0A0A0D]), false }, + // A nested if saves EXEC in s[4:5] and restores it before anything else writes s4; s4 is + // written afterwards, which no longer hides the restore's subset. + { "restore-then-overwrite", IfProgram([], [0x7D88008A, 0xBE84246A, AddFiveToV5, 0xBEFE0404, 0xBE840380], []), true }, + // s4 is overwritten between the save and the restore: the restore could turn lanes on. + { "overwrite-then-restore", IfProgram([], [0x7D88008A, 0xBE84246A, AddFiveToV5, 0xBE840380, 0xBEFE0404], []), false }, + // v_mov_b32_dpp v5, v0 quad_perm:[1,0,3,2] reads a lane of its own quad. + { "dpp-quad-perm", IfProgram([], [0x7E0A02FA, 0xFF00B100], []), true }, + // The same DPP, then v_readlane_b32 s5, v5, 40: a lane of the other half. + { "dpp-then-readlane", IfProgram([], [0x7E0A02FA, 0xFF00B100, 0xD7600005, 0x00015105], []), false }, + }; + + [Theory] + [MemberData(nameof(ProofShapes))] + public void TheBodyProof_TakesExactlyTheHalfLocalShapes(string name, uint[] program, bool halfLocal) + { + var fixture = new Gen5ComputeFixture($"half-branch-proof-{name}", program, 8, 64 * 4); + var half = Compile(fixture, new Gen5MslCodegenOptions()); + if (halfLocal) + { + Assert.Contains(HalfLocalTest, half.Source); + } + else + { + Assert.DoesNotContain(HalfLocalTest, half.Source); + } + + if (Environment.GetEnvironmentVariable("SHARPEMU_TEST_REQUIRE_DEVICE") != "1") + { + return; + } + + Assert.True(MetalNative.IsAvailable, "A Metal device is required."); + var before = Compile(fixture, new Gen5MslCodegenOptions { HalfLocalExecBranches = false }); + var guarded = Compile(fixture, new Gen5MslCodegenOptions(ExecGuardElision: false) { HalfLocalExecBranches = false }); + var expected = Execute(fixture, guarded); + Assert.Equal(expected, Execute(fixture, before)); + Assert.Equal(expected, Execute(fixture, half)); + } + private static byte[] Execute(Gen5ComputeFixture fixture, Gen5MslShader shader) { Assert.True(MetalNative.TryCompileLibrary(shader.Source, out var library, out var compileError), compileError); From 1d3bba6ac56d6e6ef8831e6baf528680ebdf2c0b Mon Sep 17 00:00:00 2001 From: kuba Date: Mon, 16 Nov 2026 15:06:09 +0000 Subject: [PATCH 140/178] [Shader] Half-local branch liveness: an updating scalar destination is a read S_ADDK, S_MULK, S_CMOVK and S_BITSET0/1 list the register they update only as a destination, so the liveness pass saw a plain overwrite and a body's write looked dead at the join; the proof then accepted a body the two wave halves disagree on. --- .../Gen5MslTranslator.HalfBranches.cs | 16 +++++ .../MslHalfLocalLivenessSoundnessTests.cs | 66 +++++++++++++++++++ 2 files changed, 82 insertions(+) create mode 100644 tests/SharpEmu.ShaderCompiler.Metal.Tests/MslHalfLocalLivenessSoundnessTests.cs diff --git a/src/SharpEmu.ShaderCompiler.Metal/Gen5MslTranslator.HalfBranches.cs b/src/SharpEmu.ShaderCompiler.Metal/Gen5MslTranslator.HalfBranches.cs index 88f06b770..839f5005b 100644 --- a/src/SharpEmu.ShaderCompiler.Metal/Gen5MslTranslator.HalfBranches.cs +++ b/src/SharpEmu.ShaderCompiler.Metal/Gen5MslTranslator.HalfBranches.cs @@ -700,6 +700,22 @@ private static (UInt128 Reads, bool ReadsScc, UInt128 Writes, bool WritesScc) Sc opcode.StartsWith("SSubb", StringComparison.Ordinal) || opcode.StartsWith("SCmov", StringComparison.Ordinal) || opcode.StartsWith("SCbranchScc", StringComparison.Ordinal); + // S_ADDK, S_MULK, S_CMOVK and S_BITSET0/1 name their destination once, and it is also the + // operand they update (or keep, when a conditional move is not taken): a read, not only + // a write. Without it the destination looks dead before them. + if (opcode.StartsWith("SAddk", StringComparison.Ordinal) || opcode.StartsWith("SMulk", StringComparison.Ordinal) || + opcode.StartsWith("SCmovk", StringComparison.Ordinal) || opcode.StartsWith("SBitset0", StringComparison.Ordinal) || + opcode.StartsWith("SBitset1", StringComparison.Ordinal)) + { + foreach (var destination in instruction.Destinations) + { + if (destination.Kind == Gen5OperandKind.ScalarRegister) + { + reads |= Bits(destination.Value, IsWideScalarOpcode(opcode) ? 2u : 1u); + } + } + } + var (writes, _) = DefiniteScalarWrites(instruction); var width = MayScalarDestinationWidth(opcode); if (IsEnumeratedScalarDestination(instruction, width, out var firstDestination)) diff --git a/tests/SharpEmu.ShaderCompiler.Metal.Tests/MslHalfLocalLivenessSoundnessTests.cs b/tests/SharpEmu.ShaderCompiler.Metal.Tests/MslHalfLocalLivenessSoundnessTests.cs new file mode 100644 index 000000000..47cf7f945 --- /dev/null +++ b/tests/SharpEmu.ShaderCompiler.Metal.Tests/MslHalfLocalLivenessSoundnessTests.cs @@ -0,0 +1,66 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using Xunit; + +namespace SharpEmu.ShaderCompiler.Metal.Tests; + +/// The half-local branch proof must refuse a body whose scalar write is read after the +/// join. These shapes hide that read behind instructions whose destination is also a source the +/// liveness pass does not record. +public sealed class MslHalfLocalLivenessSoundnessTests +{ + private const string HalfLocalTest = "sharpemu_ballot(exec) == 0u"; + private const uint AddFiveToV5 = 0x4A0A0085; // v_add_nc_u32 v5, 5, v0 + + private static uint[] IfProgram(uint[] pre, uint[] body, uint[] after) => + [ + 0xD7650000, 0x000100C1, // v_mbcnt_lo_u32_b32 v0, -1, 0 + 0xD7660000, 0x000200C1, // v_mbcnt_hi_u32_b32 v0, -1, v0 + 0x34080082, // v_lshlrev_b32 v4, 2, v0 + 0x7E0A0280, // v_mov_b32 v5, 0 + 0xBE840383, // s_mov_b32 s4, 3 + 0xBE8E0383, // s_mov_b32 s14, 3 + .. pre, + 0x7D880094, // v_cmp_gt_u32 vcc, 20, v0 + 0xBE82246A, // s_and_saveexec_b64 s[2:3], vcc + 0xBF880000 | (uint)body.Length, // s_cbranch_execz join + .. body, + 0xBEFE0402, // join: s_mov_b64 exec, s[2:3] + .. after, + 0xE0701000, 0x80020504, // buffer_store_dword v5, v4, s[8:11], 0 offen + 0xBF810000, // s_endpgm + ]; + + private static void AssertRefused(string name, uint[] program) + { + var fixture = new Gen5ComputeFixture($"half-branch-liveness-{name}", program, 8, 64 * 4); + var request = Gen5ComputeFixtures.CreateComputeRequest(fixture, 64, 64); + Assert.True(Gen5MslTranslator.TryCompileProgram(request, out var shader, out var error, new Gen5MslCodegenOptions()), error); + Assert.DoesNotContain(HalfLocalTest, shader.Source); + } + + private static readonly uint[] BodyWritesS5 = [0xBE850387, AddFiveToV5]; // s_mov_b32 s5, 7 + + // The body writes s5; after the join s_addk_i32 s5, 1 reads it (read-modify-write), then v5 = s5. + [Fact] + public void SAddk_AfterTheJoin_ReadsTheBodysWrite() => + AssertRefused("saddk", IfProgram([], BodyWritesS5, [0xB7850001, 0x7E0A0205])); + + // s_mulk_i32 s5, 3 likewise. + [Fact] + public void SMulk_AfterTheJoin_ReadsTheBodysWrite() => + AssertRefused("smulk", IfProgram([], BodyWritesS5, [0xB8050003, 0x7E0A0205])); + + // s_cmovk_i32 s5, 9 writes s5 only when SCC is set, otherwise keeps the body's value. + // The body writes s5 with a scalar load, so it writes no SCC and SCC being live (the cmovk reads it) + // cannot refuse it by itself. + [Fact] + public void SCmovk_AfterTheJoin_KeepsTheBodysWriteWhenNotTaken() => + AssertRefused("scmovk", IfProgram([], [0xF4200144, 0xFA000000, 0xBF8CC07F, AddFiveToV5], [0xB1050009, 0x7E0A0205])); + + // s_bitset0_b32 s5, 1 clears one bit of s5 and keeps the rest (read-modify-write). + [Fact] + public void SBitset0_AfterTheJoin_ReadsTheBodysWrite() => + AssertRefused("sbitset0", IfProgram([], BodyWritesS5, [0xBE851B81, 0x7E0A0205])); +} From 8fcc4b937d084559f7f41c2d251b1d37d7ea0f2a Mon Sep 17 00:00:00 2001 From: kuba Date: Mon, 16 Nov 2026 17:14:12 +0000 Subject: [PATCH 141/178] [GPU] Split the prefetch's unresolved draw takes by what bounded the resolver's lead takes_unresolved now counts frontier= (the job was the newest submitted: the stream had produced nothing further to resolve ahead) and behind= (later jobs were queued and the one in-order resolving thread had not reached this one), with the worker's wait in each. The unresolved_by_gate kind is the job's own gate, which with dispatch and collector look-ahead is the last synchronous call or idle commit, not what held it. Co-Authored-By: Claude --- .../Gpu/Rendering/ParallelProgramPrefetch.cs | 24 ++++++++++-- .../ParallelProgramPrefetchCallerTests.cs | 37 +++++++++++++++++++ 2 files changed, 57 insertions(+), 4 deletions(-) diff --git a/src/SharpEmu.Libs/Gpu/Rendering/ParallelProgramPrefetch.cs b/src/SharpEmu.Libs/Gpu/Rendering/ParallelProgramPrefetch.cs index c43c5bc9b..63d21100d 100644 --- a/src/SharpEmu.Libs/Gpu/Rendering/ParallelProgramPrefetch.cs +++ b/src/SharpEmu.Libs/Gpu/Rendering/ParallelProgramPrefetch.cs @@ -422,7 +422,10 @@ public void NoteGateItem(long gate, GateItemKind kind) // Per kind of the item that last gated a draw's job: the draws submitted with a gate above the draw before them // (draw_gate_raises), the draw takes that found their job unresolved (busy or queued), the subset whose job the - // resolving thread had reached before its gate opened (gate-bound), and the worker's wait in them. + // resolving thread had reached before its gate opened (gate-bound), and the worker's wait in them. The kind is that + // of the job's own gate (Job.Gate): where draws look ahead of dispatches and collector calls it is the last item + // they do not, often a synchronous call or an idle commit long before the draw, so an unresolved take counted + // under a kind was held by it only when it is gate-bound as well. private long _lastDrawGate; private readonly long[] _drawGateRaises = new long[(int)GateItemKind.Count]; private readonly long[] _unresolvedByGate = new long[(int)GateItemKind.Count]; @@ -598,7 +601,7 @@ public bool TryTakeGraphics(RegisterBanks banks, in GraphicsProgramInputs inputs // well-prefetched burst is one, and two clock reads per draw were measurable. if (job.State == 0) { - var gateKind = NoteUnresolvedTake(job); + var gateKind = NoteUnresolvedTake(job, out var behind); var waitStarted = System.Diagnostics.Stopwatch.GetTimestamp(); // Caller work is reported separately, not disguised as a shorter resolver wait. // Keep long queues out of the claim routine's lock/finally frame. @@ -610,6 +613,7 @@ public bool TryTakeGraphics(RegisterBanks banks, in GraphicsProgramInputs inputs var waited = System.Diagnostics.Stopwatch.GetTimestamp() - waitStarted; Interlocked.Add(ref _waitTicks, waited); Interlocked.Add(ref _unresolvedWaitTicksByGate[(int)gateKind], waited); + Interlocked.Add(ref behind ? ref _unresolvedBehindWaitTicks : ref _unresolvedFrontierWaitTicks, waited); } } @@ -1049,8 +1053,17 @@ public string TakeComputeReport() // thread busy with another job, or queued behind others with its gate open (takes_unresolved). private long _unresolvedGated, _unresolvedBusy, _unresolvedQueued; - private GateItemKind NoteUnresolvedTake(Job job) + // The same takes by what bounded the resolving thread's lead (takes_unresolved frontier= and behind=): at the + // frontier the job was the newest submitted, so the stream had produced nothing further for it to resolve ahead + // (its lead is the command thread's); behind, later jobs were already queued and the one resolving thread, which + // resolves in submission order, had not got through this one yet. With the worker's wait in each. Submitted is + // read without the lock: a stale value only moves a take between the two. + private long _unresolvedFrontier, _unresolvedBehind, _unresolvedFrontierWaitTicks, _unresolvedBehindWaitTicks; + + private GateItemKind NoteUnresolvedTake(Job job, out bool behind) { + behind = Submitted > job.Index + 1; + Interlocked.Increment(ref behind ? ref _unresolvedBehind : ref _unresolvedFrontier); if (job.Gate > Volatile.Read(ref _executedGate)) Interlocked.Increment(ref _unresolvedGated); else if (Volatile.Read(ref _running)) Interlocked.Increment(ref _unresolvedBusy); else Interlocked.Increment(ref _unresolvedQueued); @@ -1092,7 +1105,10 @@ public string TakeResolverReport() var lastCpu = Interlocked.Exchange(ref _lastResolverCpu, cpu); var cpuMs = cpu < 0 || lastCpu < 0 ? -1.0 : (cpu - lastCpu) / 1e6; return $"takes_unresolved=(busy={Interlocked.Exchange(ref _unresolvedBusy, 0)},gated={Interlocked.Exchange(ref _unresolvedGated, 0)}," + - $"queued={Interlocked.Exchange(ref _unresolvedQueued, 0)},started={Interlocked.Exchange(ref _unresolvedStarted, 0)}) " + + $"queued={Interlocked.Exchange(ref _unresolvedQueued, 0)},started={Interlocked.Exchange(ref _unresolvedStarted, 0)}," + + $"frontier={Interlocked.Exchange(ref _unresolvedFrontier, 0)},behind={Interlocked.Exchange(ref _unresolvedBehind, 0)}," + + $"frontier_wait_ms={Milliseconds(Interlocked.Exchange(ref _unresolvedFrontierWaitTicks, 0)).ToString("F1", culture)}," + + $"behind_wait_ms={Milliseconds(Interlocked.Exchange(ref _unresolvedBehindWaitTicks, 0)).ToString("F1", culture)}) " + $"unresolved_by_gate=({FormatByKind(_unresolvedByGate)}) gate_bound_by_gate=({FormatByKind(_gateBoundByGate)}) " + $"unresolved_wait_ms_by_gate=({FormatByKind(_unresolvedWaitTicksByGate, ticks => Milliseconds(ticks).ToString("F1", culture))}) " + $"draw_gate_raises=({FormatByKind(_drawGateRaises)}) {TakeDrawLookaheadReport()} resolver_jobs={Interlocked.Exchange(ref _resolverJobs, 0)} " + diff --git a/tests/SharpEmu.Libs.Tests/Gpu/Rendering/ParallelProgramPrefetchCallerTests.cs b/tests/SharpEmu.Libs.Tests/Gpu/Rendering/ParallelProgramPrefetchCallerTests.cs index 41b4724b5..7f9b02c9f 100644 --- a/tests/SharpEmu.Libs.Tests/Gpu/Rendering/ParallelProgramPrefetchCallerTests.cs +++ b/tests/SharpEmu.Libs.Tests/Gpu/Rendering/ParallelProgramPrefetchCallerTests.cs @@ -309,4 +309,41 @@ public void TakingACompletedJobReportsNoWaitAndAnUnfinishedOneDoes() Assert.True(waiter.Wait(TimeSpan.FromSeconds(10)) && waiter.Result); Assert.True(f.Prefetch.TakeCounters().WaitMilliseconds > 0); } + + // An unresolved take of the newest job counts at the frontier (nothing further submitted for the resolving thread + // to run ahead on); one with later jobs already queued counts behind. + [Theory] + [InlineData(false)] + [InlineData(true)] + public void AnUnresolvedTakeCountsAtTheFrontierOrBehindByTheJobsSubmittedAfterIt(bool later) + { + using var f = new Fixture(false); + var banks = Banks(); + _ = f.Prefetch.TakeResolverReport(); + Task waiter; + ParallelProgramPrefetch.Job? next = null; + Monitor.Enter(f.QueueLock); + try + { + // The resolving thread cannot start a job while this thread holds the queue lock. + var job = f.Prefetch.Submit(banks); + if (later) + { + next = f.Prefetch.Submit(banks); + } + + waiter = Task.Run(() => f.Take(banks, job)); + Assert.False(waiter.Wait(50)); + } + finally { Monitor.Exit(f.QueueLock); } + + Assert.True(waiter.Wait(TimeSpan.FromSeconds(10)) && waiter.Result); + var report = f.Prefetch.TakeResolverReport(); + Assert.Contains(later ? "frontier=0,behind=1," : "frontier=1,behind=0,", report); + if (next is not null) + { + f.Idle(); + Assert.True(f.Take(banks, next)); + } + } } From 13132ba1b967aaf0152a18e46495dabfc117e0de Mon Sep 17 00:00:00 2001 From: kuba Date: Mon, 16 Nov 2026 17:52:45 +0000 Subject: [PATCH 142/178] [GPU] Fill the resolve memo key with the offset in a register Put/PutSpan took the key as a span and the offset by ref: the offset's address was taken and each inlined call made a span temporary, so the JIT kept both in the stack frame and every one of the key's ~70 fields paid stores and reloads of them (~18 instructions a field). The writers now take the key's first byte and return the new offset, with one bound check against the key buffer each; the key bytes are the same. DS-shaped bench (GameShaped, COPIED_TABLES): Fill's resolver self time 254 -> 95 samples. Co-Authored-By: Claude --- .../Gpu/Pipelines/GraphicsResolveMemo.cs | 194 ++++++++++-------- 1 file changed, 108 insertions(+), 86 deletions(-) diff --git a/src/SharpEmu.Libs/Gpu/Pipelines/GraphicsResolveMemo.cs b/src/SharpEmu.Libs/Gpu/Pipelines/GraphicsResolveMemo.cs index d02bf1625..bb11bdf45 100644 --- a/src/SharpEmu.Libs/Gpu/Pipelines/GraphicsResolveMemo.cs +++ b/src/SharpEmu.Libs/Gpu/Pipelines/GraphicsResolveMemo.cs @@ -237,136 +237,158 @@ public bool Fill(RegisterBanks banks, ReadOnlySpan targetExpo PixelOutputBlendBits blendBits) { FillSerial++; - var key = _key.AsSpan(); + ref var key = ref MemoryMarshal.GetArrayDataReference(_key); var at = 0; var vertex = banks.Shader.Vertex; var pixel = banks.Shader.Pixel; var context = banks.Context; var shaderInterface = context.ShaderInterface; - Put(key, ref at, flags); - Put(key, ref at, targetExportMapping.Length); - PutSpan(key, ref at, targetExportMapping); + at = Put(ref key, at, flags); + at = Put(ref key, at, targetExportMapping.Length); + at = PutSpan(ref key, at, targetExportMapping); // The vertex stage: every plain register (the hull, legacy and export user scalars are not read). - Put(key, ref at, vertex.ExportAddress); - Put(key, ref at, vertex.LocalAddress); - Put(key, ref at, vertex.HullAddress); - Put(key, ref at, vertex.HullUserDataAddress); - Put(key, ref at, vertex.HullResource1); - Put(key, ref at, vertex.HullResource2); - Put(key, ref at, vertex.GeometryAddress); - Put(key, ref at, vertex.GeometryUserDataAddress); - Put(key, ref at, vertex.GeometryResource1); - Put(key, ref at, vertex.GeometryResource2); - Put(key, ref at, vertex.ExportResource1); - Put(key, ref at, vertex.ExportResource2); - Put(key, ref at, vertex.LegacyVertexAddress); - Put(key, ref at, vertex.LegacyVertexResource1); - Put(key, ref at, vertex.LegacyVertexResource2); - Put(key, ref at, vertex.GeometryUserScalars.Count); + at = Put(ref key, at, vertex.ExportAddress); + at = Put(ref key, at, vertex.LocalAddress); + at = Put(ref key, at, vertex.HullAddress); + at = Put(ref key, at, vertex.HullUserDataAddress); + at = Put(ref key, at, vertex.HullResource1); + at = Put(ref key, at, vertex.HullResource2); + at = Put(ref key, at, vertex.GeometryAddress); + at = Put(ref key, at, vertex.GeometryUserDataAddress); + at = Put(ref key, at, vertex.GeometryResource1); + at = Put(ref key, at, vertex.GeometryResource2); + at = Put(ref key, at, vertex.ExportResource1); + at = Put(ref key, at, vertex.ExportResource2); + at = Put(ref key, at, vertex.LegacyVertexAddress); + at = Put(ref key, at, vertex.LegacyVertexResource1); + at = Put(ref key, at, vertex.LegacyVertexResource2); + at = Put(ref key, at, vertex.GeometryUserScalars.Count); if (flags.PixelActive) { - Put(key, ref at, pixel.Address); - Put(key, ref at, pixel.UserDataAddress); - Put(key, ref at, pixel.AuxiliaryTableAddress); - Put(key, ref at, pixel.Resource1); - Put(key, ref at, pixel.Resource2); - Put(key, ref at, pixel.UserScalars.Count); + at = Put(ref key, at, pixel.Address); + at = Put(ref key, at, pixel.UserDataAddress); + at = Put(ref key, at, pixel.AuxiliaryTableAddress); + at = Put(ref key, at, pixel.Resource1); + at = Put(ref key, at, pixel.Resource2); + at = Put(ref key, at, pixel.UserScalars.Count); } // The context registers the resolution reads (ShaderPipelineCache, HostViewportTransform, ColorTargetResolver, // PixelExportRouting): the blend state as the bits it resolves from (PixelOutputBlend), the viewport's transform. - Put(key, ref at, context.ShaderStages); - Put(key, ref at, context.RenderTargetMask); - PutSpan(key, ref at, context.ColorTargets.AsSpan()); - Put(key, ref at, blendBits.Value); - Put(key, ref at, context.Clip); - Put(key, ref at, context.DepthRenderOverride); - Put(key, ref at, context.DepthTarget.ZInfo); - Put(key, ref at, context.ScreenViewport.TransformControl); + at = Put(ref key, at, context.ShaderStages); + at = Put(ref key, at, context.RenderTargetMask); + at = PutSpan(ref key, at, context.ColorTargets.AsSpan()); + at = Put(ref key, at, blendBits.Value); + at = Put(ref key, at, context.Clip); + at = Put(ref key, at, context.DepthRenderOverride); + at = Put(ref key, at, context.DepthTarget.ZInfo); + at = Put(ref key, at, context.ScreenViewport.TransformControl); ref readonly var viewport = ref context.ScreenViewport.Primary; - Put(key, ref at, viewport.MinDepth); - Put(key, ref at, viewport.MaxDepth); - Put(key, ref at, viewport.XScale); - Put(key, ref at, viewport.XOffset); - Put(key, ref at, viewport.YScale); - Put(key, ref at, viewport.YOffset); - Put(key, ref at, viewport.ZScale); - Put(key, ref at, viewport.ZOffset); - PutSpan(key, ref at, context.UserClipPlanes.AsSpan()); + at = Put(ref key, at, viewport.MinDepth); + at = Put(ref key, at, viewport.MaxDepth); + at = Put(ref key, at, viewport.XScale); + at = Put(ref key, at, viewport.XOffset); + at = Put(ref key, at, viewport.YScale); + at = Put(ref key, at, viewport.YOffset); + at = Put(ref key, at, viewport.ZScale); + at = Put(ref key, at, viewport.ZOffset); + at = PutSpan(ref key, at, context.UserClipPlanes.AsSpan()); // The whole shader interface. - Put(key, ref at, shaderInterface.VertexOutputConfiguration); - Put(key, ref at, shaderInterface.PositionExportFormat); - Put(key, ref at, shaderInterface.VertexOutputControl); - PutSpan(key, ref at, shaderInterface.PixelInterpolatorSettings.AsSpan()); - Put(key, ref at, shaderInterface.PixelInterpolatorWritten); - Put(key, ref at, shaderInterface.IndexExportFormat); - Put(key, ref at, shaderInterface.PrimitiveShaderSubgroupControl); - Put(key, ref at, shaderInterface.GeometryInstanceCount); - Put(key, ref at, shaderInterface.GeometryOnChipControl); - Put(key, ref at, shaderInterface.MaxTessellationLevel); - Put(key, ref at, shaderInterface.MinTessellationLevel); - Put(key, ref at, shaderInterface.MaxOutputPerSubgroup); - Put(key, ref at, shaderInterface.ExportRingItemSize); - Put(key, ref at, shaderInterface.GeometryMaxVerticesOut); - Put(key, ref at, shaderInterface.GeometryOutputPrimitiveType); - Put(key, ref at, shaderInterface.PrimitiveIdEnable); - Put(key, ref at, shaderInterface.VertexReuseOff); - Put(key, ref at, shaderInterface.TessellationDistribution); - Put(key, ref at, shaderInterface.LocalHullConfiguration); - Put(key, ref at, shaderInterface.TessellationFactorParameter); - Put(key, ref at, shaderInterface.DepthExportFormat); - PutSpan(key, ref at, shaderInterface.TargetOutputModes.AsSpan()); - Put(key, ref at, shaderInterface.PixelInputEnable); - Put(key, ref at, shaderInterface.PixelInputAddress); - Put(key, ref at, shaderInterface.PixelInputControl); - Put(key, ref at, shaderInterface.BarycentricControl); - Put(key, ref at, shaderInterface.ColorShaderMask); - Put(key, ref at, shaderInterface.ScanShaderControl); - Put(key, ref at, shaderInterface.DepthShaderControl); + at = Put(ref key, at, shaderInterface.VertexOutputConfiguration); + at = Put(ref key, at, shaderInterface.PositionExportFormat); + at = Put(ref key, at, shaderInterface.VertexOutputControl); + at = PutSpan(ref key, at, shaderInterface.PixelInterpolatorSettings.AsSpan()); + at = Put(ref key, at, shaderInterface.PixelInterpolatorWritten); + at = Put(ref key, at, shaderInterface.IndexExportFormat); + at = Put(ref key, at, shaderInterface.PrimitiveShaderSubgroupControl); + at = Put(ref key, at, shaderInterface.GeometryInstanceCount); + at = Put(ref key, at, shaderInterface.GeometryOnChipControl); + at = Put(ref key, at, shaderInterface.MaxTessellationLevel); + at = Put(ref key, at, shaderInterface.MinTessellationLevel); + at = Put(ref key, at, shaderInterface.MaxOutputPerSubgroup); + at = Put(ref key, at, shaderInterface.ExportRingItemSize); + at = Put(ref key, at, shaderInterface.GeometryMaxVerticesOut); + at = Put(ref key, at, shaderInterface.GeometryOutputPrimitiveType); + at = Put(ref key, at, shaderInterface.PrimitiveIdEnable); + at = Put(ref key, at, shaderInterface.VertexReuseOff); + at = Put(ref key, at, shaderInterface.TessellationDistribution); + at = Put(ref key, at, shaderInterface.LocalHullConfiguration); + at = Put(ref key, at, shaderInterface.TessellationFactorParameter); + at = Put(ref key, at, shaderInterface.DepthExportFormat); + at = PutSpan(ref key, at, shaderInterface.TargetOutputModes.AsSpan()); + at = Put(ref key, at, shaderInterface.PixelInputEnable); + at = Put(ref key, at, shaderInterface.PixelInputAddress); + at = Put(ref key, at, shaderInterface.PixelInputControl); + at = Put(ref key, at, shaderInterface.BarycentricControl); + at = Put(ref key, at, shaderInterface.ColorShaderMask); + at = Put(ref key, at, shaderInterface.ScanShaderControl); + at = Put(ref key, at, shaderInterface.DepthShaderControl); // The user data words each stage resolves with (ShaderPipelineCache.UserData): its declared count, else the // registers the guest wrote. _userDataStart = at; - if (!PutUserData(key, ref at, vertex.GeometryUserScalars, vertex.GeometryResource2.UserScalarCount) || - (flags.PixelActive && !PutUserData(key, ref at, pixel.UserScalars, pixel.Resource2.UserScalarCount))) + at = PutUserData(ref key, at, vertex.GeometryUserScalars, vertex.GeometryResource2.UserScalarCount); + if (at >= 0 && flags.PixelActive) + { + at = PutUserData(ref key, at, pixel.UserScalars, pixel.Resource2.UserScalarCount); + } + + if (at < 0) { return false; } _keyLength = at; - Hash = XxHash3.HashToUInt64(key[..at]); + Hash = XxHash3.HashToUInt64(_key.AsSpan(0, at)); return true; } - private static bool PutUserData(Span key, ref int at, UserScalarRegisters registers, uint declared) + // The key's offset after the user data, or -1 when the count is over the bank. The writers take the key's first byte + // and return the offset rather than take a span and a ref to the offset: the offset's address and a span per field + // put every field's write through memory (the inlined spans were more locals than the JIT keeps in registers). + // Each write still stops at the key's end. + private static int PutUserData(ref byte key, int at, UserScalarRegisters registers, uint declared) { var count = declared != 0 ? declared : registers.Count; if (count > UserScalarRegisters.Capacity) { - return false; + return -1; } - Put(key, ref at, count); - PutSpan(key, ref at, registers.ValueSpan((int)count)); - return true; + at = Put(ref key, at, count); + return PutSpan(ref key, at, registers.ValueSpan((int)count)); } - private static void Put(Span key, ref int at, in T value) where T : unmanaged + private static int Put(ref byte key, int at, T value) where T : unmanaged { - MemoryMarshal.Write(key[at..], in value); - at += System.Runtime.CompilerServices.Unsafe.SizeOf(); + var size = System.Runtime.CompilerServices.Unsafe.SizeOf(); + if ((ulong)(uint)at + (ulong)size > MaxKeyBytes) + { + ThrowKeyOverflow(); + } + + System.Runtime.CompilerServices.Unsafe.WriteUnaligned(ref System.Runtime.CompilerServices.Unsafe.Add(ref key, at), value); + return at + size; } - private static void PutSpan(Span key, ref int at, ReadOnlySpan values) where T : unmanaged + private static int PutSpan(ref byte key, int at, ReadOnlySpan values) where T : unmanaged { var bytes = MemoryMarshal.AsBytes(values); - bytes.CopyTo(key[at..]); - at += bytes.Length; + if ((ulong)(uint)at + (ulong)(uint)bytes.Length > MaxKeyBytes) + { + ThrowKeyOverflow(); + } + + bytes.CopyTo(MemoryMarshal.CreateSpan(ref System.Runtime.CompilerServices.Unsafe.Add(ref key, at), bytes.Length)); + return at + bytes.Length; } + [System.Diagnostics.CodeAnalysis.DoesNotReturn] + private static void ThrowKeyOverflow() => throw new InvalidOperationException("The resolve memo key is over its buffer."); + // The entry with the filled key, or null. public Entry? Find() { From 121417de77276b50fd5932fa65f5862a74014e59 Mon Sep 17 00:00:00 2001 From: kuba Date: Mon, 16 Nov 2026 17:52:45 +0000 Subject: [PATCH 143/178] [Shader] Merge a read proof's address-ordered runs instead of sorting them Each level records its reads in address order (ReadLevel sorts them, a fixed plan reads its runs in offset order), so a proof's reads are a few ascending runs. They are merged one at a time into the ordered prefix through scratch buffers; more than 16 runs fall back to Array.Sort. Equal addresses may come out in either order, as with the unstable sort: Build refuses them when their words differ and keeps one otherwise. In the Demon's Souls resolver profile the sort was ~3.4% of the thread's CPU. Co-Authored-By: Claude --- .../Resources/MaterializationProgram.cs | 74 ++++++++++++++++++- 1 file changed, 73 insertions(+), 1 deletion(-) diff --git a/src/SharpEmu.ShaderCompiler/Resources/MaterializationProgram.cs b/src/SharpEmu.ShaderCompiler/Resources/MaterializationProgram.cs index 42afa9c60..14aedf8bc 100644 --- a/src/SharpEmu.ShaderCompiler/Resources/MaterializationProgram.cs +++ b/src/SharpEmu.ShaderCompiler/Resources/MaterializationProgram.cs @@ -125,6 +125,9 @@ internal sealed class Scratch public ulong[] ReadAddresses = new ulong[64]; public uint[] ReadWords = new uint[64]; public int ReadCount; + // Where ReadProof.Build merges the reads' address-ordered runs. + public ulong[] MergeAddresses = new ulong[64]; + public uint[] MergeWords = new uint[64]; public readonly List Unreadable = []; public void NoteRead(ulong address, uint word) @@ -591,7 +594,7 @@ internal sealed class ReadProof var count = scratch.ReadCount; var addresses = scratch.ReadAddresses; var words = scratch.ReadWords; - Array.Sort(addresses, words, 0, count); + SortReads(scratch, count); var unique = 0; var ranges = 0; for (var index = 0; index < count; index++) @@ -678,6 +681,75 @@ internal sealed class ReadProof }; } + // Most runs of recorded reads to merge rather than sort: each level records its reads in address order. + private const int MaxMergedRuns = 16; + + // The recorded reads in address order. A level's reads are recorded in address order (ReadLevel sorts them, a + // fixed plan reads its runs in offset order), so the reads are a few ascending runs, merged here one into the + // ordered prefix before it; more runs than that are sorted. Equal addresses may end in any order: Build refuses + // them when their words differ and keeps one when they are the same. + private static void SortReads(Scratch scratch, int count) + { + var addresses = scratch.ReadAddresses; + var words = scratch.ReadWords; + var runs = 1; + for (var index = 1; index < count; index++) + { + if (addresses[index] < addresses[index - 1] && ++runs > MaxMergedRuns) + { + Array.Sort(addresses, words, 0, count); + return; + } + } + + if (runs == 1) + { + return; + } + + if (scratch.MergeAddresses.Length < count) + { + scratch.MergeAddresses = new ulong[Math.Max(count, scratch.MergeAddresses.Length * 2)]; + scratch.MergeWords = new uint[scratch.MergeAddresses.Length]; + } + + var mergedAddresses = scratch.MergeAddresses; + var mergedWords = scratch.MergeWords; + var ordered = 1; + while (ordered < count && addresses[ordered] >= addresses[ordered - 1]) ordered++; + while (ordered < count) + { + var end = ordered + 1; + while (end < count && addresses[end] >= addresses[end - 1]) end++; + // Merge [0, ordered) and [ordered, end) into the merge buffers, then back. + int left = 0, right = ordered, at = 0; + while (left < ordered && right < end) + { + if (addresses[right] < addresses[left]) + { + mergedAddresses[at] = addresses[right]; + mergedWords[at++] = words[right++]; + } + else + { + mergedAddresses[at] = addresses[left]; + mergedWords[at++] = words[left++]; + } + } + + while (left < ordered) + { + mergedAddresses[at] = addresses[left]; + mergedWords[at++] = words[left++]; + } + + // The rest of the right run is already in place after the merged part. + Array.Copy(mergedAddresses, addresses, at); + Array.Copy(mergedWords, words, at); + ordered = end; + } + } + // Whether the unique sorted addresses form exactly the proof's ranges. private static bool SameRanges(ReadProof proof, ulong[] addresses, int unique) { From ef1ac3d4c43a708ad58bf8e92a7fa0f1b11f8090 Mon Sep 17 00:00:00 2001 From: kuba Date: Mon, 16 Nov 2026 17:52:45 +0000 Subject: [PATCH 144/178] [GPU] Keep the resolver's per-job allocations and lookups off the hot path The concurrent-assumption pool holds 96 (was 32), above the 64 jobs the resolver can be ahead of the worker, so a resolver running ahead no longer allocates one with empty lists per job; slots are read before the exchange, so an empty one costs no atomic. GetFusedPrograms remembers the last memory and its registry: every draw stage asked the ConditionalWeakTable, which never drops a registry while its memory lives. DS-shaped bench: resolver allocation 280 -> ~120 B/job. Co-Authored-By: Claude --- .../Gen5ShaderTranslator.cs | 15 ++++++++++++++- .../V2/MetalRenderHost.ConcurrentResolve.cs | 12 +++++++++--- 2 files changed, 23 insertions(+), 4 deletions(-) diff --git a/src/SharpEmu.ShaderCompiler/Gen5ShaderTranslator.cs b/src/SharpEmu.ShaderCompiler/Gen5ShaderTranslator.cs index 745c0bc81..b55ecd7ee 100644 --- a/src/SharpEmu.ShaderCompiler/Gen5ShaderTranslator.cs +++ b/src/SharpEmu.ShaderCompiler/Gen5ShaderTranslator.cs @@ -103,9 +103,22 @@ private static FusedProgramRegistry GetFusedPrograms(ICpuMemory memory) memory = wrapper.Inner; } - return _fusedProgramsByMemory.GetValue(memory, static _ => new FusedProgramRegistry()); + // The memory looked up last and its registry: every draw stage looks its code address up here, and the table's + // lookup was most of that. The table never drops a registry while its memory lives, and this holds the memory. + if (Volatile.Read(ref _lastFusedPrograms) is { } last && ReferenceEquals(last.Memory, memory)) + { + return last.Registry; + } + + var registry = _fusedProgramsByMemory.GetValue(memory, static _ => new FusedProgramRegistry()); + Volatile.Write(ref _lastFusedPrograms, new LastFusedPrograms(memory, registry)); + return registry; } + private sealed record LastFusedPrograms(ICpuMemory Memory, FusedProgramRegistry Registry); + + private static LastFusedPrograms? _lastFusedPrograms; + /// /// Records the two code objects that AGC joins into one hardware shader. /// The entry code transfers control to the continuation with S_SETPC_B64, or with an diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.ConcurrentResolve.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.ConcurrentResolve.cs index 5b0f35bc4..489a2b124 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.ConcurrentResolve.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.ConcurrentResolve.cs @@ -580,9 +580,13 @@ public void Record(ConcurrentQuery query, ulong address, ulong size, bool owned) internal void BeginConcurrentResolve() { ConcurrentAssumptions? pooled = null; + // A plain read first: an empty slot costs no exchange. for (var slot = 0; slot < _assumptionPool.Length && pooled is null; slot++) { - pooled = Interlocked.Exchange(ref _assumptionPool[slot], null); + if (Volatile.Read(ref _assumptionPool[slot]) is not null) + { + pooled = Interlocked.Exchange(ref _assumptionPool[slot], null); + } } // Read before the versions and every guest byte: a write logged after this is one the resolution may have missed. @@ -608,7 +612,9 @@ internal void BeginConcurrentResolve() // Slots taken and filled with an exchange each: the resolving thread takes one per draw and the worker // returns one per draw, and a lock both took per draw was contended on every one (Demon's Souls, ~7000 a frame). private readonly ConcurrentAssumptions?[] _assumptionPool = new ConcurrentAssumptions?[MaxPooledAssumptions]; - private const int MaxPooledAssumptions = 32; + // Above the jobs a resolving thread can have resolved ahead of the worker (the command thread's queue of 64 items), + // so a resolver ahead of the worker still finds one rather than allocating it with its lists empty. + private const int MaxPooledAssumptions = 96; private const int MaxPooledAnswers = 4096; internal void ReleaseConcurrentAssumptions(object assumptionsObject) @@ -620,7 +626,7 @@ internal void ReleaseConcurrentAssumptions(object assumptionsObject) for (var slot = 0; slot < _assumptionPool.Length; slot++) { - if (Interlocked.CompareExchange(ref _assumptionPool[slot], assumptions, null) is null) + if (Volatile.Read(ref _assumptionPool[slot]) is null && Interlocked.CompareExchange(ref _assumptionPool[slot], assumptions, null) is null) { return; } From d73d6d5ab7bf279724de9e80d5b8e0c6bd51a89f Mon Sep 17 00:00:00 2001 From: kuba Date: Mon, 16 Nov 2026 18:02:46 +0000 Subject: [PATCH 145/178] [GPU] Read a draw's colour target export mapping without copying its resolution again ProgramInputsOf matched each bound slot's ColorTargetResolution? with `is { } r`, which copied the whole resolution (~320 bytes, 20 load/store pairs) a second time to read its one-byte ExportMapping; it is now read in place through Nullable.GetValueRefOrDefaultRef. Co-Authored-By: Claude --- src/SharpEmu.Libs/Gpu/Rendering/RenderExecutor.Prefetch.cs | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/src/SharpEmu.Libs/Gpu/Rendering/RenderExecutor.Prefetch.cs b/src/SharpEmu.Libs/Gpu/Rendering/RenderExecutor.Prefetch.cs index 8624abb32..6d74eb5b6 100644 --- a/src/SharpEmu.Libs/Gpu/Rendering/RenderExecutor.Prefetch.cs +++ b/src/SharpEmu.Libs/Gpu/Rendering/RenderExecutor.Prefetch.cs @@ -162,9 +162,11 @@ public static GraphicsProgramInputs ProgramInputsOf(RegisterBanks banks, IImageF continue; } - if (ColorTargetResolver.Resolve(context, slot, DrawLayerOffset, ignoreTargetMask: false, out var resolvedSlot) is { } resolution) + // Read in place: the resolution is a few hundred bytes, and a pattern match copied all of it again for one field. + var resolution = ColorTargetResolver.Resolve(context, slot, DrawLayerOffset, ignoreTargetMask: false, out var resolvedSlot); + if (resolution.HasValue) { - mapping[(int)resolvedSlot] = resolution.ExportMapping; + mapping[(int)resolvedSlot] = Nullable.GetValueRefOrDefaultRef(in resolution).ExportMapping; } } From 657c8b9ded6cc4e2130a8f45ba90d333011c6997 Mon Sep 17 00:00:00 2001 From: kuba Date: Mon, 16 Nov 2026 18:28:42 +0000 Subject: [PATCH 146/178] [GPU] Answer a draw's tessellation test and unwritten-target drop without per-draw copies IsEmulatedTessellation answers a draw without both the local and the hull stage inline (the full test's frame and call cost ~1.6% of the worker in the DS-shaped bench); NoteSampledTextures copies a texture descriptor only when its binding has a statistics counter; DropUnwrittenColorTargets no longer copies each kept colour target onto itself. Same results: DsDrawCostBench GameShaped checksum unchanged, worker cpu median 3.73 -> 3.62 us/draw (ABBA, 8 runs per arm). --- .../Gpu/Rendering/RenderExecutor.Targets.cs | 8 +++++++- .../RenderExecutor.TessellationEmulation.cs | 16 +++++++++++++++- .../Gpu/Rendering/RenderRecorder.cs | 15 ++++++++++++--- 3 files changed, 34 insertions(+), 5 deletions(-) diff --git a/src/SharpEmu.Libs/Gpu/Rendering/RenderExecutor.Targets.cs b/src/SharpEmu.Libs/Gpu/Rendering/RenderExecutor.Targets.cs index fb81e8f23..3459ab6ef 100644 --- a/src/SharpEmu.Libs/Gpu/Rendering/RenderExecutor.Targets.cs +++ b/src/SharpEmu.Libs/Gpu/Rendering/RenderExecutor.Targets.cs @@ -411,7 +411,13 @@ internal static void DropUnwrittenColorTargets(ContextRegisters context, ref Dra continue; } - state.Colors[(int)kept++] = target; + // Until the first dropped target every kept one is already in its place. + if (kept != i) + { + state.Colors[(int)kept] = target; + } + + kept++; } state.ColorCount = kept; diff --git a/src/SharpEmu.Libs/Gpu/Rendering/RenderExecutor.TessellationEmulation.cs b/src/SharpEmu.Libs/Gpu/Rendering/RenderExecutor.TessellationEmulation.cs index 627c9a13d..67a508c6f 100644 --- a/src/SharpEmu.Libs/Gpu/Rendering/RenderExecutor.TessellationEmulation.cs +++ b/src/SharpEmu.Libs/Gpu/Rendering/RenderExecutor.TessellationEmulation.cs @@ -48,8 +48,22 @@ public sealed partial class RenderExecutor private bool _tessellationAnnounced; // Whether this draw is a tessellated one the host runs, how many control points its patches have - // and whether they are quads. + // and whether they are quads. Asked on every draw: a draw without both the local and the hull stage + // (nearly all) is answered here, without the call and the frame of the full test. + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] private bool IsEmulatedTessellation(RegisterBanks banks, out uint controlPoints, out bool quad) + { + if ((banks.Context.ShaderStages & (LocalStageEnable | HullStageEnable)) != (LocalStageEnable | HullStageEnable)) + { + controlPoints = 0; + quad = false; + return false; + } + + return IsEmulatedTessellationStaged(banks, out controlPoints, out quad); + } + + private bool IsEmulatedTessellationStaged(RegisterBanks banks, out uint controlPoints, out bool quad) { controlPoints = 0; quad = false; diff --git a/src/SharpEmu.Libs/Gpu/Rendering/RenderRecorder.cs b/src/SharpEmu.Libs/Gpu/Rendering/RenderRecorder.cs index 38553c53f..f71069ed6 100644 --- a/src/SharpEmu.Libs/Gpu/Rendering/RenderRecorder.cs +++ b/src/SharpEmu.Libs/Gpu/Rendering/RenderRecorder.cs @@ -469,9 +469,18 @@ private static void NoteSampledTextures(in ShaderStageResources stage) { if (program.Images[index].Class == ImageResourceClass.Sampled) { - MipStatistics.Shared.NoteSampled( - new TextureDescriptorWords(descriptors[index]), - statistics is not null && index < statistics.Length ? statistics[index] : ShaderCompiler.Resources.ResourceSnapshot.NoMipStatistics); + var sampled = statistics is not null && index < statistics.Length ? statistics[index] : ShaderCompiler.Resources.ResourceSnapshot.NoMipStatistics; + // A binding without a statistics counter notes nothing (MipStatistics.NoteSampled): its descriptor + // is not copied. The counter bit is the snapshot's, or the descriptor's word 5 bit 25 without one. + var words = descriptors[index]; + if (sampled == ShaderCompiler.Resources.ResourceSnapshot.NoMipStatistics + ? words.Length <= 5 || (words[5] & ShaderCompiler.Resources.ResourceSnapshot.MipStatisticsEnableWordMask) == 0 + : (sampled & ShaderCompiler.Resources.ResourceSnapshot.MipStatisticsEnabled) == 0) + { + continue; + } + + MipStatistics.Shared.NoteSampled(new TextureDescriptorWords(words), sampled); } } } From e9538ad20a3e55008bc38b5f0c1a3edee2893714 Mon Sep 17 00:00:00 2001 From: kuba Date: Mon, 16 Nov 2026 18:35:02 +0000 Subject: [PATCH 147/178] [Metal] Write upload ranges once, answer a stage's step-report slot from its last program, move memo ways without a bulk move UploadDwords, WriteArgumentRange and the GPU-limits shader data copied their bytes over a range they had just cleared: they copy, then clear only the tail. UploadFlattenedTable's padded copy no longer clears its stack buffer (SkipLocalsInit) before writing it whole. StepReportAddress answers a stage's last program without the slot map (slots are never reassigned). MetalReadBindingMemoV2.MoveToFront shifts at most three ways with element copies instead of two BulkMoveWithWriteBarrier calls. Same bytes, same order. --- .../V2/MetalReadBindingMemoV2.cs | 19 +++++++++++++------ .../V2/MetalRenderHost.Descriptors.cs | 13 ++++++++----- .../V2/MetalRenderHost.StepReport.cs | 19 ++++++++++++++++--- 3 files changed, 37 insertions(+), 14 deletions(-) diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalReadBindingMemoV2.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalReadBindingMemoV2.cs index 752583356..c213c4548 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalReadBindingMemoV2.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalReadBindingMemoV2.cs @@ -191,12 +191,19 @@ public int Insert(ulong address, uint size, bool compute) private void MoveToFront(int first, int way) { - var entry = _entries[first + way]; - var side = _sides[first + way]; - _entries.AsSpan(first, way).CopyTo(_entries.AsSpan(first + 1, way)); - _sides.AsSpan(first, way).CopyTo(_sides.AsSpan(first + 1, way)); - _entries[first] = entry; - _sides[first] = side; + // At most Ways - 1 entries move down one way: element copies, not a bulk move with its write-barrier call. + var entries = _entries; + var sides = _sides; + var entry = entries[first + way]; + var side = sides[first + way]; + for (var index = first + way; index > first; index--) + { + entries[index] = entries[index - 1]; + sides[index] = sides[index - 1]; + } + + entries[first] = entry; + sides[first] = side; } /// The counters since the last call (the PERF line's read_binding_memo); resets them. diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Descriptors.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Descriptors.cs index e5f3c16b2..302dcacde 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Descriptors.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Descriptors.cs @@ -1756,7 +1756,7 @@ private void WriteArgumentBuffer(MetalStageBindings stage, int stageIndex) break; case MslArgumentFieldKind.StepReport: BinaryPrimitives.WriteUInt64LittleEndian( - span, StepReportAddress(stage.Program.Hash, StepReportStageName(stageIndex))); + span, StepReportAddress(stage.Program.Hash, stageIndex)); break; case MslArgumentFieldKind.PairLocks: // One table for every program, resident with the windows, so two programs @@ -1831,8 +1831,8 @@ private static MetalRegionMemo[] CreateRegionMemos(int count, int slots) private MetalGuestRange WriteArgumentRange(ReadOnlySpan bytes) { var range = _guestMemory.Allocate((ulong)bytes.Length, 256, out var span); - span.Clear(); bytes.CopyTo(span); + span[bytes.Length..].Clear(); return range; } @@ -2080,6 +2080,8 @@ internal static void AddDeviceAddressEntry( // The program reads the table's fixed slots below minimumWords without a bounds check // (Gen5MslCodegenOptions.ConstantTableSlots), so a shorter table goes up zero-padded: // those slots read the 0 the check gave. The padded words are part of the reuse key. + // The padded copy is written whole (the table, then a zero tail), so its stack memory is not zeroed first. + [System.Runtime.CompilerServices.SkipLocalsInit] private ulong UploadFlattenedTable(uint[] table, uint minimumWords) { if ((uint)table.Length >= minimumWords) @@ -2088,8 +2090,8 @@ private ulong UploadFlattenedTable(uint[] table, uint minimumWords) } Span padded = minimumWords <= 1024 ? stackalloc uint[(int)minimumWords] : new uint[minimumWords]; - padded.Clear(); table.CopyTo(padded); + padded[table.Length..].Clear(); return UploadDwords(padded); } @@ -2106,8 +2108,8 @@ private ulong UploadShaderDataForGpuLimits(MetalStageBindings stage) var bytes = System.Runtime.InteropServices.MemoryMarshal.AsBytes( stage.ShaderData.AsSpan(0, (int)layout.ShaderDataDwordCount)); var range = _guestMemory.Allocate((ulong)Math.Max(bytes.Length, 16), 256, out var span); - span.Clear(); bytes.CopyTo(span); + span[bytes.Length..].Clear(); _threadLimitsTarget = range with { Offset = range.Offset + ((ulong)layout.DispatchThreadLimitsDword * sizeof(uint)), @@ -2124,9 +2126,10 @@ private ulong UploadDwords(ReadOnlySpan words) return found.GpuAddress; } + // The range is the table's bytes and a zero tail up to the 16-byte minimum, each written once. var range = _guestMemory.Allocate((ulong)Math.Max(bytes.Length, 16), 256, out var span); - span.Clear(); bytes.CopyTo(span); + span[bytes.Length..].Clear(); if (ArgumentBufferReuse) { _uploadedTables.Add(bytes, _submissionSerial, in range); diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.StepReport.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.StepReport.cs index 7296b090c..cee7e42f3 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.StepReport.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.StepReport.cs @@ -85,12 +85,16 @@ private static int ProbeLogOffset(int index) private readonly string[] _stepReportStageBySlot = new string[StepReportSlots]; private readonly long[] _stepCapTotalBySlot = new long[StepReportSlots]; + // Per stage: the program that last took a slot here, and that slot plus one (zero: none yet). + private readonly ulong[] _stepReportLastHash = new ulong[StageCount]; + private readonly int[] _stepReportLastSlot = new int[StageCount]; + /// /// The GPU address of the step-report word reserved for one program, or zero when /// no slot is left; the shader null-checks the pointer, so zero just disables the /// report for that program. /// - private ulong StepReportAddress(ulong hash, string stage) + private ulong StepReportAddress(ulong hash, int stageIndex) { for (var index = 0; index < ProbeLogs.Length; index++) { @@ -102,7 +106,14 @@ private ulong StepReportAddress(ulong hash, string stage) } } - if (!_stepReportSlotByHash.TryGetValue(hash, out var slot)) + // A program keeps its slot for good, so the stage's last program answers without the map: consecutive + // draws mostly run the same programs. + int slot; + if (_stepReportLastSlot[stageIndex] != 0 && _stepReportLastHash[stageIndex] == hash) + { + slot = _stepReportLastSlot[stageIndex] - 1; + } + else if (!_stepReportSlotByHash.TryGetValue(hash, out slot)) { if (_stepReportUsed == StepReportSlots) { @@ -117,9 +128,11 @@ private ulong StepReportAddress(ulong hash, string stage) slot = _stepReportUsed++; _stepReportSlotByHash[hash] = slot; _stepReportHashBySlot[slot] = hash; - _stepReportStageBySlot[slot] = stage; + _stepReportStageBySlot[slot] = StepReportStageName(stageIndex); } + _stepReportLastHash[stageIndex] = hash; + _stepReportLastSlot[stageIndex] = slot + 1; NoteUsedResource(_stepReportBuffer, Mtl.ResourceUsageRead | Mtl.ResourceUsageWrite); return _stepReportGpuAddress + (ulong)(slot * StepReportStride * sizeof(uint)); } From a7196c50ed057cf6f4bc0b03bb07636f42702de7 Mon Sep 17 00:00:00 2001 From: kuba Date: Mon, 16 Nov 2026 18:35:02 +0000 Subject: [PATCH 148/178] [GPU] Resolve a draw's targets in place and leave unwritten resolve/copy fields alone at reset TryResolveDrawTargets built each colour target and the depth attachment in a stack temporary (a 3.6 KB zeroed frame) and copied it into the draw: it now writes their fields in place. ResolvedDraw.Reset cleared two 328-byte resolve targets and two copy requests on every draw although only a multisample resolve or depth/stencil copy writes them: it clears them only after one did (TargetCopyFieldsWritten). --- .../Gpu/Rendering/RenderExecutor.Targets.cs | 17 ++++++++++--- .../Gpu/Rendering/ResolvedCommands.cs | 24 ++++++++++++------- 2 files changed, 30 insertions(+), 11 deletions(-) diff --git a/src/SharpEmu.Libs/Gpu/Rendering/RenderExecutor.Targets.cs b/src/SharpEmu.Libs/Gpu/Rendering/RenderExecutor.Targets.cs index 3459ab6ef..3fb060d61 100644 --- a/src/SharpEmu.Libs/Gpu/Rendering/RenderExecutor.Targets.cs +++ b/src/SharpEmu.Libs/Gpu/Rendering/RenderExecutor.Targets.cs @@ -41,13 +41,22 @@ private bool TryResolveDrawTargets(RegisterBanks banks, in DrawCall draw, ref Dr { ref readonly var resolution = ref layout.Colors[index]; if (MeshDrawTrace.Active) MeshDrawTrace.Write("color-request", $"slot={layout.ColorSlots[index]} address=0x{resolution.Request.Description.Data.Address:X16} size=0x{resolution.Request.Description.Data.Size:X} view={resolution.Request.View}"); - state.Colors[(int)state.ColorCount++] = new ColorTargetState(in resolution, layout.ColorSlots[index], ResourceSlotIdentifier.Invalid); + // Written in place, field by field, as the constructor would: no stack copy of the resolution. + ref var color = ref state.Colors[(int)state.ColorCount++]; + color.Resolution = resolution; + color.Slot = layout.ColorSlots[index]; + color.Image = ResourceSlotIdentifier.Invalid; + color.View = default; } - if (layout.Depth is { } depthTarget) + if (layout.Depth.HasValue) { + ref readonly var depthTarget = ref Nullable.GetValueRefOrDefaultRef(in layout.Depth); if (MeshDrawTrace.Active) MeshDrawTrace.Write("depth-request", $"address=0x{depthTarget.Target.Request.Description.Data.Address:X16} size=0x{depthTarget.Target.Request.Description.Data.Size:X} view={depthTarget.Target.Request.View}"); - state.Depth = new DepthAttachmentState(in depthTarget, ResourceSlotIdentifier.Invalid); + state.Depth.Target = depthTarget; + state.Depth.Image = ResourceSlotIdentifier.Invalid; + state.Depth.View = default; + state.Depth.MetadataClear = false; state.DepthResolved = true; } @@ -331,6 +340,7 @@ private static bool TryResolveMultisampleColor(ContextRegisters context, Resolve record.Kind = ResolvedDrawKind.MultisampleResolve; record.ResolveSource = from; record.ResolveDestination = to; + record.TargetCopyFieldsWritten = true; return true; } @@ -367,6 +377,7 @@ private bool TryResolveDepthStencilCopy(ContextRegisters context, ResolvedDraw r var write = ImageRequestBuilders.DepthTargetCopy(in words, _host.FormatSupport, writeBuffer: true) ?? throw _host.Fatal("A depth/stencil copy has no writable depth target."); record.Kind = ResolvedDrawKind.DepthStencilCopy; + record.TargetCopyFieldsWritten = true; record.CopyRead = read.Request; record.CopyWrite = write.Request; record.CopyReadFormat = read.Format; diff --git a/src/SharpEmu.Libs/Gpu/Rendering/ResolvedCommands.cs b/src/SharpEmu.Libs/Gpu/Rendering/ResolvedCommands.cs index 657d07fb9..863fa21fd 100644 --- a/src/SharpEmu.Libs/Gpu/Rendering/ResolvedCommands.cs +++ b/src/SharpEmu.Libs/Gpu/Rendering/ResolvedCommands.cs @@ -128,6 +128,10 @@ internal sealed class ResolvedDraw public GpuExtent3D CopyExtent; public GpuImageAspect CopyAspects; + // A multisample resolve or depth/stencil copy wrote the fields above since the last Reset; until one does they + // hold their defaults, and Reset leaves them alone (two 328-byte targets and two image requests every draw). + public bool TargetCopyFieldsWritten; + public void Reset() { TessellationHull = null; @@ -161,14 +165,18 @@ public void Reset() IndexedTrace = null; PacketAddress = 0; Clear = default; - ResolveSource = default; - ResolveDestination = default; - CopyRead = default; - CopyWrite = default; - CopyReadFormat = default; - CopyWriteFormat = default; - CopyExtent = default; - CopyAspects = default; + if (TargetCopyFieldsWritten) + { + ResolveSource = default; + ResolveDestination = default; + CopyRead = default; + CopyWrite = default; + CopyReadFormat = default; + CopyWriteFormat = default; + CopyExtent = default; + CopyAspects = default; + TargetCopyFieldsWritten = false; + } } } From 1405b1e3ce75e12fd4c50e8c441b826509f48009 Mon Sep 17 00:00:00 2001 From: kuba Date: Mon, 16 Nov 2026 18:48:47 +0000 Subject: [PATCH 149/178] [GPU] Count a draw's export routing once for all its colour targets PixelExportRouting.ExportForSlot rebuilt the export mask from the eight output modes for every slot it was asked about, and the unwritten-target tests ask for every bound slot several times a draw (DropUnwrittenColorTargets, WrittenColorTargets, ResolveBoundTargets, the dual-source and extent tests, FillGraphicsState's colour masks). PixelExportRouting.Routing holds the export and slot masks; callers that loop over slots build it once, and the mask of eight modes is gathered from one 64-bit read. Same answers for every slot. --- .../Gpu/Pipelines/PixelExportRouting.cs | 79 ++++++++++++++----- .../Gpu/Pipelines/ShaderPipelineCache.cs | 14 ++-- .../Gpu/Rendering/RenderExecutor.Targets.cs | 15 +++- 3 files changed, 78 insertions(+), 30 deletions(-) diff --git a/src/SharpEmu.Libs/Gpu/Pipelines/PixelExportRouting.cs b/src/SharpEmu.Libs/Gpu/Pipelines/PixelExportRouting.cs index d53775341..353efd535 100644 --- a/src/SharpEmu.Libs/Gpu/Pipelines/PixelExportRouting.cs +++ b/src/SharpEmu.Libs/Gpu/Pipelines/PixelExportRouting.cs @@ -16,43 +16,80 @@ internal static class PixelExportRouting // The export that feeds the slot, or -1 when no export reaches it. When the registers do not // pair up, each export goes to the slot of the same number. - public static int ExportForSlot(ShaderInterfaceRegisters registers, uint slot) + public static int ExportForSlot(ShaderInterfaceRegisters registers, uint slot) => + slot >= TargetCount ? -1 : Routing.Of(registers).ExportForSlot(slot); + + /// + /// The pairing of exports and slots the registers make, counted once for every slot a draw asks about + /// (the targets' unwritten tests ask for each bound slot, several times a draw). + /// + internal readonly struct Routing { - if (slot >= TargetCount) + // Bit n of each mask: export n has a format, slot n is enabled. + private readonly uint _exports; + private readonly uint _slots; + + private Routing(uint exports, uint slots) { - return -1; + _exports = exports; + _slots = slots; } - // Bit n of each mask: export n has a format, slot n is enabled. Called for every bound slot - // of every draw from several places, so the pairing is counted in bits rather than listed. - var modes = registers.TargetOutputModes; - var exports = 0u; - for (var index = 0; index < TargetCount && index < modes.Length; index++) + public static Routing Of(ShaderInterfaceRegisters registers) => + new(ExportMask(registers.TargetOutputModes), EnabledSlots(registers.ColorShaderMask)); + + public int ExportForSlot(uint slot) { - if ((modes[index] & 0xF) != 0) + if (slot >= TargetCount) { - exports |= 1u << index; + return -1; } - } - var slots = EnabledSlots(registers.ColorShaderMask); - if (exports == 0 || BitOperations.PopCount(exports) != BitOperations.PopCount(slots)) - { - return (int)slot; + var exports = _exports; + var slots = _slots; + if (exports == 0 || BitOperations.PopCount(exports) != BitOperations.PopCount(slots)) + { + return (int)slot; + } + + if ((slots & (1u << (int)slot)) == 0) + { + return -1; + } + + // The slot's rank among the enabled slots picks the export of the same rank. + for (var rank = BitOperations.PopCount(slots & ((1u << (int)slot) - 1)); rank > 0; rank--) + { + exports &= exports - 1; + } + + return BitOperations.TrailingZeroCount(exports); } + } - if ((slots & (1u << (int)slot)) == 0) + // Bit n set when the first eight output modes give export n a format (a nonzero low nibble). + private static uint ExportMask(byte[] modes) + { + if (modes.Length >= TargetCount) { - return -1; + // All eight at once: each byte's low nibble folded into its bit 0, the eight bits gathered into the top byte. + var nibbles = System.Buffers.Binary.BinaryPrimitives.ReadUInt64LittleEndian(modes) & 0x0F0F0F0F0F0F0F0FUL; + nibbles |= nibbles >> 2; + nibbles |= nibbles >> 1; + nibbles &= 0x0101010101010101UL; + return (uint)((nibbles * 0x0102040810204080UL) >> 56); } - // The slot's rank among the enabled slots picks the export of the same rank. - for (var rank = BitOperations.PopCount(slots & ((1u << (int)slot) - 1)); rank > 0; rank--) + var exports = 0u; + for (var index = 0; index < modes.Length; index++) { - exports &= exports - 1; + if ((modes[index] & 0xF) != 0) + { + exports |= 1u << index; + } } - return BitOperations.TrailingZeroCount(exports); + return exports; } // Bit n set when CB_SHADER_MASK enables any component of slot n. diff --git a/src/SharpEmu.Libs/Gpu/Pipelines/ShaderPipelineCache.cs b/src/SharpEmu.Libs/Gpu/Pipelines/ShaderPipelineCache.cs index 84bd8158c..ced47c009 100644 --- a/src/SharpEmu.Libs/Gpu/Pipelines/ShaderPipelineCache.cs +++ b/src/SharpEmu.Libs/Gpu/Pipelines/ShaderPipelineCache.cs @@ -1689,10 +1689,11 @@ private Gen5PixelOutputBinding[] ResolveBoundTargets(ContextRegisters context, R var outputs = _boundOutputs; outputs.Clear(); var location = 0u; + var routing = PixelExportRouting.Routing.Of(context.ShaderInterface); foreach (var slot in boundSlots) { if (unwrittenExportMasks is { } exportMasks && - RenderExecutor.IsUnwrittenColorTarget(context, slot, targetExportMapping[(int)slot], exportMasks)) + RenderExecutor.IsUnwrittenColorTarget(context, in routing, slot, targetExportMapping[(int)slot], exportMasks)) { continue; } @@ -1704,7 +1705,7 @@ private Gen5PixelOutputBinding[] ResolveBoundTargets(ContextRegisters context, R } // A bound slot that no export reaches keeps its contents: its color write mask is zero. - var exportTarget = PixelExportRouting.ExportForSlot(context.ShaderInterface, slot); + var exportTarget = routing.ExportForSlot(slot); // The high nibble keys the compiled program by the export that feeds the slot. outputModes[(int)slot] = (byte)(((uint)kind + 1) | (uint)((exportTarget + 1) << 4)); outputMappings[(int)slot] = new ColorComponentMap(mapping.Packed); @@ -1868,9 +1869,10 @@ private bool LeavesSingleDualSourceTarget( var written = 0; var writtenSlot = 0u; + var routing = PixelExportRouting.Routing.Of(context.ShaderInterface); foreach (var slot in boundSlots) { - if (!RenderExecutor.IsUnwrittenColorTarget(context, slot, mappingBySlot[(int)slot], pixelColorExportMasks)) + if (!RenderExecutor.IsUnwrittenColorTarget(context, in routing, slot, mappingBySlot[(int)slot], pixelColorExportMasks)) { written++; writtenSlot = slot; @@ -1907,11 +1909,12 @@ private static bool UnwrittenTargetBoundsRenderArea( uint writtenWidth = 0, writtenHeight = 0; uint unwrittenWidth = uint.MaxValue, unwrittenHeight = uint.MaxValue; + var routing = PixelExportRouting.Routing.Of(context.ShaderInterface); for (var index = 0; index < boundSlots.Length; index++) { var slot = boundSlots[index]; var extent = boundExtents[index]; - if (RenderExecutor.IsUnwrittenColorTarget(context, slot, mappingBySlot[(int)slot], pixelColorExportMasks)) + if (RenderExecutor.IsUnwrittenColorTarget(context, in routing, slot, mappingBySlot[(int)slot], pixelColorExportMasks)) { unwrittenWidth = Math.Min(unwrittenWidth, extent.Width); unwrittenHeight = Math.Min(unwrittenHeight, extent.Height); @@ -2654,6 +2657,7 @@ private static (ShaderProgramInfo VertexStage, ShaderProgramInfo? PixelStage) Fi var colorCount = (uint)colors.Length; parameters.ColorCount = colorCount; renderingState.ColorCount = colorCount; + var routing = PixelExportRouting.Routing.Of(context.ShaderInterface); for (var index = 0; index < colors.Length; index++) { ref readonly var color = ref colors[index]; @@ -2669,7 +2673,7 @@ private static (ShaderProgramInfo VertexStage, ShaderProgramInfo? PixelStage) Fi // leave a color target bound and export only to the null target). var exportTarget = color.Slot == 0 && context.BlendControls[0].UsesSecondarySource && (context.ColorTargets[0].Info & (1u << 16)) == 0 - ? 0 : PixelExportRouting.ExportForSlot(context.ShaderInterface, color.Slot); + ? 0 : routing.ExportForSlot(color.Slot); var exported = pixelStage is not null && (exportTarget >= 0 && ((pixelStage.PixelColorExportMasks >> (exportTarget * 4)) & 0xFu) != 0); var colorMask = exported ? color.Resolution.ExportMapping.ApplyMask(context.ColorWriteMaskForSlot(color.Slot)) : 0; diff --git a/src/SharpEmu.Libs/Gpu/Rendering/RenderExecutor.Targets.cs b/src/SharpEmu.Libs/Gpu/Rendering/RenderExecutor.Targets.cs index 3fb060d61..56e1d1da4 100644 --- a/src/SharpEmu.Libs/Gpu/Rendering/RenderExecutor.Targets.cs +++ b/src/SharpEmu.Libs/Gpu/Rendering/RenderExecutor.Targets.cs @@ -413,11 +413,12 @@ internal static void DropUnwrittenColorTargets(ContextRegisters context, ref Dra } var exportMasks = pixelProgram?.PixelColorExportMasks ?? 0u; + var routing = PixelExportRouting.Routing.Of(context.ShaderInterface); var kept = 0u; for (var i = 0; i < state.ColorCount; i++) { ref readonly var target = ref state.Colors[i]; - if (IsUnwrittenColorTarget(context, target.Slot, target.Resolution.ExportMapping, exportMasks)) + if (IsUnwrittenColorTarget(context, in routing, target.Slot, target.Resolution.ExportMapping, exportMasks)) { continue; } @@ -443,11 +444,12 @@ internal static uint WrittenColorTargets(ContextRegisters context, in DrawState } var exportMasks = pixelProgram?.PixelColorExportMasks ?? 0u; + var routing = PixelExportRouting.Routing.Of(context.ShaderInterface); var written = 0u; for (var i = 0; i < state.ColorCount; i++) { ref readonly var target = ref state.Colors[i]; - if (!IsUnwrittenColorTarget(context, target.Slot, target.Resolution.ExportMapping, exportMasks)) + if (!IsUnwrittenColorTarget(context, in routing, target.Slot, target.Resolution.ExportMapping, exportMasks)) { written |= 1u << i; } @@ -458,14 +460,19 @@ internal static uint WrittenColorTargets(ContextRegisters context, in DrawState // The export that reaches the slot is the one routed to it, not the export of the same // number: exports are compacted onto the slots CB_SHADER_MASK enables. - internal static bool IsUnwrittenColorTarget(ContextRegisters context, uint slot, ColorComponentMap exportMapping, uint pixelColorExportMasks) + internal static bool IsUnwrittenColorTarget(ContextRegisters context, uint slot, ColorComponentMap exportMapping, uint pixelColorExportMasks) => + IsUnwrittenColorTarget(context, PixelExportRouting.Routing.Of(context.ShaderInterface), slot, exportMapping, pixelColorExportMasks); + + // As above, with the registers' export routing counted once by a caller that asks for several slots. + internal static bool IsUnwrittenColorTarget( + ContextRegisters context, in PixelExportRouting.Routing routing, uint slot, ColorComponentMap exportMapping, uint pixelColorExportMasks) { if (exportMapping.ApplyMask(context.RenderTargetMaskForSlot(slot)) == 0) { return true; } - var export = PixelExportRouting.ExportForSlot(context.ShaderInterface, slot); + var export = routing.ExportForSlot(slot); return export < 0 || ((pixelColorExportMasks >> (export * 4)) & 0xFu) == 0; } } From bfbaba32e7381c81e5b4480c0277408218de3323 Mon Sep 17 00:00:00 2001 From: kuba Date: Mon, 16 Nov 2026 18:48:47 +0000 Subject: [PATCH 150/178] [GPU] Record a queue's known colour targets only when its colour-target registers moved RecordKnownColorTargets stored every bound target's words in KnownColorTargets on every draw. Under the banks' unchanged ColorTargets stamp (the target words and CB_TARGET_MASK; every write, context push, pop and the flip replay move it) the registers hold the words the last call stored, so the call returns. --- src/SharpEmu.Libs/Agc/AgcExports.CommandStream.cs | 7 +++++++ src/SharpEmu.Libs/Agc/AgcExports.cs | 4 ++++ 2 files changed, 11 insertions(+) diff --git a/src/SharpEmu.Libs/Agc/AgcExports.CommandStream.cs b/src/SharpEmu.Libs/Agc/AgcExports.CommandStream.cs index 962766d3b..0d04bcd0e 100644 --- a/src/SharpEmu.Libs/Agc/AgcExports.CommandStream.cs +++ b/src/SharpEmu.Libs/Agc/AgcExports.CommandStream.cs @@ -272,6 +272,13 @@ private RegisterBanks RequireTypedRegisters(SubmittedDcbState state) => // The words of every bound color target, so a flip can replay a retained draw into the display buffer. private static void RecordKnownColorTargets(SubmittedDcbState state, RegisterBanks banks) { + var stamp = banks.Stamp(RegisterStamp.ColorTargets); + if (stamp == state.KnownColorTargetsStamp) + { + return; + } + + state.KnownColorTargetsStamp = stamp; var context = banks.Context; for (var slot = 0u; slot < ContextRegisters.ColorTargetCount; slot++) { diff --git a/src/SharpEmu.Libs/Agc/AgcExports.cs b/src/SharpEmu.Libs/Agc/AgcExports.cs index 104010949..ff1216dc8 100644 --- a/src/SharpEmu.Libs/Agc/AgcExports.cs +++ b/src/SharpEmu.Libs/Agc/AgcExports.cs @@ -274,6 +274,10 @@ public void AttachInterpreter(GpuCommandInterpreter interpreter) // The color target words last bound at each base address; the flip replay reads the display buffer's. public Dictionary KnownColorTargets { get; } = new(); + // The banks' colour-target stamp (the target words and CB_TARGET_MASK) when KnownColorTargets last took + // them: under the same stamp the registers hold the same words, which are recorded already. + public ulong KnownColorTargetsStamp { get; set; } + // A draw without targets kept for the next flip, with the banks it was issued under. public RetainedTargetlessDraw? RetainedTargetlessDraw { get; set; } From 243726ff35f7bd09c37984914da6c58878def04d Mon Sep 17 00:00:00 2001 From: kuba Date: Mon, 16 Nov 2026 18:48:47 +0000 Subject: [PATCH 151/178] [Metal] Look up an encoder's named residents in a stamped open-addressing table TryNoteResident asked a Dictionary for every used resource of every draw. The index is now the used-resource index's scheme: linear probing over a power-of-two table at most half full, a slot live when its stamp is the encoder's, so ForgetResidentResources empties it by moving the stamp. Same resources named in the same order. --- .../V2/MetalRenderHost.Descriptors.cs | 59 ++++++++++++++++--- 1 file changed, 51 insertions(+), 8 deletions(-) diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Descriptors.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Descriptors.cs index 302dcacde..fda2d5af2 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Descriptors.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Descriptors.cs @@ -2335,7 +2335,12 @@ private void ApplyStageBindings(bool graphics) private nuint[] _encoderResidentUsage = new nuint[64]; private nuint[] _encoderResidentStages = new nuint[64]; private int _encoderResidentCount; - private readonly Dictionary _encoderResidentIndex = new(); + // The resources' positions by hash, open addressing, at most half full: a slot is live when its stamp is the + // current one (moved with every encoder), so a new encoder starts empty without a clear. Looked up for every used + // resource of every draw. + private int[] _encoderResidentSlots = new int[128]; + private long[] _encoderResidentSlotStamps = new long[128]; + private long _encoderResidentStamp = 1; private long _residencyCallsSkipped; // Resources an encoder was told (not skipped), and compute encoders opened: what re-declaring the submission's // residents to every new compute encoder costs (the WAITS line's residency_named and compute_encoders). @@ -2345,11 +2350,7 @@ private void ApplyStageBindings(bool graphics) private void ForgetResidentResources() { _encoderEpoch++; - if (_encoderResidentCount != 0) - { - _encoderResidentIndex.Clear(); - } - + _encoderResidentStamp++; _encoderResidentCount = 0; } @@ -2512,7 +2513,24 @@ private unsafe void NameResidentBuffers(nint encoder, ReadOnlySpan buffers private bool TryNoteResident(nint resource, nuint usage, nuint stages) { - if (_encoderResidentIndex.TryGetValue(resource, out var index)) + var slots = _encoderResidentSlots; + var slotStamps = _encoderResidentSlotStamps; + var mask = slots.Length - 1; + var slot = UsedResourceHash(resource) & mask; + var index = -1; + while (slotStamps[slot] == _encoderResidentStamp) + { + var position = slots[slot] - 1; + if (_encoderResidentResources[position] == resource) + { + index = position; + break; + } + + slot = (slot + 1) & mask; + } + + if (index >= 0) { // A wider usage or a new stage has to be named again; the same one need not. if ((_encoderResidentUsage[index] & usage) == usage && @@ -2535,15 +2553,40 @@ private bool TryNoteResident(nint resource, nuint usage, nuint stages) Array.Resize(ref _encoderResidentStages, _encoderResidentCount * 2); } - _encoderResidentIndex[resource] = _encoderResidentCount; _encoderResidentResources[_encoderResidentCount] = resource; _encoderResidentUsage[_encoderResidentCount] = usage; _encoderResidentStages[_encoderResidentCount] = stages; _encoderResidentCount++; + slotStamps[slot] = _encoderResidentStamp; + slots[slot] = _encoderResidentCount; + if (_encoderResidentCount * 2 > slots.Length) + { + GrowEncoderResidentIndex(); + } + _residencyCallsNamed++; return true; } + [MethodImpl(MethodImplOptions.NoInlining)] + private void GrowEncoderResidentIndex() + { + _encoderResidentSlots = new int[_encoderResidentSlots.Length * 2]; + _encoderResidentSlotStamps = new long[_encoderResidentSlots.Length]; + var mask = _encoderResidentSlots.Length - 1; + for (var position = 0; position < _encoderResidentCount; position++) + { + var slot = UsedResourceHash(_encoderResidentResources[position]) & mask; + while (_encoderResidentSlotStamps[slot] == _encoderResidentStamp) + { + slot = (slot + 1) & mask; + } + + _encoderResidentSlotStamps[slot] = _encoderResidentStamp; + _encoderResidentSlots[slot] = position + 1; + } + } + private void BindStageBuffers(nint encoder, int stageIndex, nint setBufferSelector) { if (encoder == 0) From a419f9e521d93ffb2ded6501c8f3c68ffaf5fcad Mon Sep 17 00:00:00 2001 From: kuba Date: Mon, 16 Nov 2026 18:52:35 +0000 Subject: [PATCH 152/178] [GPU] Find once whether a program writes a storage image RenderExecutor.WritesStorageImage walked the program's images on every call, several a draw (the adaptations, the draw-writes-memory and pixel-stores tests, the recorder's fragment-write ranges). ShaderProgramInfo.WritesAnyStorageImage finds it once, as WritesAnyBuffer does for the buffers. --- .../Rendering/RenderExecutor.Adaptations.cs | 13 +------------ .../Gpu/Rendering/ShaderStageResources.cs | 19 +++++++++++++++++++ 2 files changed, 20 insertions(+), 12 deletions(-) diff --git a/src/SharpEmu.Libs/Gpu/Rendering/RenderExecutor.Adaptations.cs b/src/SharpEmu.Libs/Gpu/Rendering/RenderExecutor.Adaptations.cs index f7ebb1738..b7fff2342 100644 --- a/src/SharpEmu.Libs/Gpu/Rendering/RenderExecutor.Adaptations.cs +++ b/src/SharpEmu.Libs/Gpu/Rendering/RenderExecutor.Adaptations.cs @@ -161,18 +161,7 @@ private static bool StageMayWriteMemory(ShaderProgramInfo? program) return false; } - internal static bool WritesStorageImage(ShaderProgramInfo program) - { - foreach (var image in program.Images) - { - if (image.Class == ImageResourceClass.Storage && image.Written) - { - return true; - } - } - - return false; - } + internal static bool WritesStorageImage(ShaderProgramInfo program) => program.WritesAnyStorageImage; private static bool IsPremultipliedFillBlend(in BlendRegisters blend) => blend.Enable && blend.ColorSourceFactor == BlendFactorOne && blend.ColorDestinationFactor == BlendFactorOneMinusSourceAlpha && blend.ColorFunction == BlendFunctionAdd; diff --git a/src/SharpEmu.Libs/Gpu/Rendering/ShaderStageResources.cs b/src/SharpEmu.Libs/Gpu/Rendering/ShaderStageResources.cs index bd218a331..16a1ee366 100644 --- a/src/SharpEmu.Libs/Gpu/Rendering/ShaderStageResources.cs +++ b/src/SharpEmu.Libs/Gpu/Rendering/ShaderStageResources.cs @@ -93,6 +93,25 @@ public bool WritesAnyBuffer private int _writesAnyBuffer; public ImageResourceInfo[] Images { get; init; } = []; + + // Whether any storage image is written, found once as WritesAnyBuffer is: asked several times a draw. + public bool WritesAnyStorageImage + { + get + { + var known = Volatile.Read(ref _writesAnyStorageImage); + if (known == 0) + { + known = Array.Exists(Images, static image => image.Class == ImageResourceClass.Storage && image.Written) ? 2 : 1; + Volatile.Write(ref _writesAnyStorageImage, known); + } + + return known == 2; + } + } + + private int _writesAnyStorageImage; + public int SamplerCount { get; init; } public uint WaveSize { get; init; } = 64; public uint ScratchDwords { get; init; } From 20a4e7a8493fc52adf13c3cd96d16195a778998f Mon Sep 17 00:00:00 2001 From: kuba Date: Mon, 16 Nov 2026 21:30:28 +0000 Subject: [PATCH 153/178] [Shader] Read portable buffer words through optional function constants Behind PortableBufferWord.ConstantsEnabled (off): each run-time stride and word 3 a portable program uses becomes a uint function constant, read when the function is made with a value and from the shader data otherwise. A formatted load whose word 3 is a constant calls sharpemu_format_fetch_constant when the value is given, which folds to the packed run form; the run-time decode stays in the other branch. Gen5MslShader lists the constants and parses them back from source text. --- .../Gen5MslCodegenOptions.cs | 9 ++ .../Gen5MslShader.cs | 41 ++++++- .../Gen5MslTranslator.BufferWordConstants.cs | 106 ++++++++++++++++++ .../Gen5MslTranslator.cs | 60 ++++++++-- .../format_fetch_constant_prelude.msl | 64 +++++++++++ .../Resources/PortableBufferWord.cs | 29 +++++ 6 files changed, 297 insertions(+), 12 deletions(-) create mode 100644 src/SharpEmu.ShaderCompiler.Metal/Gen5MslTranslator.BufferWordConstants.cs create mode 100644 src/SharpEmu.ShaderCompiler.Metal/Templates/format_fetch_constant_prelude.msl diff --git a/src/SharpEmu.ShaderCompiler.Metal/Gen5MslCodegenOptions.cs b/src/SharpEmu.ShaderCompiler.Metal/Gen5MslCodegenOptions.cs index 2bab70069..174b1e05e 100644 --- a/src/SharpEmu.ShaderCompiler.Metal/Gen5MslCodegenOptions.cs +++ b/src/SharpEmu.ShaderCompiler.Metal/Gen5MslCodegenOptions.cs @@ -250,6 +250,15 @@ public sealed record Gen5MslCodegenOptions( /// the inline decoder and the DecodedFormatLoadThreshold helper. public bool FormatFetch { get; init; } = true; + /// Make each run-time buffer word of a portable program a function constant + /// (PortableBufferWord.ConstantsEnabled); null follows that process-wide switch. Set by tests. + public bool? BufferWordConstants { get; init; } + + /// A program with more BUFFER_LOAD_FORMAT_* than this keeps the run-time decode alone at + /// every site whose word 3 is a function constant (): each such site + /// otherwise carries the constant form as well, and a library with hundreds builds slower. + public int FormatFetchConstantSiteLimit { get; init; } = Gen5MslTranslator.FormatFetchConstantSiteLimit; + /// Experimental guarded forwarding of the last 128-bit LDS write in a /// single-wave mesh subgroup. SHARPEMU_MSL_MESH_LDS_FORWARDING=1. public bool MeshLdsForwarding { get; init; } diff --git a/src/SharpEmu.ShaderCompiler.Metal/Gen5MslShader.cs b/src/SharpEmu.ShaderCompiler.Metal/Gen5MslShader.cs index d2ef1a191..887d5d337 100644 --- a/src/SharpEmu.ShaderCompiler.Metal/Gen5MslShader.cs +++ b/src/SharpEmu.ShaderCompiler.Metal/Gen5MslShader.cs @@ -156,7 +156,7 @@ public uint InputPrimitivesPerSubgroup(Gen5MslMeshInputTopology input) } // Compiled source, stage interface counts, and the argument-buffer layout. -public sealed record Gen5MslShader( +public sealed partial record Gen5MslShader( string Source, string EntryPoint, Gen5MslStage Stage, @@ -187,6 +187,45 @@ public sealed record Gen5MslShader( /// function must be made with a value for it (newFunctionWithName:constantValues:error:). public bool UsesMipStatisticsConstant { get; init; } + /// One buffer-word function constant a source declares (PortableBufferWord.ConstantsEnabled): + /// its [[function_constant(n)]] index and the shader-data dword it stands in for. + public readonly record struct BufferWordConstant(uint Index, uint Dword); + + /// The buffer-word function constants the source declares, by index. A function made + /// with a value for one reads that value instead of the shader-data dword; one made without + /// reads the shader data. + public IReadOnlyList BufferWordConstants { get; init; } = []; + + /// The buffer-word constants a translated source declares, recovered from its text + /// (a stored source carries no metadata), by index. + public static IReadOnlyList ParseBufferWordConstants(string source) + { + var found = new List(); + var prefix = $"constant uint {Resources.PortableBufferWord.ConstantNamePrefix}"; + for (var at = source.IndexOf(prefix, StringComparison.Ordinal); at >= 0; + at = source.IndexOf(prefix, at + prefix.Length, StringComparison.Ordinal)) + { + var end = source.IndexOf('\n', at); + var line = end < 0 ? source[at..] : source[at..end]; + var match = BufferWordDeclaration().Match(line); + if (!match.Success || match.Groups[1].Value != match.Groups[3].Value) + { + throw new FormatException($"A buffer-word constant declaration does not parse: '{line.TrimEnd()}'."); + } + + found.Add(new BufferWordConstant( + uint.Parse(match.Groups[1].ValueSpan, System.Globalization.CultureInfo.InvariantCulture), + uint.Parse(match.Groups[2].ValueSpan, System.Globalization.CultureInfo.InvariantCulture))); + } + + found.Sort(static (left, right) => left.Index.CompareTo(right.Index)); + return found; + } + + [System.Text.RegularExpressions.GeneratedRegex( + @"^constant uint sharpemu_fc_bw(\d+)_sd(\d+) \[\[function_constant\((\d+)\)\]\];")] + private static partial System.Text.RegularExpressions.Regex BufferWordDeclaration(); + /// The vertex indices covers, from zero. public const int ConstantPositionVertexCount = 6; diff --git a/src/SharpEmu.ShaderCompiler.Metal/Gen5MslTranslator.BufferWordConstants.cs b/src/SharpEmu.ShaderCompiler.Metal/Gen5MslTranslator.BufferWordConstants.cs new file mode 100644 index 000000000..3f6bd80f4 --- /dev/null +++ b/src/SharpEmu.ShaderCompiler.Metal/Gen5MslTranslator.BufferWordConstants.cs @@ -0,0 +1,106 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using System.Text; +using SharpEmu.ShaderCompiler.Resources; + +namespace SharpEmu.ShaderCompiler.Metal; + +public static partial class Gen5MslTranslator +{ + /// + /// The default : a program with + /// more BUFFER_LOAD_FORMAT_* keeps today's decode alone even where word 3 is a function + /// constant. Vertex programs fetch a handful. + /// + internal const int FormatFetchConstantSiteLimit = 64; + + private sealed partial class CompilationContext + { + // The buffer-word function constants the program reads (PortableBufferWord.ConstantsEnabled): + // constant index -> the shader-data dword it stands in for. + private readonly SortedDictionary _bufferWordConstants = new(); + private bool _usesFormatFetchConstant; + + private bool BufferWordConstantsEnabled => _options.BufferWordConstants ?? PortableBufferWord.ConstantsEnabled; + + // A portable buffer's run-time word: the function constant when the function was made + // with a value for it, the shader data otherwise. Declares the constant. + private string BufferWordConstant(int bindingIndex, int word, uint dword, out string name) + { + var index = PortableBufferWord.ConstantIndex(bindingIndex, word); + name = PortableBufferWord.ConstantName(index, dword); + _bufferWordConstants[index] = dword; + return $"({name}_set ? {name} : {ShaderDataDword(dword)})"; + } + + private IReadOnlyList BufferWordConstants() => + _bufferWordConstants.Select(static pair => new Gen5MslShader.BufferWordConstant(pair.Key, pair.Value)).ToArray(); + + // Program-scope declarations, after the preludes: each constant and whether it was given. + private void AppendBufferWordConstants(StringBuilder source) + { + foreach (var (index, dword) in _bufferWordConstants) + { + var name = PortableBufferWord.ConstantName(index, dword); + source.AppendLine($"constant uint {name} [[function_constant({index})]];"); + source.AppendLine($"constant bool {name}_set = is_function_constant_defined({name});"); + } + + if (_usesFormatFetchConstant) + { + source.Append(MslTemplates.Render("format_fetch_constant_prelude")); + } + } + + // A formatted load whose word 3 is the function constant: the constant form + // (format_fetch_constant_prelude.msl) where the function has the value, the run-time + // decode, unchanged, where it does not. False where the site keeps the run-time decode + // alone: a D16 or GLC load, a placed access, a program over the site limit. + private bool TryEmitConstantFormatLoad( + int bindingIndex, + BufferAddress byteAddress, + string descriptorWord3, + string word3Constant, + uint vectorData, + uint componentCount, + FormatD16 d16, + bool glc) + { + if (d16.Enabled || glc || !byteAddress.Contiguous || !_options.FormatFetch || + _formatBufferLoads > _options.FormatFetchConstantSiteLimit) + { + return false; + } + + _usesFormatFetch = true; + _usesFormatFetchConstant = true; + Line($"if ({word3Constant}_set)"); + Line("{"); + _indent++; + var fetched = Temp( + "uint4", + $"sharpemu_format_fetch_constant(b{bindingIndex}, {BufferBytes(bindingIndex)}, {byteAddress.Base}, {word3Constant}, {componentCount}u)"); + for (uint component = 0; component < componentCount; component++) + { + StoreVector(vectorData + component, $"{fetched}[{component}]"); + } + + _indent--; + Line("}"); + Line("else"); + Line("{"); + _indent++; + EmitDecodedBufferFormatLoad( + BindingFormatMemory(bindingIndex, glc), + byteAddress, + descriptorWord3, + vectorData, + componentCount, + d16); + _indent--; + Line("}"); + return true; + } + } +} diff --git a/src/SharpEmu.ShaderCompiler.Metal/Gen5MslTranslator.cs b/src/SharpEmu.ShaderCompiler.Metal/Gen5MslTranslator.cs index 3f318b0e8..e9c48d470 100644 --- a/src/SharpEmu.ShaderCompiler.Metal/Gen5MslTranslator.cs +++ b/src/SharpEmu.ShaderCompiler.Metal/Gen5MslTranslator.cs @@ -756,6 +756,7 @@ public bool TryCompile(out Gen5MslShader shader, out string error) { UsesPerVertexInputs = UsesVertexValueInputs, UsesMipStatisticsConstant = UsesMipStatisticsConstant, + BufferWordConstants = BufferWordConstants(), ConstantPositions = _stage == Gen5MslStage.Vertex && !DebugVertexPosition && _request.Tessellation is null ? EvaluateConstantPositions(_request.Program.Instructions, _request.ClipSpace) : null, @@ -897,6 +898,8 @@ private void EmitModule(StringBuilder source, IReadOnlyList blocks) $"[[function_constant({Gen5MslShader.MipStatisticsFunctionConstantIndex})]];"); } + AppendBufferWordConstants(source); + source.AppendLine(); if (_stage == Gen5MslStage.Mesh) @@ -2597,15 +2600,37 @@ private bool EmitResolvedBufferMemory( var stride = FormatUInt(packedStride & 0x3FFF); var descriptorFormat = specialized.DescriptorFormat; var descriptorWord3 = FormatUInt((specialized.DescriptorFormat << 12) | (specialized.DescriptorSwizzle & 0xFFF)); + string? word3Constant = null; if (_request.Bindings is { BufferWordCount: not 0 } portable && (uint)bindingIndex < portable.MemoryOffsetCount) { // Portable buffers (PortableBufferWord): the V#'s stride, and the format word // of a formatted buffer the program only reads, come from the shader data. var words = portable.FirstBufferWordDword() + (uint)bindingIndex * PortableBufferWord.DwordCount; - stride = Temp("uint", $"({ShaderDataDword(words)} & 0x{PortableBufferWord.StrideMask:X}u)"); - if (PortableBufferWord.ReadsFormatAtRuntime(specialized)) + if (BufferWordConstantsEnabled) + { + // Each word a function constant (PortableBufferWord.ConstantsEnabled), declared + // only where the program uses it: the stride where an index multiplies it, + // word 3 where an untyped formatted load decodes it. + var strideWord = BufferIndex(control, addThreadId ? "true" : null) != "0u" + ? BufferWordConstant(bindingIndex, 0, words, out _) + : ShaderDataDword(words); + stride = Temp("uint", $"({strideWord} & 0x{PortableBufferWord.StrideMask:X}u)"); + if (PortableBufferWord.ReadsFormatAtRuntime(specialized)) + { + descriptorWord3 = Temp( + "uint", + IsFormatBufferLoad(instruction.Opcode) && !control.Typed + ? BufferWordConstant(bindingIndex, 1, words + 1, out word3Constant) + : ShaderDataDword(words + 1)); + } + } + else { - descriptorWord3 = Temp("uint", ShaderDataDword(words + 1)); + stride = Temp("uint", $"({ShaderDataDword(words)} & 0x{PortableBufferWord.StrideMask:X}u)"); + if (PortableBufferWord.ReadsFormatAtRuntime(specialized)) + { + descriptorWord3 = Temp("uint", ShaderDataDword(words + 1)); + } } } @@ -2669,14 +2694,27 @@ private bool EmitResolvedBufferMemory( { if (!control.Typed) { - EmitBufferFormatLoad( - bindingIndex, - address, - descriptorWord3, - control.VectorData, - components, - d16, - control.Glc); + if (word3Constant is null || + !TryEmitConstantFormatLoad( + bindingIndex, + address, + descriptorWord3, + word3Constant, + control.VectorData, + components, + d16, + control.Glc)) + { + EmitBufferFormatLoad( + bindingIndex, + address, + descriptorWord3, + control.VectorData, + components, + d16, + control.Glc); + } + return true; } diff --git a/src/SharpEmu.ShaderCompiler.Metal/Templates/format_fetch_constant_prelude.msl b/src/SharpEmu.ShaderCompiler.Metal/Templates/format_fetch_constant_prelude.msl new file mode 100644 index 000000000..56f1448e1 --- /dev/null +++ b/src/SharpEmu.ShaderCompiler.Metal/Templates/format_fetch_constant_prelude.msl @@ -0,0 +1,64 @@ +// BUFFER_LOAD_FORMAT_* at a site whose descriptor word 3 is a function constant +// (PortableBufferWord.ConstantsEnabled), called only where the host made the function with a +// value for it. Every value below derives from word3 and count alone, so once Metal substitutes +// the constant the table reads, selectors and conversions fold, and what is left is the literal +// packed form (BeginLiteralPackedFormatLoad, TryEmitLiteralDwordFormatLoad): one test that the +// dwords the selected components lie in are inside the binding, those dwords loaded as one run, +// and each component taken from its dword. An element whose run does not fit (a short final +// element, an access past the end) takes sharpemu_format_fetch, whose results these equal. +static inline uint4 sharpemu_load_words_n(device uint* b, uint bytes, uint addr, uint n) +{ + uint4 result = uint4(0u); + if ((addr & 3u) == 0u) + { + uint index = addr >> 2; + result.x = b[index]; + if (n > 1u) result.y = b[index + 1u]; + if (n > 2u) result.z = b[index + 2u]; + if (n > 3u) result.w = b[index + 3u]; + } + else + { + result.x = sharpemu_load_word(b, bytes, addr); + if (n > 1u) result.y = sharpemu_load_word(b, bytes, addr + 4u); + if (n > 2u) result.z = sharpemu_load_word(b, bytes, addr + 8u); + if (n > 3u) result.w = sharpemu_load_word(b, bytes, addr + 12u); + } + return result; +} + +static inline uint4 sharpemu_format_fetch_constant(device uint* b, uint bytes, uint addr, uint word3, uint count) +{ + uint entry = sharpemu_gfx10_formats[(word3 >> 12) & 0x7Fu]; + uint dfmt = entry & 0xFFu; + uint nfmt = (entry >> 8) & 0xFFu; + uint one = sharpemu_format_one(nfmt); + uint byteOff[4]; + uint bitOff[4]; + uint bits[4]; + uint run = 0u; + for (uint destination = 0u; destination < 4u; destination++) + { + uint selector = (word3 >> (destination * 3u)) & 7u; + sharpemu_format_layout(dfmt, (selector - 4u) & 3u, byteOff[destination], bitOff[destination], bits[destination]); + bool memory = destination < count && selector >= 4u && bits[destination] != 0u; + run = memory ? max(run, (byteOff[destination] >> 2) + 1u) : run; + } + if (run != 0u && !(run * 4u <= bytes && addr <= bytes - run * 4u)) + { + return sharpemu_format_fetch(b, bytes, addr, word3, count); + } + uint4 words = run == 0u ? uint4(0u) : sharpemu_load_words_n(b, bytes, addr, run); + uint4 result = uint4(0u); + for (uint destination = 0u; destination < 4u; destination++) + { + uint selector = (word3 >> (destination * 3u)) & 7u; + uint component = (selector - 4u) & 3u; + uint raw = bits[destination] == 0u ? 0u : + extract_bits(words[(byteOff[destination] >> 2u) & 3u], ((byteOff[destination] & 3u) << 3u) + bitOff[destination], bits[destination]); + uint value = bits[destination] == 0u ? (component == 3u ? one : 0u) : + sharpemu_format_convert(raw, bits[destination], nfmt, dfmt); + result[destination] = destination >= count ? 0u : selector < 4u ? (selector == 1u ? one : 0u) : value; + } + return result; +} diff --git a/src/SharpEmu.ShaderCompiler/Resources/PortableBufferWord.cs b/src/SharpEmu.ShaderCompiler/Resources/PortableBufferWord.cs index 2dc6b54d3..4b3d36e22 100644 --- a/src/SharpEmu.ShaderCompiler/Resources/PortableBufferWord.cs +++ b/src/SharpEmu.ShaderCompiler/Resources/PortableBufferWord.cs @@ -25,6 +25,35 @@ public static class PortableBufferWord public static bool Enabled { get; set; } + /// + /// Each run-time word a portable program reads also becomes a Metal function constant + /// ([[function_constant(n)]]) the program takes in place of the shader-data dword + /// when a function is made with a value for it, so the library stays layout independent + /// and a function specialized for one layout folds the word into its addressing and + /// format decode. A function made without values reads the shader data as before. + /// Process-wide like , and off until the host makes specialized + /// functions. + /// + public static bool ConstantsEnabled { get; set; } + + /// The first function-constant index the buffer words take; 0 is the LOD statistics switch. + public const uint FirstConstantIndex = 1; + + /// The prefix of a buffer word constant's name; completes it. + public const string ConstantNamePrefix = "sharpemu_fc_bw"; + + /// The function-constant index of a buffer's word: 0 is the stride, 1 word 3. + public static uint ConstantIndex(int binding, int word) => + (uint)word > 1 || binding < 0 + ? throw new ArgumentOutOfRangeException(word > 1 ? nameof(word) : nameof(binding)) + : FirstConstantIndex + ((uint)binding * DwordCount) + (uint)word; + + /// + /// The name of the constant at , read in place of shader-data dword + /// : both are spelled in it, so a source declares what it reads. + /// + public static string ConstantName(uint index, uint dword) => $"{ConstantNamePrefix}{index}_sd{dword}"; + public static bool ReadsFormatAtRuntime(BufferResource buffer) => buffer.Formatted && !buffer.Written; /// The run-time words of one V#: the stride and word 3. From 44b19c1181a799130deb7f4c65e530a246d7809d Mon Sep 17 00:00:00 2001 From: kuba Date: Mon, 16 Nov 2026 21:30:28 +0000 Subject: [PATCH 154/178] [Tests] Device tests and bench for buffer-word function constants --- .../MetalNative.Benchmark.cs | 9 +- .../MetalNative.cs | 50 +++- .../MslRuntimeFormatLoadTests.Constants.cs | 277 ++++++++++++++++++ ...ntimeFormatLoadTests.ConstantsBenchmark.cs | 209 +++++++++++++ 4 files changed, 536 insertions(+), 9 deletions(-) create mode 100644 tests/SharpEmu.ShaderCompiler.Metal.Tests/MslRuntimeFormatLoadTests.Constants.cs create mode 100644 tests/SharpEmu.ShaderCompiler.Metal.Tests/MslRuntimeFormatLoadTests.ConstantsBenchmark.cs diff --git a/tests/SharpEmu.ShaderCompiler.Metal.Tests/MetalNative.Benchmark.cs b/tests/SharpEmu.ShaderCompiler.Metal.Tests/MetalNative.Benchmark.cs index 1017b98ef..0ee5f3fba 100644 --- a/tests/SharpEmu.ShaderCompiler.Metal.Tests/MetalNative.Benchmark.cs +++ b/tests/SharpEmu.ShaderCompiler.Metal.Tests/MetalNative.Benchmark.cs @@ -41,10 +41,12 @@ public static bool TryBenchmark( out string error, IReadOnlyList? tables = null, nuint? mathMode = null, - bool groupSizeIsMultipleOfWidth = false) + bool groupSizeIsMultipleOfWidth = false, + IReadOnlyList<(uint Index, uint Value)>? constants = null, + nint library = 0) { result = default; - if (!TryCompileLibrary(shader.Source, out var library, out error, mathMode)) + if (library == 0 && !TryCompileLibrary(shader.Source, out library, out error, mathMode)) { return false; } @@ -73,10 +75,9 @@ public static bool TryBenchmark( return false; } - var function = Send(library, Selector("newFunctionWithName:"), NsString(shader.EntryPoint)); + var function = NewFunction(library, shader.EntryPoint, constants, out error); if (function == 0) { - error = $"entry point '{shader.EntryPoint}' not found"; return false; } diff --git a/tests/SharpEmu.ShaderCompiler.Metal.Tests/MetalNative.cs b/tests/SharpEmu.ShaderCompiler.Metal.Tests/MetalNative.cs index 664d6259d..a2de2ca58 100644 --- a/tests/SharpEmu.ShaderCompiler.Metal.Tests/MetalNative.cs +++ b/tests/SharpEmu.ShaderCompiler.Metal.Tests/MetalNative.cs @@ -235,7 +235,8 @@ public static bool TryExecuteWithArgumentBuffer( uint threadgroupCount = 1, IReadOnlyList? tables = null, IReadOnlyList? bindlessTables = null, - Func? textureOfClass = null) + Func? textureOfClass = null, + IReadOnlyList<(uint Index, uint Value)>? constants = null) { result = []; stepCapHits = 0; @@ -340,7 +341,8 @@ public static bool TryExecuteWithArgumentBuffer( bufferContents.Length, out result, out error, - threadgroupCount)) + threadgroupCount, + constants)) { return false; } @@ -706,6 +708,44 @@ private static nint SharedBuffer(byte[] contents) } } + private const nuint MetalDataTypeUInt = 33; + + /// A library function: plain (newFunctionWithName:) when + /// is null, otherwise specialized with those uint function + /// constants (newFunctionWithName:constantValues:error:), an empty list giving none. + public static unsafe nint NewFunction( + nint library, string entryPoint, IReadOnlyList<(uint Index, uint Value)>? constants, out string error) + { + error = string.Empty; + if (constants is null) + { + var plain = Send(library, Selector("newFunctionWithName:"), NsString(entryPoint)); + if (plain == 0) + { + error = $"entry point '{entryPoint}' not found in the compiled library"; + } + + return plain; + } + + var values = Send(Send(objc_getClass("MTLFunctionConstantValues"), Selector("alloc")), Selector("init")); + foreach (var (index, value) in constants) + { + var word = value; + SendSetBuffer(values, Selector("setConstantValue:type:atIndex:"), (nint)(&word), MetalDataTypeUInt, index); + } + + nint nsError = 0; + var function = Send(library, Selector("newFunctionWithName:constantValues:error:"), NsString(entryPoint), values, ref nsError); + SendVoid(values, Selector("release")); + if (function == 0) + { + error = $"specializing '{entryPoint}' failed: {DescribeError(nsError)}"; + } + + return function; + } + private static bool RunKernel( nint library, string entryPoint, @@ -716,15 +756,15 @@ private static bool RunKernel( int resultLength, out byte[] result, out string error, - uint threadgroupCount = 1) + uint threadgroupCount = 1, + IReadOnlyList<(uint Index, uint Value)>? constants = null) { result = []; error = string.Empty; - var function = Send(library, Selector("newFunctionWithName:"), NsString(entryPoint)); + var function = NewFunction(library, entryPoint, constants, out error); if (function == 0) { - error = $"entry point '{entryPoint}' not found in the compiled library"; return false; } diff --git a/tests/SharpEmu.ShaderCompiler.Metal.Tests/MslRuntimeFormatLoadTests.Constants.cs b/tests/SharpEmu.ShaderCompiler.Metal.Tests/MslRuntimeFormatLoadTests.Constants.cs new file mode 100644 index 000000000..1b0bde079 --- /dev/null +++ b/tests/SharpEmu.ShaderCompiler.Metal.Tests/MslRuntimeFormatLoadTests.Constants.cs @@ -0,0 +1,277 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using System.Buffers.Binary; +using System.Diagnostics; +using SharpEmu.ShaderCompiler.Resources; +using Xunit; + +namespace SharpEmu.ShaderCompiler.Metal.Tests; + +// Buffer words as function constants (PortableBufferWord.ConstantsEnabled): a function made +// with the values reads them, one made without reads the shader data as before. +public sealed partial class MslRuntimeFormatLoadTests +{ + private static Gen5MslCodegenOptions ConstantOptions(bool constants) => + new(ForceRegisterInitialization: true) { BufferWordConstants = constants }; + + // BUFFER_LOAD_FORMAT with IDXEN: v1 = s0 is the index, the stride multiplies it. + private static Gen5ComputeFixture IndexedFixture(uint components) => new( + "runtime-format-load-indexed", + [ + 0x7E020200, // v_mov_b32 v1, s0 + 0xE0002000 | ((components - 1) << 18), 0x80020401, // buffer_load_format v[4:], v1, s[8:11] idxen + 0xE0700000, 0x80030400, + 0xE0700004, 0x80030500, + 0xE0700008, 0x80030600, + 0xE070000C, 0x80030700, + 0xBF810000, + ], 12, BufferBytes); + + // BUFFER_STORE_FORMAT_XYZW v[4:7] to s[8:11] at offset s0: a written formatted buffer. + private static Gen5ComputeFixture StoreFormatFixture() => new( + "runtime-format-store", + [ + 0x7E020200, // v_mov_b32 v1, s0 + 0xE01C1000, 0x80020401, // buffer_store_format_xyzw v[4:7], v1, s[8:11] offen + 0xBF810000, + ], 12, BufferBytes); + + private static int ReadBinding(Gen5MslShader shader) => + (int)((shader.BufferWordConstants.Single(constant => (constant.Index - PortableBufferWord.FirstConstantIndex) % 2 == 1).Index - + PortableBufferWord.FirstConstantIndex) / 2); + + private static byte[] Push(BindingLayout layout, uint offset, IReadOnlyDictionary words) + { + var push = Push(layout, 0, offset); + foreach (var (binding, (stride, word3)) in words) + { + var at = (int)(layout.FirstBufferWordDword() + (uint)binding * PortableBufferWord.DwordCount) * 4; + BinaryPrimitives.WriteUInt32LittleEndian(push.AsSpan(at), stride); + BinaryPrimitives.WriteUInt32LittleEndian(push.AsSpan(at + 4), word3); + } + + return push; + } + + [Fact] + public void ConstantIndicesFollowTheBindingAndWord() + { + Assert.Equal(1u, PortableBufferWord.ConstantIndex(0, 0)); + Assert.Equal(2u, PortableBufferWord.ConstantIndex(0, 1)); + Assert.Equal(7u, PortableBufferWord.ConstantIndex(3, 0)); + Assert.Equal(8u, PortableBufferWord.ConstantIndex(3, 1)); + Assert.Throws(() => PortableBufferWord.ConstantIndex(0, 2)); + Assert.NotEqual(Gen5MslShader.MipStatisticsFunctionConstantIndex, PortableBufferWord.FirstConstantIndex); + } + + [Fact] + public void SwitchOffKeepsTodaysSource() + { + foreach (var fixture in new[] { Fixture(4), IndexedFixture(3), StoreFormatFixture() }) + { + var (today, _) = Compile(fixture, new Gen5MslCodegenOptions(ForceRegisterInitialization: true)); + var (off, _) = Compile(fixture, ConstantOptions(false)); + Assert.Equal(today.Source, off.Source); + Assert.Empty(off.BufferWordConstants); + Assert.DoesNotContain(PortableBufferWord.ConstantNamePrefix, off.Source); + Assert.Empty(Gen5MslShader.ParseBufferWordConstants(off.Source)); + } + } + + [Fact] + public void EachWordReadIsOneConstant() + { + var (shader, layout) = Compile(IndexedFixture(4), ConstantOptions(true)); + var binding = ReadBinding(shader); + var words = layout.FirstBufferWordDword() + (uint)binding * PortableBufferWord.DwordCount; + Assert.Equal( + [ + new Gen5MslShader.BufferWordConstant(PortableBufferWord.ConstantIndex(binding, 0), words), + new Gen5MslShader.BufferWordConstant(PortableBufferWord.ConstantIndex(binding, 1), words + 1), + ], + shader.BufferWordConstants); + Assert.Equal(shader.BufferWordConstants, Gen5MslShader.ParseBufferWordConstants(shader.Source)); + foreach (var constant in shader.BufferWordConstants) + { + Assert.Single(System.Text.RegularExpressions.Regex.Matches( + shader.Source, $@"\[\[function_constant\({constant.Index}\)\]\]")); + } + + Assert.Contains("sharpemu_format_fetch_constant(b", shader.Source); + } + + [Fact] + public void ADeclarationThatDoesNotParseIsRefused() + { + Assert.Equal( + [new Gen5MslShader.BufferWordConstant(3, 12), new Gen5MslShader.BufferWordConstant(4, 13)], + Gen5MslShader.ParseBufferWordConstants( + "constant uint sharpemu_fc_bw4_sd13 [[function_constant(4)]];\n" + + "constant uint sharpemu_fc_bw3_sd12 [[function_constant(3)]];\n")); + Assert.Throws(() => Gen5MslShader.ParseBufferWordConstants( + "constant uint sharpemu_fc_bw3_sd12 [[function_constant(5)]];\n")); + } + + [Fact] + public void AnUnindexedAccessReadsNoStrideConstant() + { + var (shader, _) = Compile(Fixture(4), ConstantOptions(true)); + var constant = Assert.Single(shader.BufferWordConstants); + Assert.Equal(1u, (constant.Index - PortableBufferWord.FirstConstantIndex) % 2); + } + + [Fact] + public void AWrittenFormattedBufferKeepsItsBakedFormat() + { + var (shader, _) = Compile(StoreFormatFixture(), ConstantOptions(true)); + Assert.DoesNotContain(shader.BufferWordConstants, constant => (constant.Index - PortableBufferWord.FirstConstantIndex) % 2 == 1); + Assert.DoesNotContain("sharpemu_format_fetch_constant", shader.Source); + } + + [Fact] + public void AProgramOverTheSiteLimitKeepsTheRuntimeDecode() + { + var (shader, _) = Compile(ManyFetchFixture(Gen5MslTranslator.FormatFetchConstantSiteLimit + 1), ConstantOptions(true)); + Assert.NotEmpty(shader.BufferWordConstants); + Assert.DoesNotContain("sharpemu_format_fetch_constant", shader.Source); + } + + // count BUFFER_LOAD_FORMAT_XY from s[8:11] at offsets 0, 4, ..., each summed into v1. + private static Gen5ComputeFixture ManyFetchFixture(int count) + { + var words = new List { 0x7E020280, 0x7E040200 }; // v_mov_b32 v1, 0; v_mov_b32 v2, s0 + for (var site = 0; site < count; site++) + { + words.AddRange([0xE0041000 | (uint)(site * 4 % 4096), 0x80020402]); // buffer_load_format_xy v[4:5], v2, s[8:11] offen + words.AddRange([0xBF8C0070, 0x4A020304, 0x4A020305]); + } + + words.AddRange([0xE0700000, 0x80030100, 0xBF810000]); // buffer_store_dword v1, off, s[12:15] + return new("runtime-format-many", words.ToArray(), 12, BufferBytes); + } + + private static IEnumerable DecodableFormats() => + Enumerable.Range(0, 128).Select(static format => (uint)format) + .Where(static format => Gfx10UnifiedFormat.TryDecode(format, out var data, out _) && data != 0); + + [Theory] + [InlineData(1u)] + [InlineData(2u)] + [InlineData(3u)] + [InlineData(4u)] + public void TheSpecializedFetchMatchesTheRuntimeDecode(uint components) + { + var (runtime, layout) = Compile(Fixture(components), ConstantOptions(false)); + var (constant, constantLayout) = Compile(Fixture(components), ConstantOptions(true)); + Assert.Equal(layout.FirstBufferWordDword(), constantLayout.FirstBufferWordDword()); + var word3Index = Assert.Single(constant.BufferWordConstants).Index; + if (!RequireDevice()) return; + Assert.True(MetalNative.TryCompileLibrary(runtime.Source, out var runtimeLibrary, out var runtimeError), runtimeError); + Assert.True(MetalNative.TryCompileLibrary(constant.Source, out var constantLibrary, out var constantError), constantError); + var data = Enumerable.Range(0, BufferBytes).Select(i => (byte)(i * 37 + 11)).ToArray(); + // Identity, constants 0 and 1, reordered, repeated W, the reserved selectors. + var swizzles = new uint[] { 0xFAC, 0x204, 0x977, 0xFFF, 0x0D1 }; + var offsets = new uint[] { 0, 1, 2, 33, 64, 113, 120, 122, 124, 126, 127, 128, 200 }; + var specialized = 0; + foreach (var format in DecodableFormats()) + { + foreach (var swizzle in swizzles) + { + var word3 = (format << 12) | swizzle; + // Only the constant can give the right answer: the shader data holds another + // format and swizzle. + var wrong = (((format + 37) & 0x7F) << 12) | (swizzle ^ 0x249); + foreach (var offset in offsets) + { + var right = Push(layout, word3, offset); + Assert.True(MetalNative.TryExecuteWithArgumentBuffer(runtimeLibrary, runtime.EntryPoint, data, right, + runtime.ArgumentLayout!, 1, out var expected, out _, out var runtimeRunError), runtimeRunError); + // No values: the run-time path, exactly today's. Made through + // newFunctionWithName:constantValues: with none: a plain newFunctionWithName: + // function of a source with function constants cannot build a pipeline + // (Metal validation: "Use newFunctionWithName:constantValues:"). + Assert.True(MetalNative.TryExecuteWithArgumentBuffer(constantLibrary, constant.EntryPoint, data, right, + constant.ArgumentLayout!, 1, out var unspecialized, out _, out var plainError, constants: []), plainError); + Assert.True(expected.AsSpan().SequenceEqual(unspecialized), + $"unspecialized components={components} format={format} swizzle=0x{swizzle:X} offset={offset}"); + Assert.True(MetalNative.TryExecuteWithArgumentBuffer(constantLibrary, constant.EntryPoint, data, + Push(layout, wrong, offset), constant.ArgumentLayout!, 1, out var actual, out _, out var specializedError, + constants: [(word3Index, word3)]), specializedError); + Assert.True(expected.AsSpan().SequenceEqual(actual), + $"specialized components={components} format={format} swizzle=0x{swizzle:X} offset={offset}"); + } + + specialized++; + } + } + + output.WriteLine($"components={components} specializations={specialized}"); + } + + [Theory] + [InlineData(4u, 0u)] + [InlineData(4u, 6u)] + [InlineData(3u, 13u)] + public void ASpecializedStrideMatchesTheRuntimeStride(uint components, uint index) + { + var (runtime, layout) = Compile(IndexedFixture(components), ConstantOptions(false)); + var (constant, _) = Compile(IndexedFixture(components), ConstantOptions(true)); + var binding = ReadBinding(constant); + var strideIndex = PortableBufferWord.ConstantIndex(binding, 0); + Assert.Contains(constant.BufferWordConstants, word => word.Index == strideIndex); + Assert.Empty(runtime.BufferWordConstants); + if (!RequireDevice()) return; + Assert.True(MetalNative.TryCompileLibrary(runtime.Source, out var runtimeLibrary, out var runtimeError), runtimeError); + Assert.True(MetalNative.TryCompileLibrary(constant.Source, out var constantLibrary, out var constantError), constantError); + var data = Enumerable.Range(0, BufferBytes).Select(i => (byte)(i * 37 + 11)).ToArray(); + foreach (var stride in new uint[] { 4, 7, 8, 12, 16 }) + { + foreach (var word3 in new[] { (77u << 12) | 0xFAC, (56u << 12) | 0xFAC, (24u << 12) | 0x977 }) + { + var right = Push(layout, index, new Dictionary { [binding] = (stride, word3) }); + Assert.True(MetalNative.TryExecuteWithArgumentBuffer(runtimeLibrary, runtime.EntryPoint, data, right, + runtime.ArgumentLayout!, 1, out var expected, out _, out var runtimeRunError), runtimeRunError); + // The stride alone specialized; word 3 still from the shader data. + var wrongStride = Push(layout, index, new Dictionary { [binding] = (stride * 3 + 1, word3) }); + Assert.True(MetalNative.TryExecuteWithArgumentBuffer(constantLibrary, constant.EntryPoint, data, wrongStride, + constant.ArgumentLayout!, 1, out var strideOnly, out _, out var strideError, + constants: [(strideIndex, stride)]), strideError); + Assert.True(expected.AsSpan().SequenceEqual(strideOnly), $"stride={stride} word3=0x{word3:X} index={index}"); + // Both. + var wrongBoth = Push(layout, index, new Dictionary { [binding] = (stride * 3 + 1, word3 ^ 0x5A249) }); + Assert.True(MetalNative.TryExecuteWithArgumentBuffer(constantLibrary, constant.EntryPoint, data, wrongBoth, + constant.ArgumentLayout!, 1, out var both, out _, out var bothError, + constants: [(strideIndex, stride), (PortableBufferWord.ConstantIndex(binding, 1), word3)]), bothError); + Assert.True(expected.AsSpan().SequenceEqual(both), $"both stride={stride} word3=0x{word3:X} index={index}"); + } + } + } + + [Fact] + public void LibraryCompileTimeWithManySites() + { + if (Environment.GetEnvironmentVariable("SHARPEMU_GPU_BENCH") != "1") return; + if (!RequireDevice()) return; + foreach (var sites in new[] { 8, Gen5MslTranslator.FormatFetchConstantSiteLimit, 256 }) + { + foreach (var (constants, limit) in new[] { (false, 0), (true, Gen5MslTranslator.FormatFetchConstantSiteLimit), (true, 4096) }) + { + if (limit == 4096 && sites <= Gen5MslTranslator.FormatFetchConstantSiteLimit) continue; + var (shader, _) = Compile(ManyFetchFixture(sites), ConstantOptions(constants) with { FormatFetchConstantSiteLimit = limit }); + // A distinct comment keeps the system shader cache out of the timing. + var source = shader.Source + $"\n// {Guid.NewGuid()}\n"; + var clock = Stopwatch.StartNew(); + Assert.True(MetalNative.TryCompileLibrary(source, out var library, out var error), error); + var libraryMs = clock.Elapsed.TotalMilliseconds; + clock.Restart(); + Assert.True(MetalNative.TryExecuteWithArgumentBuffer(library, shader.EntryPoint, new byte[BufferBytes], new byte[PushData.ByteSize], + shader.ArgumentLayout!, 1, out _, out _, out var runError, constants: []), runError); + var pipelineMs = clock.Elapsed.TotalMilliseconds; + var folded = shader.Source.Contains("sharpemu_format_fetch_constant(b", StringComparison.Ordinal); + output.WriteLine(FormattableString.Invariant( + $"sites={sites} constants={constants} folded={folded} library_ms={libraryMs:F0} unspecialized_pipeline_ms={pipelineMs:F0} source_bytes={source.Length}")); + } + } + } +} diff --git a/tests/SharpEmu.ShaderCompiler.Metal.Tests/MslRuntimeFormatLoadTests.ConstantsBenchmark.cs b/tests/SharpEmu.ShaderCompiler.Metal.Tests/MslRuntimeFormatLoadTests.ConstantsBenchmark.cs new file mode 100644 index 000000000..79c453244 --- /dev/null +++ b/tests/SharpEmu.ShaderCompiler.Metal.Tests/MslRuntimeFormatLoadTests.ConstantsBenchmark.cs @@ -0,0 +1,209 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using System.Buffers.Binary; +using System.Diagnostics; +using SharpEmu.ShaderCompiler.Resources; +using Xunit; + +namespace SharpEmu.ShaderCompiler.Metal.Tests; + +public sealed partial class MslRuntimeFormatLoadTests +{ + private const uint VertexStride = 40; + private const uint VertexCount = 1024; + private const int OutputBase = 65536; + + // An interleaved vertex the way Demon's Souls lays its streams out: one V# per attribute + // (s[0:27]), all with stride 40. (srsrc, offset, components, unified format, swizzle). + private static readonly (uint Resource, uint Offset, uint Components, uint Format, uint Swizzle)[] VertexAttributes = + [ + (0, 0, 3, 74, 0xFAC), // position 32_32_32 FLOAT + (1, 12, 4, 45, 0xFAC), // normal 10_10_10_2 SNORM + (2, 16, 4, 51, 0xFAC), // tangent 2_10_10_10 SNORM + (3, 20, 4, 56, 0xFAC), // colour 8_8_8_8 UNORM + (4, 24, 2, 29, 0xFAC), // uv0 16_16 FLOAT + (5, 28, 2, 24, 0xFAC), // uv1 16_16 SNORM + (6, 32, 4, 65, 0xFAC), // weights 16_16_16_16 UNORM + ]; + + // Each lane fetches every attribute of vertex (lane + i) & 1023 for 256 iterations and sums + // the words; the sum goes to s[28:31] past the vertices. s32 holds the group id. + private static Gen5ComputeFixture VertexFetchFixture() + { + var words = new List + { + 0x7E040300, // v_mov_b32 v2, v0 + 0x7E020280, // v_mov_b32 v1, 0 + 0xBEA103FF, 256, // s_mov_b32 s33, 256 + }; + var loop = words.Count; + foreach (var (resource, offset, components, _, _) in VertexAttributes) + { + // buffer_load_format v[4:], v2, s[4r:4r+3], offset idxen + words.AddRange([0xE0002000 | ((components - 1) << 18) | offset, 0x80000402 | (resource << 16)]); + words.Add(0xBF8C0070); + for (uint component = 0; component < components; component++) + { + words.Add(0x4A020304 + component); // v_add_nc_u32 v1, v(4+c), v1 + } + } + + words.AddRange([ + 0x4A040481, // v_add_nc_u32 v2, 1, v2 + 0x360404FF, VertexCount - 1, // v_and_b32 v2, 1023, v2 + 0x81A18121, // s_sub_i32 s33, s33, 1 + 0xBF078021, // s_cmp_lg_u32 s33, 0 + ]); + words.Add(0xBF850000 | (ushort)(short)(loop - words.Count - 1)); + words.AddRange([ + 0x34140082, // v_lshlrev_b32 v10, 2, v0 + 0x7E120220, // v_mov_b32 v9, s32 (group x) + 0x34121287, // v_lshlrev_b32 v9, 7, v9 + 0x4A121509, // v_add_nc_u32 v9, v9, v10 + 0x4A1212FF, OutputBase, // v_add_nc_u32 v9, 65536, v9 + 0xE0701000, 0x80070109, // buffer_store_dword v1, v9, s[28:31] offen + 0xBF810000, + ]); + return new("vertex-fetch-benchmark", words.ToArray(), 28, OutputBase + 1024 * 128); + } + + // portable: the run-time layout (today's default); baked: strides and formats in the source. + private static (Gen5MslShader Shader, BindingLayout Layout, Dictionary Words) CompileVertexFetch( + bool portable, bool constants) + { + var fixture = VertexFetchFixture(); + var program = Gen5ComputeFixtures.DecodeOrThrow(fixture); + var plan = ShaderResourcePlan.Extract(program, ShaderStage.Compute, 0x1234, 0, 32); + var specialization = ResourceSpecialization.Default(plan.Info); + var words = new Dictionary(); + // The attributes are fetched in order, each from its own V#, and the store comes last. + var byFirstUse = Enumerable.Range(0, plan.Info.Buffers.Count) + .OrderBy(binding => plan.Info.Buffers[binding].FirstUsePc).ToArray(); + Assert.Equal(VertexAttributes.Length + 1, byFirstUse.Length); + for (var resource = 0; resource < VertexAttributes.Length; resource++) + { + var binding = byFirstUse[resource]; + var attribute = VertexAttributes[resource]; + Assert.True(plan.Info.Buffers[binding].Formatted); + words[binding] = (VertexStride, (attribute.Format << 12) | attribute.Swizzle); + if (!portable) + specialization.Buffers[binding] = new BufferSpecialization(VertexStride, attribute.Format, attribute.Swizzle); + } + + Assert.Equal(VertexAttributes.Length, words.Count); + var resources = ResourceMaterializer.ApplyTo(plan, specialization); + var layout = BindingLayout.Allocate(resources.Info, + BindingLayout.CollectUserDataRegisters(program, 0, 32), + false, false, false, portableBuffers: portable); + var request = new ShaderCompileRequest(plan, resources, layout) + { + LocalSizeX = 32, + ComputeSystemRegisters = new Gen5ComputeSystemRegisters(32, null, null, null), + }; + Assert.True(Gen5MslTranslator.TryCompileProgram(request, out var shader, out var error, + new Gen5MslCodegenOptions(ForceRegisterInitialization: true) { BufferWordConstants = constants }), error); + return (shader, layout, words); + } + + // The shader data: in the push block when the layout fits it there, else the ShaderData table. + private static (byte[] Push, IReadOnlyList? Tables) VertexPush( + BindingLayout layout, IReadOnlyDictionary words) + { + var push = new byte[PushData.ByteSize]; + var block = new uint[Math.Max(layout.ShaderDataDwordCount, 1)]; + if (layout.BufferWordCount != 0) + { + foreach (var (binding, (stride, word3)) in words) + { + var at = layout.FirstBufferWordDword() + (uint)binding * PortableBufferWord.DwordCount; + block[at] = stride; + block[at + 1] = word3; + } + } + + if (layout.UsesPushData) + { + for (var i = 0; i < block.Length && layout.PushDataStartDword + i < PushData.DwordCount; i++) + BinaryPrimitives.WriteUInt32LittleEndian(push.AsSpan((int)(layout.PushDataStartDword + i) * 4), block[i]); + return (push, null); + } + + return (push, [MetalNative.CreateWordTable(DescriptorBindingKind.ShaderData, block)]); + } + + [Fact] + public void BenchmarkBufferWordConstants() + { + if (Environment.GetEnvironmentVariable("SHARPEMU_GPU_BENCH") != "1") return; + if (!RequireDevice()) return; + var data = Enumerable.Range(0, VertexFetchFixture().StoreBackingBytes).Select(i => (byte)(i * 37 + 11)).ToArray(); + var portable = CompileVertexFetch(portable: true, constants: false); + var baked = CompileVertexFetch(portable: false, constants: false); + var constant = CompileVertexFetch(portable: true, constants: true); + Assert.Equal(VertexAttributes.Length * 2, constant.Shader.BufferWordConstants.Count); + Assert.Equal(portable.Layout.FirstBufferWordDword(), constant.Layout.FirstBufferWordDword()); + output.WriteLine($"push={portable.Layout.UsesPushData} shader_data_dwords={portable.Layout.ShaderDataDwordCount}"); + var right = VertexPush(portable.Layout, portable.Words); + var wrong = VertexPush(constant.Layout, constant.Words.ToDictionary(pair => pair.Key, _ => (0u, 0u))); + var values = constant.Words + .SelectMany(pair => new[] + { + (PortableBufferWord.ConstantIndex(pair.Key, 0), pair.Value.Stride), + (PortableBufferWord.ConstantIndex(pair.Key, 1), pair.Value.Word3), + }) + .ToArray(); + var arms = new (string Name, Gen5MslShader Shader, (byte[] Push, IReadOnlyList? Tables) Data, (uint, uint)[]? Constants)[] + { + ("a-portable-runtime", portable.Shader, right, null), + ("b-baked-literal", baked.Shader, VertexPush(baked.Layout, baked.Words), null), + ("c-constants-unspecialized", constant.Shader, right, []), + ("d-constants-specialized", constant.Shader, wrong, values), + }; + var libraries = new nint[arms.Length]; + byte[]? expected = null; + for (var arm = 0; arm < arms.Length; arm++) + { + var (name, shader, (push, tables), constants) = arms[arm]; + var source = shader.Source + $"\n// {Guid.NewGuid()}\n"; + var clock = Stopwatch.StartNew(); + Assert.True(MetalNative.TryCompileLibrary(source, out libraries[arm], out var compileError), compileError); + var libraryMs = clock.Elapsed.TotalMilliseconds; + clock.Restart(); + Assert.True(MetalNative.TryExecuteWithArgumentBuffer(libraries[arm], shader.EntryPoint, data, push, shader.ArgumentLayout!, + 32, out var result, out _, out var runError, threadgroupCount: 1024, tables: tables, constants: constants), runError); + var pipelineMs = clock.Elapsed.TotalMilliseconds; + output.WriteLine(FormattableString.Invariant( + $"{name} library_ms={libraryMs:F0} pipeline_and_run_ms={pipelineMs:F0} source_bytes={source.Length}")); + Assert.False(result.AsSpan(OutputBase, 128).SequenceEqual(data.AsSpan(OutputBase, 128))); + expected ??= result; + Assert.True(expected.AsSpan(OutputBase).SequenceEqual(result.AsSpan(OutputBase)), $"{name} output differs from arm a"); + } + + var best = new double[arms.Length]; + Array.Fill(best, double.MaxValue); + for (var round = 0; round < 6; round++) + { + var order = Enumerable.Range(0, arms.Length).ToArray(); + if (round % 2 == 1) Array.Reverse(order); + foreach (var arm in order) + { + var (name, shader, (push, tables), constants) = arms[arm]; + Assert.True(MetalNative.TryBenchmark(shader, data, push, 1024, 32, 4, out var result, out var error, + tables: tables, constants: constants, library: libraries[arm]), error); + Assert.False(result.StepCapHit); + best[arm] = Math.Min(best[arm], result.GpuMilliseconds); + output.WriteLine(FormattableString.Invariant( + $"{name} round={round} gpu_ms={result.GpuMilliseconds:F4} max_threads={result.MaxThreadsPerThreadgroup}")); + } + } + + // 1024 groups x 32 lanes x 256 vertices x 4 dispatches. + const double elements = 1024.0 * 32 * 256 * 4; + for (var arm = 0; arm < arms.Length; arm++) + { + output.WriteLine(FormattableString.Invariant( + $"best {arms[arm].Name} gpu_ms={best[arm]:F4} ns_per_vertex={best[arm] * 1e6 / elements:F4} vs_b={best[arm] / best[1]:F3}")); + } + } +} From 7d3fcbd038edbedf6ef223a500e2c25da0567339 Mon Sep 17 00:00:00 2001 From: kuba Date: Mon, 16 Nov 2026 21:52:45 +0000 Subject: [PATCH 155/178] [Metal] Draw through pipelines specialized for each draw's buffer words SHARPEMU_METAL_V2_BUFFER_WORD_CONSTANTS (on with portable buffers; =0 restores today's MSL) turns PortableBufferWord.ConstantsEnabled on in ApplyTranslationSwitches, so the prewarm and the command stream translate alike; the prewarm stamp names the switches, which keys the static precompile's finished units, the only store that does not follow the source text. Every function made from a translated library goes through NewTranslatedFunction (the LOD statistics switch and buffer-word values, none for the generic function), which replaces NewMipStatisticsFunction: a source that declares the constants must be made with constant values. A render pipeline whose programs declare buffer words keeps up to 16 variants in a worker-only open-addressed table. Each draw hashes the words its shader data holds at the declared dwords (CommitBindings records the stages) and draws through the variant once it is built; the first draw of a layout draws through the generic pipeline and queues the variant on two background builders that compile at prewarm priority (EnterPrewarm). Specialized functions are cached per module (at most 64), made outside the module's lock. A variant is listed in the archive under its own pair key and in the state table under its values. Mesh, rectangle-list and tessellation pipelines, the pixel stage of a remapped pipeline, and compute programs stay generic; every generic draw of a declaring program is counted on the PERF line (buffer_words=[...]). --- docs/macos/configuration.md | 1 + .../V2/MetalRenderHost.BufferWordVariants.cs | 747 ++++++++++++++++++ .../V2/MetalRenderHost.Descriptors.cs | 2 + .../V2/MetalRenderHost.LodStatistics.cs | 31 +- .../V2/MetalRenderHost.Pipelines.cs | 71 +- .../V2/MetalRenderHost.Rendering.cs | 19 +- .../V2/MetalRenderHost.ShaderCache.cs | 3 + .../V2/MetalRenderHost.SubsetJoin.cs | 6 +- .../SharpEmu.Gpu.Metal/V2/MetalRenderHost.cs | 2 + .../V2/MetalShaderPrewarm.cs | 12 +- .../V2/MetalStaticPrecompile.cs | 12 +- .../V2/MetalUnstoredLibraries.cs | 2 + .../MetalBufferWordVariantTests.cs | 515 ++++++++++++ .../MetalMipStatisticsFunctionTests.cs | 4 +- .../SharpEmu.Gpu.Metal.Tests/MetalPassRig.cs | 8 +- .../GpuBench.cs | 11 +- .../Program.cs | 9 +- 17 files changed, 1380 insertions(+), 75 deletions(-) create mode 100644 src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.BufferWordVariants.cs create mode 100644 tests/SharpEmu.Gpu.Metal.Tests/MetalBufferWordVariantTests.cs diff --git a/docs/macos/configuration.md b/docs/macos/configuration.md index 833da6678..99c337141 100644 --- a/docs/macos/configuration.md +++ b/docs/macos/configuration.md @@ -106,6 +106,7 @@ undoes an optimization to isolate a miscompile: | `SHARPEMU_MSL_PERSISTENT_RECORDS` | on | Accesses multi-dword records of persistent-thread kernels dword by dword. | | `SHARPEMU_MSL_BYTEBIAS` | off | `1` keeps the per-buffer byte bias. | | `SHARPEMU_MSL_FUSE_MAD` | on | Emits the guest's legacy multiply-adds (`V_MAD_F32`, `V_MAC_F32`) as one fused operation in compute programs and pixel programs without depth export. Faster (about 5 ms of an 82 ms Demon's Souls frame) but not bit-exact for MAD/MAC: the guest rounds the product first. `0` restores the exact two-op form. | +| `SHARPEMU_METAL_V2_BUFFER_WORD_CONSTANTS` | on | With portable buffers (`SHARPEMU_METAL_V2_PORTABLE_BUFFERS`, on), each buffer stride and format word a program reads at run time is also a Metal function constant. A draw draws through its pipeline as before and, once a background compile has made it, through a variant whose functions have the draw's words folded in (same pixels, faster vertex stage). Up to 16 variants a pipeline; mesh, rectangle-list and tessellation pipelines and compute programs stay generic. The periodic counter line reports `buffer_words=[...]`. `0` restores the previous MSL exactly. | | `SHARPEMU_LOD_STATS` | guarded | `always` compiles the LOD statistics counters into every pixel pipeline. | ## Diagnostics diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.BufferWordVariants.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.BufferWordVariants.cs new file mode 100644 index 000000000..05da3b9e0 --- /dev/null +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.BufferWordVariants.cs @@ -0,0 +1,747 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using System.Collections.Concurrent; +using System.Globalization; +using System.IO.Hashing; +using System.Runtime.InteropServices; +using SharpEmu.Libs.Gpu.Pipelines; +using SharpEmu.Libs.Gpu.Rendering; +using SharpEmu.ShaderCompiler.Metal; +using SharpEmu.ShaderCompiler.Resources; + +namespace SharpEmu.Gpu.Metal.V2; + +/// +/// Render pipelines specialized for a draw's buffer words (PortableBufferWord.ConstantsEnabled). +/// A portable program reads each V#'s stride and word 3 through a function constant that, when +/// the function is made without a value, falls back to the shader-data dword. The pipeline the +/// executor creates is that generic one. Before each draw the host reads the words the draw's +/// shader data holds at the dwords the vertex and pixel programs declare constants for, and +/// draws through a pipeline whose functions were made with exactly those values once it is +/// built: the same result, with the stride and format folded into the code (Demon's Souls' +/// vertex stage: 12.16 ms a frame portable, 7.62 ms baked). +/// +/// +/// The first draw of a layout draws through the generic pipeline, as today, and queues the +/// variant on a background builder that compiles at prewarm priority (MetalCompileScheduler); +/// later draws take the variant once it is ready. Nothing is skipped or waited for. A pipeline +/// keeps at most variants and a module at most +/// specialized functions; past either the +/// draw stays on the generic pipeline and is counted. Mesh, rectangle-list and tessellation +/// pipelines stay generic, and so does the pixel stage of a pipeline with remapped colour +/// outputs. SHARPEMU_METAL_V2_BUFFER_WORD_CONSTANTS=0 turns the constants off in translation. +/// +internal sealed partial class MetalRenderHost +{ + /// + /// The buffer words of a portable program are function constants + /// (PortableBufferWord.ConstantsEnabled), on with portable buffers unless + /// SHARPEMU_METAL_V2_BUFFER_WORD_CONSTANTS=0, which restores today's MSL exactly. + /// + internal static readonly bool BufferWordConstants = + PortableBuffers && Environment.GetEnvironmentVariable("SHARPEMU_METAL_V2_BUFFER_WORD_CONSTANTS") != "0"; + + /// The translation switches that decide the MSL, for the stamps of what is stored by them. + internal static string TranslationSwitchStamp => + $"portable={(PortableBuffers ? 1 : 0)},buffer_word_constants={(BufferWordConstants ? 1 : 0)}"; + + /// Variants one pipeline entry keeps; a draw of another layout past them draws generic. + internal const int MaxBufferWordVariantsPerPipeline = 16; + + /// + /// Specialized functions one module makes; past them its variants stay generic. Some 1,260 + /// specializations of one library in one process logged "AGX: exceeded compiled variants + /// footprint limit". + /// + internal const int MaxBufferWordSpecializationsPerModule = 64; + + private static readonly nint SelBufferWordRetain = MetalNative.Selector("retain"); + private const int BufferWordVariantSlots = 32; + private const nuint MetalDataTypeUInt = 33; + private const int BufferWordVariantPending = 0; + private const int BufferWordVariantReady = 1; + private const int BufferWordVariantFailed = 2; + private const int BufferWordVariantCapped = 3; + private const int BufferWordVariantAbandoned = 4; + + /// + /// The function of a translated library. A source that declares + /// function constants (the LOD statistics switch when is + /// set, buffer words when is not empty) is made with + /// newFunctionWithName:constantValues:error:, with the values given and none for the + /// buffer words when is empty: a function of such a source made + /// with the plain selector fails pipeline validation and aborts the process. The caller + /// owns the function, or zero with . + /// + internal static unsafe nint NewTranslatedFunction( + nint library, + string entry, + bool? mipStatistics, + ReadOnlySpan declared, + ReadOnlySpan values, + out nint error) + { + error = 0; + if (mipStatistics is null && declared.IsEmpty) + { + return MetalNative.Send(library, MetalNative.Selector("newFunctionWithName:"), MetalNative.NsString(entry)); + } + + if (!values.IsEmpty && values.Length != declared.Length) + { + throw new ArgumentException( + $"Buffer-word values do not match the constants declared: values={values.Length} declared={declared.Length}.", + nameof(values)); + } + + var constants = MetalNative.Send( + MetalNative.Send(MetalNative.Class("MTLFunctionConstantValues"), MetalNative.Selector("alloc")), + MetalNative.Selector("init")); + try + { + var setValue = MetalNative.Selector("setConstantValue:type:atIndex:"); + var mip = mipStatistics == true ? (byte)1 : (byte)0; + if (mipStatistics is not null) + { + MetalNative.SendSetConstantValue( + constants, setValue, (nint)(&mip), MetalDataTypeBool, Gen5MslShader.MipStatisticsFunctionConstantIndex); + } + + fixed (uint* words = values) + { + for (var index = 0; index < values.Length; index++) + { + MetalNative.SendSetConstantValue(constants, setValue, (nint)(words + index), MetalDataTypeUInt, declared[index].Index); + } + + return MetalNative.Send( + library, + MetalNative.Selector("newFunctionWithName:constantValues:error:"), + MetalNative.NsString(entry), + constants, + ref error); + } + } + finally + { + MetalNative.SendVoid(constants, MetalNative.Selector("release")); + } + } + + /// As , + /// the generic function of a translated shader. + internal static nint NewTranslatedFunction(nint library, Gen5MslShader shader, bool mipStatistics, out nint error) => + NewTranslatedFunction( + library, + shader.EntryPoint, + shader.UsesMipStatisticsConstant ? mipStatistics : null, + BufferWordConstantsOf(shader), + [], + out error); + + private static ReadOnlySpan BufferWordConstantsOf(Gen5MslShader shader) => + shader.BufferWordConstants switch + { + Gen5MslShader.BufferWordConstant[] array => array, + List list => CollectionsMarshal.AsSpan(list), + var other => other.ToArray(), + }; + + /// + /// The archive key a variant's shader pair is listed under: the generic pair's pixel key + /// mixed with the variant's values (), so the + /// same libraries list their generic pipeline and each variant apart. + /// + internal static UInt128 BufferWordArchiveKey(UInt128 pixelPairKey, UInt128 values) => + values == default ? pixelPairKey : pixelPairKey ^ values ^ new UInt128(0x4255464645525F57UL, 0x4F5244535F564152UL); + + // The constants of a pipeline's programs, its variants, and a scratch row for the values a + // draw holds. On the GPU worker but for the builder's reads of Vertex, Pixel and a + // variant it was handed. + private sealed class BufferWordVariants(Gen5MslShader.BufferWordConstant[] vertex, Gen5MslShader.BufferWordConstant[] pixel) + { + public readonly Gen5MslShader.BufferWordConstant[] Vertex = vertex; + public readonly Gen5MslShader.BufferWordConstant[] Pixel = pixel; + public readonly uint[] Scratch = new uint[vertex.Length + pixel.Length]; + public readonly BufferWordVariant?[] Table = new BufferWordVariant?[BufferWordVariantSlots]; + public int Count; + } + + // One variant: the values (vertex constants first), their hash, the archive key, and the + // state once built. Status moves from pending exactly once, by compare-exchange: to a + // final state on the builder, or to abandoned on the worker when the entry lets go first. + private sealed class BufferWordVariant(uint[] values, ulong hash, UInt128 archiveKey) + { + public readonly uint[] Values = values; + public readonly ulong Hash = hash; + public readonly UInt128 ArchiveKey = archiveKey; + public nint State; + public int Status; + } + + // The specialized functions a variant pipeline is made from; zero takes the generic one. + private sealed record BufferWordPipeline(nint VertexFunction, nint PixelFunction, uint[] Values, int VertexCount, UInt128 ArchiveKey); + + // A module's specialized function, by its values (and the LOD statistics switch of a pixel function). + private sealed class SpecializationKey(bool? mipStatistics, uint[] values) : IEquatable + { + private readonly bool? _mipStatistics = mipStatistics; + private readonly uint[] _values = values; + + public bool Equals(SpecializationKey? other) => + other is not null && other._mipStatistics == _mipStatistics && other._values.AsSpan().SequenceEqual(_values); + + public override bool Equals(object? obj) => Equals(obj as SpecializationKey); + + public override int GetHashCode() + { + var hash = new HashCode(); + hash.Add(_mipStatistics); + foreach (var value in _values) + { + hash.Add(value); + } + + return hash.ToHashCode(); + } + } + + // The stages of the draw being recorded, from CommitBindings, whose shader data the + // variant lookup reads. On the GPU worker. + private MetalStageBindings? _bufferWordVertexStage; + private MetalStageBindings? _bufferWordPixelStage; + + private readonly BlockingCollection<(MetalPipelineEntry Entry, BufferWordVariants Variants, BufferWordVariant Variant)> _bufferWordQueue = new(); + private MetalCompileThread[]? _bufferWordBuilders; + private volatile bool _bufferWordStopping; + private int _bufferWordPending; + + // Worker-only draw counters for programs that declare buffer words, taken by the PERF line. + private long _bufferWordDrawsVariant; + private long _bufferWordDrawsGeneric; + private long _bufferWordDrawsPending; + private long _bufferWordDrawsCapped; + private long _bufferWordDrawsGenericKind; + private long _bufferWordDrawsUnreadable; + private long _bufferWordDrawsFailed; + + // Builder counters. + private long _bufferWordVariantsBuilt; + private long _bufferWordVariantsFailed; + private long _bufferWordVariantsCapped; + + /// Runs on the builder before it compiles a variant; tests hold it. + internal Action? BeforeBufferWordVariantBuild { get; set; } + + /// Variants queued or compiling. + internal int BufferWordVariantsPending => Volatile.Read(ref _bufferWordPending); + + /// The variant counters since the host started, for tests. + internal (long Built, long Failed, long Capped, long DrawsVariant, long DrawsGeneric, long DrawsPending, long DrawsCapped) BufferWordCounters => + (Interlocked.Read(ref _bufferWordVariantsBuilt), Interlocked.Read(ref _bufferWordVariantsFailed), + Interlocked.Read(ref _bufferWordVariantsCapped), _bufferWordDrawsVariant, _bufferWordDrawsGeneric, + _bufferWordDrawsPending, _bufferWordDrawsCapped); + + /// Waits until no variant is queued or compiling, for tests. + internal bool WaitForBufferWordVariants(TimeSpan timeout) + { + var deadline = System.Diagnostics.Stopwatch.GetTimestamp() + (long)(timeout.TotalSeconds * System.Diagnostics.Stopwatch.Frequency); + while (BufferWordVariantsPending != 0) + { + if (System.Diagnostics.Stopwatch.GetTimestamp() > deadline) + { + return false; + } + + Thread.Sleep(1); + } + + return true; + } + + /// The stages of the draw being recorded; CommitBindings sets them, tests too. + internal void NoteBufferWordStages(MetalStageBindings? vertex, MetalStageBindings? pixel) + { + _bufferWordVertexStage = vertex; + _bufferWordPixelStage = pixel; + } + + private void NoteBufferWordStages(ReadOnlySpan stages) + { + MetalStageBindings? vertex = null; + MetalStageBindings? pixel = null; + foreach (var prepared in stages) + { + var stage = (MetalStageBindings)prepared; + switch (StageIndexOf(stage.Program.Stage)) + { + case StageVertex: + vertex = stage; + break; + case StageFragment: + pixel = stage; + break; + } + } + + NoteBufferWordStages(vertex, pixel); + } + + // The variants of a new pipeline entry: null when neither program declares buffer words, + // or when its kind stays generic (mesh, rectangle list, tessellation). + private static BufferWordVariants? BufferWordVariantsFor( + GraphicsPipelineDescription description, + MetalShaderModule vertexModule, + MetalShaderModule? pixelModule, + Gen5MslMeshInfo? mesh, + bool rectangleList) + { + if (mesh is not null || rectangleList || vertexModule.Shader.Tessellation is not null) + { + return null; + } + + var vertex = vertexModule.Shader.BufferWordConstants; + // A remapped pixel function is a library of its own (RequireRemappedPixelFunction). + var pixel = pixelModule is not null && description.ColorRemap == 0 + ? pixelModule.Shader.BufferWordConstants + : []; + return vertex.Count + pixel.Count == 0 ? null : new BufferWordVariants([.. vertex], [.. pixel]); + } + + private static bool DeclaresBufferWords(MetalShaderModule vertexModule, MetalShaderModule? pixelModule) => + vertexModule.Shader.BufferWordConstants.Count != 0 || pixelModule is { Shader.BufferWordConstants.Count: not 0 }; + + /// + /// The render pipeline state a draw of draws with: the variant + /// made for the words the draw's shader data holds once it is ready, else the generic + /// state, with the reason counted. On the GPU worker, once per draw: a hash of the + /// declared words and a probe of a small open-addressed table; a new layout allocates + /// its variant and queues its build. + /// + private nint GraphicsStateOf(MetalPipelineEntry entry) + { + if (!entry.DeclaresBufferWords) + { + return entry.State; + } + + if (entry.BufferWordVariants is not { } variants) + { + _bufferWordDrawsGenericKind++; + _bufferWordDrawsGeneric++; + return entry.State; + } + + var values = variants.Scratch; + if (!TryReadBufferWords(_bufferWordVertexStage, variants.Vertex, values.AsSpan(0, variants.Vertex.Length)) || + !TryReadBufferWords(_bufferWordPixelStage, variants.Pixel, values.AsSpan(variants.Vertex.Length))) + { + _bufferWordDrawsUnreadable++; + _bufferWordDrawsGeneric++; + return entry.State; + } + + var hash = XxHash3.HashToUInt64(MemoryMarshal.AsBytes(values.AsSpan())); + var table = variants.Table; + var slot = (int)hash & (BufferWordVariantSlots - 1); + while (table[slot] is { } candidate) + { + if (candidate.Hash == hash && candidate.Values.AsSpan().SequenceEqual(values)) + { + switch (Volatile.Read(ref candidate.Status)) + { + case BufferWordVariantReady: + _bufferWordDrawsVariant++; + return candidate.State; + case BufferWordVariantPending: + _bufferWordDrawsPending++; + break; + case BufferWordVariantCapped: + _bufferWordDrawsCapped++; + break; + default: + _bufferWordDrawsFailed++; + break; + } + + _bufferWordDrawsGeneric++; + return entry.State; + } + + slot = (slot + 1) & (BufferWordVariantSlots - 1); + } + + _bufferWordDrawsGeneric++; + if (variants.Count >= MaxBufferWordVariantsPerPipeline) + { + _bufferWordDrawsCapped++; + MetalV2Diagnostics.WarnOnce( + "buffer-word-variant-cap", + $"A pipeline drew more buffer-word layouts than it keeps variants for; the rest draw generic: " + + $"pipeline={entry.Id} vertex=0x{entry.VertexHash:X16} variants={variants.Count}."); + return entry.State; + } + + var copy = values.ToArray(); + var variant = new BufferWordVariant(copy, hash, VariantArchiveKey(copy, variants.Vertex.Length)); + table[slot] = variant; + variants.Count++; + _bufferWordDrawsPending++; + QueueBufferWordVariant(entry, variants, variant); + return entry.State; + } + + // The words a stage's shader data holds at the dwords its program declares constants for. + private static bool TryReadBufferWords( + MetalStageBindings? stage, Gen5MslShader.BufferWordConstant[] declared, Span values) + { + if (declared.Length == 0) + { + return true; + } + + if (stage is null) + { + return false; + } + + var data = stage.ShaderData; + for (var index = 0; index < declared.Length; index++) + { + var dword = declared[index].Dword; + if (dword >= (uint)data.Length) + { + return false; + } + + values[index] = data[dword]; + } + + return true; + } + + private static UInt128 VariantArchiveKey(uint[] values, int vertexCount) + { + var key = XxHash128.HashToUInt128(MemoryMarshal.AsBytes(values.AsSpan()), vertexCount); + return key == default ? UInt128.One : key; + } + + private void QueueBufferWordVariant(MetalPipelineEntry entry, BufferWordVariants variants, BufferWordVariant variant) + { + if (_bufferWordBuilders is null) + { + // Two builders: a variant waits behind the game's compiles anyway (EnterPrewarm). + _bufferWordBuilders = new MetalCompileThread[2]; + for (var index = 0; index < _bufferWordBuilders.Length; index++) + { + _bufferWordBuilders[index] = MetalCompileThread.Start( + "SharpEmu Metal v2 buffer-word variants", SharpEmu.HLE.Host.HostThreadQos.Utility, RunBufferWordBuilder); + } + } + + Interlocked.Increment(ref _bufferWordPending); + if (_bufferWordStopping || !_bufferWordQueue.TryAdd((entry, variants, variant))) + { + Interlocked.CompareExchange(ref variant.Status, BufferWordVariantFailed, BufferWordVariantPending); + Interlocked.Decrement(ref _bufferWordPending); + } + } + + private void RunBufferWordBuilder() + { + try + { + foreach (var (entry, variants, variant) in _bufferWordQueue.GetConsumingEnumerable()) + { + BuildBufferWordVariant(entry, variants, variant); + } + } + catch (ObjectDisposedException) + { + // The host went away. + } + } + + private void BuildBufferWordVariant(MetalPipelineEntry entry, BufferWordVariants variants, BufferWordVariant variant) + { + var status = BufferWordVariantFailed; + nint state = 0; + nint vertexFunction = 0; + nint pixelFunction = 0; + try + { + if (_bufferWordStopping || Volatile.Read(ref variant.Status) != BufferWordVariantPending) + { + status = BufferWordVariantAbandoned; + return; + } + + BeforeBufferWordVariantBuild?.Invoke(); + using var slot = MetalCompileScheduler.Shared.EnterPrewarm(() => _bufferWordStopping); + if (!slot.Entered) + { + status = BufferWordVariantAbandoned; + return; + } + + var description = entry.GraphicsDescription ?? + throw new InvalidOperationException($"A buffer-word variant has no description: pipeline={entry.Id}."); + var vertexModule = RequireModule(description.VertexProgram, onWorker: false); + var pixelModule = description.PixelStage is not null && description.PixelProgram.IsValid + ? RequireModule(description.PixelProgram, onWorker: false) + : null; + // Made from now on: the bound keeps a module it made a pipeline from in the last + // seconds (TrimModules), as it does for the compiler threads' builds. + var now = System.Diagnostics.Stopwatch.GetTimestamp(); + vertexModule.LastUsedTicks = now; + if (pixelModule is not null) + { + pixelModule.LastUsedTicks = now; + } + + var vertexCount = variants.Vertex.Length; + if (vertexCount != 0 && + (vertexFunction = RetainSpecializedFunction(vertexModule, null, variants.Vertex, variant.Values[..vertexCount])) == 0) + { + status = BufferWordVariantCapped; + return; + } + + if (variants.Pixel.Length != 0) + { + var mip = pixelModule!.Shader.UsesMipStatisticsConstant ? description.LodStatistics : (bool?)null; + if ((pixelFunction = RetainSpecializedFunction(pixelModule, mip, variants.Pixel, variant.Values[vertexCount..])) == 0) + { + status = BufferWordVariantCapped; + return; + } + } + + state = CreateRenderPipelineState( + description, vertexModule, pixelModule, null, false, Mtl.ControlPointIndexTypeNone, out _, + new BufferWordPipeline(vertexFunction, pixelFunction, variant.Values, vertexCount, variant.ArchiveKey)); + status = BufferWordVariantReady; + } + catch (Exception exception) + { + // The draws keep the generic pipeline, which gives the same result; the counter + // and this line say the variant is missing. + if (_bufferWordStopping) + { + status = BufferWordVariantAbandoned; + return; + } + + Console.Error.WriteLine( + $"[METAL-V2][WARN] A buffer-word variant could not be built; its draws stay generic: " + + $"pipeline={entry.Id} vertex=0x{entry.VertexHash:X16} {exception.Message}"); + } + finally + { + foreach (var function in (ReadOnlySpan)[vertexFunction, pixelFunction]) + { + if (function != 0) + { + MetalNative.SendVoid(function, SelRelease); + } + } + + PublishBufferWordVariant(variant, status, state); + Interlocked.Decrement(ref _bufferWordPending); + } + } + + private void PublishBufferWordVariant(BufferWordVariant variant, int status, nint state) + { + if (status == BufferWordVariantReady) + { + variant.State = state; + } + + var published = status != BufferWordVariantAbandoned && + Interlocked.CompareExchange(ref variant.Status, status, BufferWordVariantPending) == BufferWordVariantPending; + if (!published) + { + // The entry let go of it first (or the host is stopping): nothing will draw with it. + if (state != 0) + { + ReleaseState(state); + } + + Interlocked.CompareExchange(ref variant.Status, BufferWordVariantAbandoned, BufferWordVariantPending); + return; + } + + if (status == BufferWordVariantReady) + { + Interlocked.Increment(ref _bufferWordVariantsBuilt); + } + else if (status == BufferWordVariantCapped) + { + Interlocked.Increment(ref _bufferWordVariantsCapped); + } + else + { + Interlocked.Increment(ref _bufferWordVariantsFailed); + } + } + + /// + /// The function of specialized with , + /// made once and kept with the module like its LOD statistics function, retained for the + /// caller; zero once the module has made . + /// The function is made outside the module's lock: the worker takes it to release an idle + /// module, and must not wait for a specialization meanwhile. + /// + private nint RetainSpecializedFunction( + MetalShaderModule module, bool? mipStatistics, Gen5MslShader.BufferWordConstant[] declared, uint[] values) + { + var key = new SpecializationKey(mipStatistics, values); + nint library; + lock (module) + { + RequireResidentModule(module); + if (module.SpecializedFunctions?.TryGetValue(key, out var known) == true) + { + MetalNative.Send(known, SelBufferWordRetain); + return known; + } + + if ((module.SpecializedFunctions?.Count ?? 0) >= MaxBufferWordSpecializationsPerModule) + { + return 0; + } + + library = module.Library; + MetalNative.Send(library, SelBufferWordRetain); + } + + nint function; + nint error; + try + { + function = NewTranslatedFunction(library, module.Shader.EntryPoint, mipStatistics, declared, values, out error); + } + finally + { + MetalNative.SendVoid(library, SelRelease); + } + + if (function == 0) + { + throw new InvalidOperationException( + $"The specialized function could not be made: hash=0x{module.Hash:X16} {MetalNative.DescribeError(error)}."); + } + + lock (module) + { + if (module.Library != library || module.Function == 0) + { + MetalNative.SendVoid(function, SelRelease); + throw new InvalidOperationException( + $"The module's library was released while it was specialized: hash=0x{module.Hash:X16}."); + } + + module.SpecializedFunctions ??= new(); + if (module.SpecializedFunctions.TryGetValue(key, out var winner)) + { + // Another builder made the same one first. + MetalNative.SendVoid(function, SelRelease); + function = winner; + } + else + { + module.SpecializedFunctions.Add(key, function); + } + + MetalNative.Send(function, SelBufferWordRetain); + return function; + } + + static void RequireResidentModule(MetalShaderModule module) + { + if (module.Library == 0 || module.Function == 0) + { + throw new InvalidOperationException($"The module's library was released: hash=0x{module.Hash:X16}."); + } + } + } + + // Under the module's lock. + private static void ReleaseSpecializedFunctions(MetalShaderModule module) + { + if (module.SpecializedFunctions is not { } functions) + { + return; + } + + foreach (var function in functions.Values) + { + MetalNative.SendVoid(function, SelRelease); + } + + module.SpecializedFunctions = null; + } + + // The variants of an entry whose states go (the bound released it, or the host is going). + // On the GPU worker. One still compiling is abandoned: its builder releases what it made. + private void ReleaseBufferWordVariants(MetalPipelineEntry entry) + { + if (entry.BufferWordVariants is not { Count: not 0 } variants) + { + return; + } + + var table = variants.Table; + for (var index = 0; index < table.Length; index++) + { + if (table[index] is not { } variant) + { + continue; + } + + if (Interlocked.CompareExchange(ref variant.Status, BufferWordVariantAbandoned, BufferWordVariantPending) != + BufferWordVariantPending && + Volatile.Read(ref variant.Status) == BufferWordVariantReady) + { + ReleaseState(variant.State); + } + + table[index] = null; + } + + variants.Count = 0; + } + + // Before the pipelines are released at disposal: the builders finish what they hold. + private void StopBufferWordBuilders() + { + _bufferWordStopping = true; + _bufferWordQueue.CompleteAdding(); + foreach (var builder in _bufferWordBuilders ?? []) + { + if (!builder.IsCurrentThread) + { + builder.Join(TimeSpan.FromSeconds(30)); + } + } + } + + // The PERF line's view: variants built, queued or compiling, and refused at a module's cap + // or failed; then draws of programs that declare buffer words on a variant, on the generic + // pipeline, and of those why: variant not ready, a pipeline's cap, a kind that stays + // generic, words not readable, or a variant that failed or was capped. + private string FormatBufferWordCounters() => + string.Create(CultureInfo.InvariantCulture, + $"built={Interlocked.Read(ref _bufferWordVariantsBuilt)} pending={BufferWordVariantsPending} " + + $"capped={Interlocked.Read(ref _bufferWordVariantsCapped)} failed={Interlocked.Read(ref _bufferWordVariantsFailed)} " + + $"draws_variant={Interlocked.Exchange(ref _bufferWordDrawsVariant, 0)} " + + $"draws_generic={Interlocked.Exchange(ref _bufferWordDrawsGeneric, 0)} " + + $"generic_pending={Interlocked.Exchange(ref _bufferWordDrawsPending, 0)} " + + $"generic_capped={Interlocked.Exchange(ref _bufferWordDrawsCapped, 0)} " + + $"generic_kind={Interlocked.Exchange(ref _bufferWordDrawsGenericKind, 0)} " + + $"generic_unreadable={Interlocked.Exchange(ref _bufferWordDrawsUnreadable, 0)} " + + $"generic_failed={Interlocked.Exchange(ref _bufferWordDrawsFailed, 0)}"); +} diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Descriptors.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Descriptors.cs index fda2d5af2..0c8a15a81 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Descriptors.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Descriptors.cs @@ -270,6 +270,7 @@ public void ResetBindings() DisarmPendingCopy(); _pendingGraphicsPipeline = null; _pendingComputePipeline = null; + NoteBufferWordStages(null, null); _vertexBufferCount = 0; _indexBuffer = 0; _acquisitionSequence++; @@ -1589,6 +1590,7 @@ public void CommitBindings(GpuBindPoint bindPoint, in PipelineHandle pipeline, R if (bindPoint == GpuBindPoint.Graphics) { NoteJoinStages(stages); + NoteBufferWordStages(stages); } Span pushData = stackalloc uint[(int)PushData.DwordCount]; diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.LodStatistics.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.LodStatistics.cs index c7f49ace0..041cc04be 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.LodStatistics.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.LodStatistics.cs @@ -45,35 +45,6 @@ internal sealed partial class MetalRenderHost private bool _lodStatsCompiledOut; private bool _lodStatsPrimed; - /// - /// The function of a pixel (or any) library entry that declares the LOD statistics function - /// constant, specialized with ; the caller owns it, or zero. - /// - internal static unsafe nint NewMipStatisticsFunction(nint library, string entry, bool enabled, out nint error) - { - error = 0; - var values = MetalNative.Send( - MetalNative.Send(MetalNative.Class("MTLFunctionConstantValues"), MetalNative.Selector("alloc")), - MetalNative.Selector("init")); - try - { - var value = enabled ? (byte)1 : (byte)0; - MetalNative.SendSetConstantValue( - values, MetalNative.Selector("setConstantValue:type:atIndex:"), (nint)(&value), MetalDataTypeBool, - Gen5MslShader.MipStatisticsFunctionConstantIndex); - return MetalNative.Send( - library, - MetalNative.Selector("newFunctionWithName:constantValues:error:"), - MetalNative.NsString(entry), - values, - ref error); - } - finally - { - MetalNative.SendVoid(values, MetalNative.Selector("release")); - } - } - private const nuint MetalDataTypeBool = 53; // After the bank: the slots the last report said were sampled, those whose finest mip @@ -200,6 +171,8 @@ internal static void ApplyTranslationSwitches() { EnableLodStatistics(); PortableBufferWord.Enabled = PortableBuffers; + // Only a portable program has run-time words (MetalRenderHost.BufferWordVariants). + PortableBufferWord.ConstantsEnabled = BufferWordConstants; } /// GET_LOD_STATS reports this host packed on the GPU. diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Pipelines.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Pipelines.cs index 4c0069824..c4cb0127b 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Pipelines.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Pipelines.cs @@ -83,6 +83,12 @@ private sealed class MetalPipelineEntry // state is only released once that command buffer is done and it has been idle. public ulong LastUsedSerial; public long LastUsedTicks; + + // Whether either program declares buffer-word function constants, and the variants + // specialized for the words a draw holds (MetalRenderHost.BufferWordVariants); null + // when the pipeline's kind stays generic. + public bool DeclaresBufferWords; + public BufferWordVariants? BufferWordVariants; } // One compiled MSL module: its library, its function, and the shader it came from. @@ -122,6 +128,10 @@ private sealed class MetalShaderModule // built the first time a subset join needs that remap of this program. public Dictionary<(uint Remap, bool LodStatistics), (nint Library, nint Function, UInt128 ArchiveKey)>? RemappedFunctions; + // The functions specialized with buffer words for variant pipelines, made on the + // variant builder the first time a variant needs them (RetainSpecializedFunction). + public Dictionary? SpecializedFunctions; + // The binary archive keys of the library and of the rectangle-list library (zero // with no archive): the pipeline made from them stores them under these. public UInt128 ArchiveKey; @@ -276,11 +286,7 @@ private void BuildModule(MetalShaderModule module, ShaderStage stage) var pool = MetalNative.objc_autoreleasePoolPush(); try { - nint specializationError = 0; - var function = shader.UsesMipStatisticsConstant - ? NewMipStatisticsFunction(library, shader.EntryPoint, enabled: false, out specializationError) - : MetalNative.Send( - library, MetalNative.Selector("newFunctionWithName:"), MetalNative.NsString(shader.EntryPoint)); + var function = NewTranslatedFunction(library, shader, mipStatistics: false, out var specializationError); if (function == 0) { ReleaseLibrary(library); @@ -328,7 +334,7 @@ private nint PixelFunctionOf(MetalShaderModule module, bool lodStatistics) return module.LodFunction; } - var function = NewMipStatisticsFunction(module.Library, module.Shader.EntryPoint, enabled: true, out var error); + var function = NewTranslatedFunction(module.Library, module.Shader, mipStatistics: true, out var error); if (function == 0) { throw Fatal( @@ -350,16 +356,20 @@ private nint RequireRectangleFunction(MetalShaderModule module) return module.RectangleFunction; } + var shader = module.Compiled.AcquireShader(); var library = CompileLibrary( - Gen5MslRectangleList.BuildSource(module.Compiled.AcquireShader()), module.Hash, usesPerVertexInputs: false, prewarmable: true, + Gen5MslRectangleList.BuildSource(shader), module.Hash, usesPerVertexInputs: false, prewarmable: true, out module.RectangleArchiveKey, out module.RectangleSourceKey); - var function = MetalNative.Send( - library, MetalNative.Selector("newFunctionWithName:"), MetalNative.NsString(Gen5MslRectangleList.EntryPoint)); + // The post-tessellation form carries the program's declarations: its buffer words + // stay generic (MetalRenderHost.BufferWordVariants). + var function = NewTranslatedFunction( + library, Gen5MslRectangleList.EntryPoint, null, BufferWordConstantsOf(shader), [], out var error); if (function == 0) { ReleaseLibrary(library); throw Fatal( - $"The rectangle-list MSL library has no entry point: entry={Gen5MslRectangleList.EntryPoint} hash=0x{module.Hash:X16}."); + $"The rectangle-list MSL library has no entry point: entry={Gen5MslRectangleList.EntryPoint} hash=0x{module.Hash:X16}" + + (error != 0 ? $" {MetalNative.DescribeError(error)}." : ".")); } module.RectangleLibrary = library; @@ -889,6 +899,8 @@ private PipelineHandle RegisterGraphicsPipeline(GraphicsPipelineDescription desc VertexLayout = compiled.VertexLayout, GraphicsDescription = description, LastUsedTicks = System.Diagnostics.Stopwatch.GetTimestamp(), + DeclaresBufferWords = DeclaresBufferWords(vertexModule, pixelModule), + BufferWordVariants = BufferWordVariantsFor(description, vertexModule, pixelModule, mesh, rectangleList), }; _pipelineEntries[entry.Id] = entry; Interlocked.Increment(ref _residentPipelines); @@ -932,7 +944,8 @@ private nint CreateRenderPipelineState( Gen5MslMeshInfo? mesh, bool rectangleList, nuint controlPointIndexType, - out string? vertexLayout) + out string? vertexLayout, + BufferWordPipeline? bufferWords = null) { var parameters = description.StaticParameters; var descriptorClass = mesh is null ? "MTLRenderPipelineDescriptor" : "MTLMeshRenderPipelineDescriptor"; @@ -953,7 +966,9 @@ private nint CreateRenderPipelineState( MetalNative.SendVoid( descriptor, MetalNative.Selector("setVertexFunction:"), - rectangleList ? RequireRectangleFunction(vertexModule) : vertexModule.Function); + rectangleList ? RequireRectangleFunction(vertexModule) + : bufferWords is { VertexFunction: not 0 } ? bufferWords.VertexFunction + : vertexModule.Function); MetalV2Native.SendVoidValue( descriptor, MetalNative.Selector("setRasterSampleCount:"), Math.Max(parameters.Samples, 1)); if (rectangleList) @@ -1004,7 +1019,12 @@ private nint CreateRenderPipelineState( if (pixelModule is not null) { nint pixelFunction; - if (description.ColorRemap != 0) + if (bufferWords is { PixelFunction: not 0 }) + { + // Made with the counters in or out as PixelFunctionOf chooses them. + pixelFunction = bufferWords.PixelFunction; + } + else if (description.ColorRemap != 0) { (pixelFunction, pixelLibraryKey) = RequireRemappedPixelFunction(pixelModule, description.ColorRemap, description.LodStatistics); } @@ -1105,7 +1125,9 @@ private nint CreateRenderPipelineState( vertexModule.Shader.WritesLayer || vertexModule.Shader.WritesViewportIndex, rectangleList, controlPointIndexType, - description.LodStatistics && pixelModule is { Shader.UsesMipStatisticsConstant: true }); + description.LodStatistics && pixelModule is { Shader.UsesMipStatisticsConstant: true }, + bufferWords?.Values, + bufferWords?.VertexCount ?? 0); if (_states.TryAcquire(shareKey, out var shared, out _)) { Interlocked.Increment(ref _pipelineDedups); @@ -1114,7 +1136,8 @@ private nint CreateRenderPipelineState( } nint error = 0; - using var runtime = MetalCompileScheduler.Shared.Runtime(); + // A variant compiles at prewarm priority: its builder holds a prewarm slot. + using var runtime = bufferWords is null ? MetalCompileScheduler.Shared.Runtime() : default; var started = System.Diagnostics.Stopwatch.GetTimestamp(); var archive = MetalBinaryArchive.For(_device); var vertexArchiveKey = rectangleList ? vertexModule.RectangleArchiveKey : vertexModule.ArchiveKey; @@ -1124,6 +1147,8 @@ private nint CreateRenderPipelineState( ? default : MetalBinaryArchive.LodStatisticsKey( pixelModule.ArchiveKey, description.LodStatistics && pixelModule.Shader.UsesMipStatisticsConstant); + // A variant is another pipeline of the same libraries, listed under a pair of its own. + pixelArchiveKey = BufferWordArchiveKey(pixelArchiveKey, bufferWords?.ArchiveKey ?? default); var archives = archive?.AcquirePipelineArchives(vertexArchiveKey, pixelArchiveKey) ?? 0; state = 0; if (archives != 0) @@ -1248,7 +1273,9 @@ internal static MetalPipelineStateKey PipelineStateKeyOf( bool layered, bool rectangleList, nuint controlPointIndexType, - bool lodStatistics = false) + bool lodStatistics = false, + uint[]? bufferWords = null, + int vertexBufferWords = 0) { var parameters = description.StaticParameters; var key = new MetalPipelineStateKey.Builder() @@ -1256,6 +1283,15 @@ internal static MetalPipelineStateKey PipelineStateKeyOf( .Add(pixelSource is not null) .Add(pixelSource ?? default) .Add(lodStatistics) + // The values a variant's functions were specialized with (vertex ones first). + .Add((ulong)vertexBufferWords) + .Add((ulong)(bufferWords?.Length ?? 0)); + foreach (var word in bufferWords ?? []) + { + key.Add((ulong)word); + } + + key .Add(rectangleList) .Add(rectangleList ? controlPointIndexType : 0) .Add(Math.Max(parameters.Samples, 1)) @@ -2173,10 +2209,12 @@ private void DisposePipelines() // Let whatever is still compiling finish before the device goes away. _compiler?.Dispose(); _compiler = null; + StopBufferWordBuilders(); // What this run added to the title's archive is written before its functions go. MetalBinaryArchive.For(_device)?.Flush(wait: true, TimeSpan.FromSeconds(10)); foreach (var entry in _pipelineEntries.Values) { + ReleaseBufferWordVariants(entry); if (entry.State != 0) { ReleaseState(entry.State); @@ -2222,6 +2260,7 @@ private void DisposePipelines() MetalNative.SendVoid(module.LodFunction, SelRelease); } + ReleaseSpecializedFunctions(module); if (module.Library != 0) { ReleaseLibrary(module.Library); diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Rendering.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Rendering.cs index b6be83633..b29632d04 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Rendering.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Rendering.cs @@ -1630,13 +1630,20 @@ private void ApplyGraphicsState() var entry = _pendingGraphicsPipeline ?? throw Fatal("A draw has no bound Metal render pipeline state."); - if (!ReferenceEquals(_boundGraphicsPipeline, entry)) + var entryChanged = !ReferenceEquals(_boundGraphicsPipeline, entry); + if (entryChanged) { // Every later draw of this encoder with the entry (its rectangle states too) is // in the same command buffer. UsePipelineState(entry); - MetalNative.SendVoid(_renderEncoder, SelSetRenderPipelineState, entry.State); - _boundRenderState = entry.State; + } + + // The variant made for this draw's buffer words, once built (MetalRenderHost.BufferWordVariants). + var renderState = GraphicsStateOf(entry); + if (entryChanged) + { + MetalNative.SendVoid(_renderEncoder, SelSetRenderPipelineState, renderState); + _boundRenderState = renderState; SignpostPipeline(_renderEncoder, entry); MetalV2Native.SendVoidValue( _renderEncoder, SelSetCullMode, (nuint)(MetalV2Diagnostics.IgnoreCulling ? Mtl.CullModeNone : entry.CullMode)); @@ -1645,6 +1652,12 @@ private void ApplyGraphicsState() MetalV2Native.SendVoidValue(_renderEncoder, SelSetTriangleFillMode, (nuint)entry.FillMode); _boundGraphicsPipeline = entry; } + else if (entry.BufferWordVariants is not null && _boundRenderState != renderState) + { + // The same entry, another layout: its variant (or the generic state) in place of the last. + MetalNative.SendVoid(_renderEncoder, SelSetRenderPipelineState, renderState); + _boundRenderState = renderState; + } // Encoder state survives between draws, so only what changed is sent. A draw // costs twenty-odd message sends otherwise, and consecutive draws in one pass diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.ShaderCache.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.ShaderCache.cs index e49f3ff42..e70718645 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.ShaderCache.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.ShaderCache.cs @@ -256,6 +256,8 @@ private int TrimModules(long now, MetalShaderCacheLimits limits) private void ReleasePipelineState(MetalPipelineEntry entry) { + // Its variants are built again when draws ask for them. + ReleaseBufferWordVariants(entry); ReleaseState(entry.State); if (entry.RectangleStates is { } rectangles) { @@ -292,6 +294,7 @@ private bool ReleaseModule(MetalShaderModule module) module.LodFunction = 0; } + ReleaseSpecializedFunctions(module); ReleaseLibrary(module.Library); if (module.RectangleFunction != 0) { diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.SubsetJoin.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.SubsetJoin.cs index fcb6b977a..5e00adc70 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.SubsetJoin.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.SubsetJoin.cs @@ -345,10 +345,8 @@ private bool PixelOutputsMovable(in ShaderProgram program) return slot < 0 ? match.Value : $"[[color({slot})"; }); var library = CompileLibrary(source, module.Hash, shader.UsesPerVertexInputs, prewarmable: true, out var archiveKey, out _); - nint error = 0; - var function = shader.UsesMipStatisticsConstant - ? NewMipStatisticsFunction(library, shader.EntryPoint, enabled: counters, out error) - : MetalNative.Send(library, MetalNative.Selector("newFunctionWithName:"), MetalNative.NsString(shader.EntryPoint)); + // Its buffer words stay generic (MetalRenderHost.BufferWordVariants). + var function = NewTranslatedFunction(library, shader, mipStatistics: counters, out var error); if (function == 0) { ReleaseLibrary(library); diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.cs index 0341272b5..5f8f0ec6e 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.cs @@ -2897,6 +2897,8 @@ public void ReportCounters() // queued or running on the compiler threads now. $"draws_skipped_compiling={Interlocked.Exchange(ref _drawsSkippedCompiling, 0)} " + $"leave_out=[{FormatLeaveOutCounters()}] " + + // Pipelines specialized for a draw's buffer words, and the draws on them (FormatBufferWordCounters). + $"buffer_words=[{FormatBufferWordCounters()}] " + $"pipeline_waits_blocking={Interlocked.Exchange(ref _pipelineWaitsBlocking, 0)} " + $"async_compiles_inflight={PipelinesCompiling} " + // Read-aheads of the dispatches after one waiting on its pipeline, the dispatches diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalShaderPrewarm.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalShaderPrewarm.cs index 170006dbe..b9404609e 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalShaderPrewarm.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalShaderPrewarm.cs @@ -221,7 +221,6 @@ internal static class MetalShaderPrewarm private const int MaxLoggedPrewarmFailures = 8; private const int PrewarmProgressBatch = 256; - private static readonly nint SelNewFunctionWithName = MetalNative.Selector("newFunctionWithName:"); private static readonly nint SelNewComputePipelineState = MetalNative.Selector("newComputePipelineStateWithFunction:error:"); private static readonly nint SelRelease = MetalNative.Selector("release"); @@ -817,6 +816,9 @@ private static string Stamp(IGuestGpuBackend compiler, nint device) => StampPart(typeof(Gen5MslTranslator)), compiler.GetType().FullName, MslMathMode.Identity(MslMathMode.Default), + // The switches decide the MSL as the translators do; what is stored under this stamp + // and not keyed by source text (the static precompile's finished units) follows them. + MetalRenderHost.TranslationSwitchStamp, MetalNative.ReadNsString(MetalNative.Send(device, SelName)), RuntimeInformation.OSDescription); @@ -938,10 +940,14 @@ private static void CompileComputePipeline(ComputePrewarmRecord record, MetalCom return; } - function = MetalNative.Send(library, SelNewFunctionWithName, MetalNative.NsString(metal.Shader.EntryPoint)); + // The generic function, as the module the dispatch creates makes it (BuildModule). + function = MetalRenderHost.NewTranslatedFunction(library, metal.Shader, mipStatistics: false, out var functionError); if (function == 0) { - NoteFailure(record, $"the library has no entry point {metal.Shader.EntryPoint}"); + NoteFailure( + record, + $"the library has no entry point {metal.Shader.EntryPoint}" + + (functionError != 0 ? $": {MetalNative.DescribeError(functionError)}" : string.Empty)); return; } diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalStaticPrecompile.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalStaticPrecompile.cs index b1ad28fdd..d8cb861c9 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalStaticPrecompile.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalStaticPrecompile.cs @@ -569,7 +569,9 @@ internal static List Translate(StaticShaderBuild build, IGuestGpu /// it returns. The file's bytes, or -1 (with the reason, or none when skipped). /// internal static long Store(MetalBinaryArchive archive, nint device, Gen5MslShader shader, UInt128 key, out string? error) => - Store(archive, device, shader.Source, shader.EntryPoint, shader.UsesPerVertexInputs, shader.UsesMipStatisticsConstant, key, out error); + Store( + archive, device, shader.Source, shader.EntryPoint, shader.UsesPerVertexInputs, shader.UsesMipStatisticsConstant, + shader.BufferWordConstants, key, out error); /// As , from the shader's parts. internal static long Store( @@ -579,6 +581,7 @@ internal static long Store( string entry, bool usesPerVertexInputs, bool usesMipStatisticsConstant, + IReadOnlyList bufferWordConstants, UInt128 key, out string? error) { @@ -622,10 +625,9 @@ internal static long Store( return -1; } - nint functionError = 0; - function = usesMipStatisticsConstant - ? MetalRenderHost.NewMipStatisticsFunction(library, entry, enabled: false, out functionError) - : MetalNative.Send(library, SelNewFunctionWithName, MetalNative.NsString(entry)); + // The generic function: no buffer-word values (MetalRenderHost.NewTranslatedFunction). + function = MetalRenderHost.NewTranslatedFunction( + library, entry, usesMipStatisticsConstant ? false : null, [.. bufferWordConstants], [], out var functionError); if (function == 0) { error = $"the library has no entry point {entry}" + diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalUnstoredLibraries.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalUnstoredLibraries.cs index 1758e5bcc..8d7177c20 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalUnstoredLibraries.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalUnstoredLibraries.cs @@ -195,6 +195,8 @@ private static bool Store(UInt128 key, Entry entry) entryPoint, entry.UsesPerVertexInputs, UsesMipStatisticsConstant(entry.Source), + // A stored source carries no metadata: its buffer-word declarations are read off it. + Gen5MslShader.ParseBufferWordConstants(entry.Source), key, out var error); if (bytes > 0) diff --git a/tests/SharpEmu.Gpu.Metal.Tests/MetalBufferWordVariantTests.cs b/tests/SharpEmu.Gpu.Metal.Tests/MetalBufferWordVariantTests.cs new file mode 100644 index 000000000..a66249464 --- /dev/null +++ b/tests/SharpEmu.Gpu.Metal.Tests/MetalBufferWordVariantTests.cs @@ -0,0 +1,515 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using System.Runtime.InteropServices; +using SharpEmu.Gpu.Metal.V2; +using SharpEmu.Libs.Gpu.Abstractions; +using SharpEmu.Libs.Gpu.Pipelines; +using SharpEmu.Libs.Gpu.Rendering; +using SharpEmu.ShaderCompiler.Metal; +using SharpEmu.ShaderCompiler.Resources; +using Xunit; +using Xunit.Abstractions; + +namespace SharpEmu.Gpu.Metal.Tests; + +/// +/// Render pipelines specialized for a draw's buffer words (MetalRenderHost.BufferWordVariants): +/// the first draw of a layout draws through the generic pipeline while its variant builds, later +/// draws take the variant, which draws the same pixels; the variant follows only the words the +/// program declares, a pipeline keeps a bounded number of them, and a variant is listed in the +/// archive and the state table apart from the generic pipeline. The vertex program here is +/// written by hand in the translator's form (Gen5MslTranslator.BufferWordConstants): a stride +/// and a format word, each a function constant over its shader-data dword, which pick how the +/// packed vertex records are decoded. Device work is behind the exclusive device gate. +/// +public sealed unsafe class MetalBufferWordVariantTests(ITestOutputHelper output) +{ + private const uint Width = 16; + private const uint Height = 16; + private const ulong TargetBytes = Width * Height * 4; + private const ulong FirstTarget = MetalPassRig.GuestBase + 0x10000; + // The vertex records start past the 16 dwords of words at the head of the bound buffer. + private const int RecordOffset = 64; + private const int BufferBytes = 4096; + private const uint Snorm16x2 = 1; + private const uint Float32x2 = 2; + private static readonly TimeSpan BuildTimeout = TimeSpan.FromSeconds(60); + + // Binding 0's stride (dword 0) and word 3 (dword 1); dword 2 is a word the program never reads. + private static readonly Gen5MslShader.BufferWordConstant[] Declared = + [ + new(PortableBufferWord.ConstantIndex(0, 0), 0), + new(PortableBufferWord.ConstantIndex(0, 1), 1), + ]; + + private static readonly string Stride = PortableBufferWord.ConstantName(Declared[0].Index, Declared[0].Dword); + private static readonly string Word3 = PortableBufferWord.ConstantName(Declared[1].Index, Declared[1].Dword); + + // Two triangles that cover part of the target, so a wrong stride or format moves pixels. + private static readonly float[] Positions = + [ + -1.0f, -1.0f, 0.5f, -1.0f, -1.0f, 0.25f, + 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f, + ]; + + private static readonly string VertexSource = + $$""" + #include + using namespace metal; + constant uint {{Stride}} [[function_constant({{Declared[0].Index}})]]; + constant bool {{Stride}}_set = is_function_constant_defined({{Stride}}); + constant uint {{Word3}} [[function_constant({{Declared[1].Index}})]]; + constant bool {{Word3}}_set = is_function_constant_defined({{Word3}}); + + struct Gen5VsOut + { + float4 sharpemu_position [[position]]; + float4 color; + }; + + static inline uint load_u16(device const uchar* bytes, uint at) + { + return uint(bytes[at]) | (uint(bytes[at + 1u]) << 8); + } + + static inline uint load_u32(device const uchar* bytes, uint at) + { + return load_u16(bytes, at) | (load_u16(bytes, at + 2u) << 16); + } + + vertex Gen5VsOut gen5_vs(uint vertex_id [[vertex_id]], device const uint* data [[buffer(2)]]) + { + uint stride = ({{Stride}}_set ? {{Stride}} : data[0]) & 0x3FFFu; + uint word3 = {{Word3}}_set ? {{Word3}} : data[1]; + device const uchar* bytes = (device const uchar*)data + {{RecordOffset}}u; + uint at = vertex_id * stride; + float2 position; + if ((word3 >> 12) == {{Snorm16x2}}u) + { + float2 packed = float2(float(short(load_u16(bytes, at))), float(short(load_u16(bytes, at + 2u)))); + position = max(packed / 32767.0f, float2(-1.0f)); + } + else + { + position = float2(as_type(load_u32(bytes, at)), as_type(load_u32(bytes, at + 4u))); + } + + Gen5VsOut result = {}; + result.sharpemu_position = float4(position, 0.5f, 1.0f); + result.color = float4(float(word3 & 0xFu), float((word3 >> 4) & 0xFu), float((word3 >> 8) & 0xFu), 15.0f) / 15.0f; + return result; + } + """; + + private const string PixelSource = + """ + #include + using namespace metal; + struct PixelIn + { + float4 position [[position]]; + float4 color; + }; + + fragment float4 gen5_ps(PixelIn in [[stage_in]]) + { + return in.color; + } + """; + + private static readonly Lazy Device = new(MetalNative.MTLCreateSystemDefaultDevice); + + [Fact] + public void AVariantIsListedUnderAnotherArchiveKeyThanTheGenericPipeline() + { + var vertex = new UInt128(0x1111, 0x2222); + var pixel = new UInt128(0x1234, 0x5678); + var first = new UInt128(1, 2); + var second = new UInt128(3, 4); + + Assert.Equal(pixel, MetalRenderHost.BufferWordArchiveKey(pixel, default)); + Assert.NotEqual(pixel, MetalRenderHost.BufferWordArchiveKey(pixel, first)); + Assert.NotEqual( + MetalRenderHost.BufferWordArchiveKey(pixel, first), MetalRenderHost.BufferWordArchiveKey(pixel, second)); + // A pipeline without a pixel program lists its variants apart too. + Assert.NotEqual(default, MetalRenderHost.BufferWordArchiveKey(default, first)); + Assert.NotEqual( + MetalBinaryArchive.PairKey(vertex, pixel), + MetalBinaryArchive.PairKey(vertex, MetalRenderHost.BufferWordArchiveKey(pixel, first))); + // With the LOD statistics counters as well. + var counters = MetalBinaryArchive.LodStatisticsKey(pixel, counters: true); + Assert.NotEqual( + MetalBinaryArchive.PairKey(vertex, counters), + MetalBinaryArchive.PairKey(vertex, MetalRenderHost.BufferWordArchiveKey(counters, first))); + } + + [Fact] + public void TheStateTableKeepsVariantsOfOtherValuesApart() + { + var description = Description(new ShaderProgram(1, 1), new ShaderProgram(2, 2)); + var source = new UInt128(7, 8); + MetalPipelineStateKey Key(uint[]? words, int vertexWords = 2) => + MetalRenderHost.PipelineStateKeyOf( + description, source, source, false, false, 0, bufferWords: words, vertexBufferWords: vertexWords); + + Assert.Equal(Key([12, 0x1000]), Key([12, 0x1000])); + Assert.NotEqual(Key(null, 0), Key([12, 0x1000])); + Assert.NotEqual(Key([12, 0x1000]), Key([12, 0x2000])); + // The same values split between the stages another way are another pair of functions. + Assert.NotEqual(Key([12, 0x1000], 2), Key([12, 0x1000], 1)); + } + + [Fact] + public void AFunctionSpecializesWithTheMipSwitchAndBufferWords() + { + if (!RequireDevice()) return; + var source = + $$""" + #include + using namespace metal; + constant bool {{Gen5MslShader.MipStatisticsFunctionConstantName}} [[function_constant({{Gen5MslShader.MipStatisticsFunctionConstantIndex}})]]; + constant uint {{Stride}} [[function_constant({{Declared[0].Index}})]]; + constant bool {{Stride}}_set = is_function_constant_defined({{Stride}}); + constant uint {{Word3}} [[function_constant({{Declared[1].Index}})]]; + constant bool {{Word3}}_set = is_function_constant_defined({{Word3}}); + fragment float4 gen5_ps(float4 position [[position]], device atomic_uint* counters [[buffer(0)]], constant uint* data [[buffer(1)]]) + { + if ({{Gen5MslShader.MipStatisticsFunctionConstantName}}) + { + atomic_fetch_add_explicit(counters, 1u, memory_order_relaxed); + } + + uint stride = {{Stride}}_set ? {{Stride}} : data[0]; + uint word3 = {{Word3}}_set ? {{Word3}} : data[1]; + return position * float(stride) + float(word3); + } + """; + var library = MetalRenderHost.TryCompileLibrary(Device.Value, source, usesPerVertexInputs: false, out var libraryError); + Assert.True(library != 0, libraryError); + var functions = new List(); + try + { + foreach (var (mip, values) in new (bool, uint[])[] { (false, []), (true, []), (true, [12, 0x1000]), (false, [8, 0x2000]) }) + { + var function = MetalRenderHost.NewTranslatedFunction(library, "gen5_ps", mip, Declared, values, out var error); + Assert.True(function != 0, MetalNative.DescribeError(error)); + functions.Add(function); + } + + Assert.Equal(functions.Count, functions.Distinct().Count()); + Assert.Throws( + () => MetalRenderHost.NewTranslatedFunction(library, "gen5_ps", false, Declared, [12], out _)); + } + finally + { + foreach (var handle in functions.Append(library)) + { + MetalNative.SendVoid(handle, MetalNative.Selector("release")); + } + } + } + + [Fact] + public void AnUnstoredLibraryThatDeclaresBufferWordsIsStored() + { + if (!RequireDevice()) return; + var root = Path.Combine(Path.GetTempPath(), $"sharpemu-buffer-words-{Guid.NewGuid():N}"); + try + { + using var archive = MetalBinaryArchive.Open(root, Device.Value, "translator-a", 64L << 20); + // As MetalUnstoredLibraries stores it: everything is read off the source text. + var declared = Gen5MslShader.ParseBufferWordConstants(VertexSource); + Assert.Equal(Declared, declared); + var key = MetalBinaryArchive.LibraryKey(VertexSource, usesPerVertexInputs: false); + var bytes = MetalStaticPrecompile.Store( + archive, + Device.Value, + VertexSource, + MetalUnstoredLibraries.EntryPointOf(VertexSource)!, + usesPerVertexInputs: false, + MetalUnstoredLibraries.UsesMipStatisticsConstant(VertexSource), + declared, + key, + out var error); + Assert.True(bytes > 0, error); + } + finally + { + if (Directory.Exists(root)) + { + Directory.Delete(root, recursive: true); + } + } + } + + [Fact] + public void TheFirstDrawOfANewLayoutDrawsGenericWhileItsVariantBuilds() + { + if (!RequireDevice()) return; + using var rig = new MetalPassRig(Device.Value, 1024 * 1024); + using var gate = new ManualResetEventSlim(false); + rig.Host.BeforeBufferWordVariantBuild = () => gate.Wait(BuildTimeout); + var pipeline = Pipeline(rig, 0x7000_0000); + var layout = Layout(Snorm16x2, 12, 0x0A1); + var buffer = NewBuffer(layout); + var stage = Stage(layout, unread: 0); + try + { + var generic = DrawInto(rig, pipeline, FirstTarget, buffer, stage); + var counters = rig.Host.BufferWordCounters; + Assert.Equal((0L, 1L, 1L, 0L), (counters.DrawsVariant, counters.DrawsGeneric, counters.DrawsPending, counters.Built)); + AssertDrawn(generic, layout); + + gate.Set(); + Assert.True(rig.Host.WaitForBufferWordVariants(BuildTimeout)); + var specialized = DrawInto(rig, pipeline, FirstTarget + 0x1000, buffer, stage); + counters = rig.Host.BufferWordCounters; + Assert.Equal((1L, 1L, 1L), (counters.Built, counters.DrawsVariant, counters.DrawsGeneric)); + Assert.Equal(generic, specialized); + } + finally + { + gate.Set(); + MetalNative.SendVoid(buffer, MetalNative.Selector("release")); + } + } + + [Fact] + public void TheGenericAndTheSpecializedPipelineDrawTheSamePixelsForPackedLayouts() + { + if (!RequireDevice()) return; + using var rig = new MetalPassRig(Device.Value, 1024 * 1024); + var pipeline = Pipeline(rig, 0x7100_0000); + var target = FirstTarget; + foreach (var layout in new[] { Layout(Snorm16x2, 12, 0x0A1), Layout(Float32x2, 8, 0x3F2), Layout(Snorm16x2, 4, 0xF0F) }) + { + var buffer = NewBuffer(layout); + var stage = Stage(layout, unread: 0); + try + { + var before = rig.Host.BufferWordCounters; + var generic = DrawInto(rig, pipeline, target, buffer, stage); + Assert.True(rig.Host.WaitForBufferWordVariants(BuildTimeout)); + var specialized = DrawInto(rig, pipeline, target + 0x1000, buffer, stage); + var after = rig.Host.BufferWordCounters; + output.WriteLine($"stride={layout.Stride} word3=0x{layout.Word3:X} built={after.Built} variant_draws={after.DrawsVariant}"); + Assert.Equal(before.Built + 1, after.Built); + Assert.Equal(before.DrawsVariant + 1, after.DrawsVariant); + AssertDrawn(generic, layout); + Assert.Equal(generic, specialized); + target += 0x2000; + } + finally + { + MetalNative.SendVoid(buffer, MetalNative.Selector("release")); + } + } + } + + [Fact] + public void TheVariantFollowsOnlyTheWordsTheProgramReads() + { + if (!RequireDevice()) return; + using var rig = new MetalPassRig(Device.Value, 1024 * 1024); + var pipeline = Pipeline(rig, 0x7200_0000); + var layout = Layout(Float32x2, 8, 0x123); + var buffer = NewBuffer(layout); + try + { + DrawInto(rig, pipeline, FirstTarget, buffer, Stage(layout, unread: 1)); + Assert.True(rig.Host.WaitForBufferWordVariants(BuildTimeout)); + Assert.Equal(1L, rig.Host.BufferWordCounters.Built); + + // Another value in a dword the program does not declare: the same variant. + DrawInto(rig, pipeline, FirstTarget, buffer, Stage(layout, unread: 0xDEAD)); + Assert.True(rig.Host.WaitForBufferWordVariants(BuildTimeout)); + var counters = rig.Host.BufferWordCounters; + Assert.Equal((1L, 1L), (counters.Built, counters.DrawsVariant)); + + // Another value of a declared word: a variant of its own. + var other = layout with { Word3 = 0x124 }; + DrawInto(rig, pipeline, FirstTarget, buffer, Stage(other, unread: 0xDEAD)); + Assert.True(rig.Host.WaitForBufferWordVariants(BuildTimeout)); + Assert.Equal(2L, rig.Host.BufferWordCounters.Built); + } + finally + { + MetalNative.SendVoid(buffer, MetalNative.Selector("release")); + } + } + + [Fact] + public void LayoutsPastThePipelinesCapDrawGenericAndAreCounted() + { + if (!RequireDevice()) return; + using var rig = new MetalPassRig(Device.Value, 1024 * 1024); + using var gate = new ManualResetEventSlim(false); + rig.Host.BeforeBufferWordVariantBuild = () => gate.Wait(BuildTimeout); + var pipeline = Pipeline(rig, 0x7300_0000); + var layout = Layout(Float32x2, 8, 0x100); + var buffer = NewBuffer(layout); + try + { + for (var index = 0; index <= MetalRenderHost.MaxBufferWordVariantsPerPipeline; index++) + { + // Each a format word of its own; the records decode the same. + DrawInto(rig, pipeline, FirstTarget, buffer, Stage(layout with { Word3 = layout.Word3 + (uint)index }, unread: 0)); + } + + var counters = rig.Host.BufferWordCounters; + Assert.Equal(MetalRenderHost.MaxBufferWordVariantsPerPipeline + 1L, counters.DrawsGeneric); + Assert.Equal(1L, counters.DrawsCapped); + Assert.Equal(MetalRenderHost.MaxBufferWordVariantsPerPipeline, rig.Host.BufferWordVariantsPending); + + gate.Set(); + Assert.True(rig.Host.WaitForBufferWordVariants(BuildTimeout)); + // The layout past the cap stays generic; the others draw their variants. + DrawInto(rig, pipeline, FirstTarget, buffer, Stage(layout with { Word3 = layout.Word3 + 16 }, unread: 0)); + DrawInto(rig, pipeline, FirstTarget, buffer, Stage(layout, unread: 0)); + counters = rig.Host.BufferWordCounters; + Assert.Equal((long)MetalRenderHost.MaxBufferWordVariantsPerPipeline, counters.Built); + Assert.Equal(2L, counters.DrawsCapped); + Assert.Equal(1L, counters.DrawsVariant); + } + finally + { + gate.Set(); + MetalNative.SendVoid(buffer, MetalNative.Selector("release")); + } + } + + private readonly record struct VertexLayout(uint Format, uint Stride, uint Word3Low) + { + public uint Word3 { get; init; } = (Format << 12) | Word3Low; + } + + private static VertexLayout Layout(uint format, uint stride, uint swizzle) => new(format, stride, swizzle); + + // The words at the head of the buffer the generic function reads, then the records. + private static nint NewBuffer(VertexLayout layout) + { + var buffer = MetalNative.SendNewBuffer(Device.Value, MetalNative.Selector("newBufferWithLength:options:"), BufferBytes, 0); + Assert.NotEqual(0, buffer); + var bytes = new Span((void*)MetalNative.Send(buffer, MetalNative.Selector("contents")), BufferBytes); + bytes.Clear(); + var words = MemoryMarshal.Cast(bytes); + words[0] = layout.Stride; + words[1] = layout.Word3; + for (var vertex = 0; vertex < Positions.Length / 2; vertex++) + { + var record = bytes[(RecordOffset + vertex * (int)layout.Stride)..]; + for (var component = 0; component < 2; component++) + { + var value = Positions[vertex * 2 + component]; + if (layout.Format == Snorm16x2) + { + MemoryMarshal.Write(record[(component * 2)..], (short)MathF.Round(value * 32767f)); + } + else + { + MemoryMarshal.Write(record[(component * 4)..], value); + } + } + } + + return buffer; + } + + // The vertex stage's shader data: the two declared words, then one the program never reads. + // A format word written here and not in the buffer's head would make the generic draw differ. + private static MetalRenderHost.MetalStageBindings Stage(VertexLayout layout, uint unread) + { + var stage = MetalPassRig.Stage(); + stage.ShaderData = [layout.Stride, layout.Word3, unread]; + return stage; + } + + private static byte[] DrawInto( + MetalPassRig rig, PipelineHandle pipeline, ulong address, nint buffer, MetalRenderHost.MetalStageBindings stage) + { + // The buffer's head holds the words the stage holds: rewrite them for this draw. + var words = new Span((void*)MetalNative.Send(buffer, MetalNative.Selector("contents")), 2); + words[0] = stage.ShaderData[0]; + words[1] = stage.ShaderData[1]; + var target = rig.MakeTarget(address, GpuFormat.R8G8B8A8Unorm, Width, Height); + rig.Draw(pipeline, [target], bind: host => + { + host.BindVertexBuffers([new BufferBinding((ulong)buffer, 0)], new VertexInputInfo()); + host.NoteBufferWordStages(stage, null); + }); + rig.Host.FlushCommandBuffer(); + return rig.Read(address, TargetBytes); + } + + // Some pixels carry the layout's colour and some do not: the triangles landed where they + // were put, not over the whole target or nowhere. + private static void AssertDrawn(byte[] pixels, VertexLayout layout) + { + var red = (byte)Math.Round((layout.Word3 & 0xF) * 255.0 / 15.0); + var green = (byte)Math.Round(((layout.Word3 >> 4) & 0xF) * 255.0 / 15.0); + var drawn = 0; + for (var at = 0; at < pixels.Length; at += 4) + { + if (pixels[at] == red && pixels[at + 1] == green && pixels[at + 3] == 255) + { + drawn++; + } + } + + Assert.True(drawn > 0 && drawn < pixels.Length / 4, $"drawn={drawn} of {pixels.Length / 4}"); + } + + private static PipelineHandle Pipeline(MetalPassRig rig, ulong id) + { + var host = rig.Host; + var vertex = new ShaderProgram(id, host.CreateShaderModule( + new MetalCompiledGuestShader(new Gen5MslShader(VertexSource, "gen5_vs", Gen5MslStage.Vertex, 1) + { + BufferWordConstants = Declared, + }), + ShaderStage.Vertex, id, id)); + var pixel = new ShaderProgram(id + 1, host.CreateShaderModule( + new MetalCompiledGuestShader(new Gen5MslShader(PixelSource, "gen5_ps", Gen5MslStage.Pixel, 1)), + ShaderStage.Pixel, id + 1, id + 1)); + return host.CreateGraphicsPipeline(Description(vertex, pixel)); + } + + private static GraphicsPipelineDescription Description(ShaderProgram vertex, ShaderProgram pixel) + { + var parameters = new PipelineStaticParameters + { + ColorCount = 1, + Topology = GpuPrimitiveTopology.TriangleList, + Samples = 1, + DepthClipEnable = true, + }; + parameters.SetColorMask(0, 0xF); + var rendering = new PipelineRenderingState { ColorCount = 1 }; + rendering.ColorFormats[0] = GpuFormat.R8G8B8A8Unorm; + return new GraphicsPipelineDescription + { + Rendering = rendering, + VertexInput = new PipelineVertexInputState(), + VertexInfo = new VertexInputInfo(), + VertexProgram = vertex, + VertexStage = new ShaderProgramInfo { Stage = ShaderStageKind.Vertex, Hash = vertex.Id }, + PixelProgram = pixel, + PixelStage = new ShaderProgramInfo { Stage = ShaderStageKind.Pixel, Hash = pixel.Id }, + StaticParameters = parameters, + }; + } + + private bool RequireDevice() + { + if (Environment.GetEnvironmentVariable("SHARPEMU_TEST_REQUIRE_DEVICE") != "1") + { + output.WriteLine("Buffer-word variants are compiled and drawn on the device only behind the exclusive device gate."); + return false; + } + + Assert.True(OperatingSystem.IsMacOS()); + Assert.NotEqual(0, Device.Value); + return true; + } +} diff --git a/tests/SharpEmu.Gpu.Metal.Tests/MetalMipStatisticsFunctionTests.cs b/tests/SharpEmu.Gpu.Metal.Tests/MetalMipStatisticsFunctionTests.cs index e71056b79..268e88046 100644 --- a/tests/SharpEmu.Gpu.Metal.Tests/MetalMipStatisticsFunctionTests.cs +++ b/tests/SharpEmu.Gpu.Metal.Tests/MetalMipStatisticsFunctionTests.cs @@ -40,8 +40,8 @@ public void TheFunctionSpecializesWithTheConstantOnAndOff() nint on = 0; try { - off = MetalRenderHost.NewMipStatisticsFunction(library, "gen5_ps", enabled: false, out var offError); - on = MetalRenderHost.NewMipStatisticsFunction(library, "gen5_ps", enabled: true, out var onError); + off = MetalRenderHost.NewTranslatedFunction(library, "gen5_ps", false, [], [], out var offError); + on = MetalRenderHost.NewTranslatedFunction(library, "gen5_ps", true, [], [], out var onError); Assert.True(off != 0, MetalNative.DescribeError(offError)); Assert.True(on != 0, MetalNative.DescribeError(onError)); Assert.NotEqual(off, on); diff --git a/tests/SharpEmu.Gpu.Metal.Tests/MetalPassRig.cs b/tests/SharpEmu.Gpu.Metal.Tests/MetalPassRig.cs index 542660046..61e19affc 100644 --- a/tests/SharpEmu.Gpu.Metal.Tests/MetalPassRig.cs +++ b/tests/SharpEmu.Gpu.Metal.Tests/MetalPassRig.cs @@ -246,11 +246,15 @@ fragment PixelOut fill_fs(PixelIn in [[stage_in]]) static string F(float value) => value.ToString("F4", CultureInfo.InvariantCulture) + "f"; } - /// One draw of a pipeline into these targets, as an executor records it. - public void Draw(PipelineHandle pipeline, ReadOnlySpan targets, MetalRenderHost.MetalStageBindings? stage = null) + /// One draw of a pipeline into these targets, as an executor records it; + /// binds what else the draw needs (vertex buffers, the stages a variant lookup reads) after the reset. + public void Draw( + PipelineHandle pipeline, ReadOnlySpan targets, MetalRenderHost.MetalStageBindings? stage = null, + Action? bind = null) { var host = Host; host.ResetBindings(); + bind?.Invoke(host); if (stage is { Program.UsesDeviceAddresses: true }) { // Bound as PrepareBindings binds it: each range its program reaches ordered after diff --git a/tools/SharpEmu.Tools.ShaderCompileBench/GpuBench.cs b/tools/SharpEmu.Tools.ShaderCompileBench/GpuBench.cs index 91b3c994d..c7ffed34b 100644 --- a/tools/SharpEmu.Tools.ShaderCompileBench/GpuBench.cs +++ b/tools/SharpEmu.Tools.ShaderCompileBench/GpuBench.cs @@ -442,15 +442,8 @@ private static Built[] CompileItem(Item item, List variants, int worker return; } - nint error = 0; - if (item.Shader.UsesMipStatisticsConstant) - { - built.Function = MetalRenderHost.NewMipStatisticsFunction(built.Library, item.Shader.EntryPoint, false, out error); - } - else - { - built.Function = MetalNative.Send(built.Library, MetalNative.Selector("newFunctionWithName:"), MetalNative.NsString(item.Shader.EntryPoint)); - } + // The generic function, as the runtime makes it (buffer-word constants without values). + built.Function = MetalRenderHost.NewTranslatedFunction(built.Library, item.Shader, mipStatistics: false, out var error); if (built.Function == 0) { diff --git a/tools/SharpEmu.Tools.ShaderCompileBench/Program.cs b/tools/SharpEmu.Tools.ShaderCompileBench/Program.cs index 6b58a3b32..f83e38854 100644 --- a/tools/SharpEmu.Tools.ShaderCompileBench/Program.cs +++ b/tools/SharpEmu.Tools.ShaderCompileBench/Program.cs @@ -391,7 +391,6 @@ private static void Compile(nint device, List rows, bool pipeline) var order = Arg("order", "list") == "bigfirst" ? rows.OrderByDescending(r => r.Source.Length).ToList() : rows; var queue = new ConcurrentQueue(order); var selNewLibrary = MetalNative.Selector("newLibraryWithSource:options:error:"); - var selNewFunction = MetalNative.Selector("newFunctionWithName:"); var selNewPipeline = MetalNative.Selector("newComputePipelineStateWithFunction:error:"); var selRelease = MetalNative.Selector("release"); var started = Stopwatch.GetTimestamp(); @@ -435,7 +434,13 @@ private static void Compile(nint device, List rows, bool pipeline) if (makePipeline) { - function = MetalNative.Send(library, selNewFunction, MetalNative.NsString(row.Entry)); + // A source that declares function constants needs constant values (generic ones here). + var mip = row.Source.Contains( + SharpEmu.ShaderCompiler.Metal.Gen5MslShader.MipStatisticsFunctionConstantName + " [[function_constant(", + StringComparison.Ordinal); + function = MetalRenderHost.NewTranslatedFunction( + library, row.Entry, mip ? false : null, + [.. SharpEmu.ShaderCompiler.Metal.Gen5MslShader.ParseBufferWordConstants(row.Source)], [], out _); var t2 = Stopwatch.GetTimestamp(); row.FunctionMs = (t2 - t1) * TicksToMs; nint pipelineError = 0; From 26a034645270e17b44c13f86e8d0f56b72666ab0 Mon Sep 17 00:00:00 2001 From: kuba Date: Mon, 16 Nov 2026 23:14:53 +0000 Subject: [PATCH 156/178] [Metal] Keep a refused buffer-word variant from ending the process, and compute its switch on use A variant build ran on a plain thread, so a pipeline Metal refused went through GpuFatal's process exit before the catch that keeps the draws generic; the builder now runs its builds as work ahead of need. The switch was a static initialized from a static of another part of the class, whose order is not defined. The corpus replay can translate as the host does (SHARPEMU_CORPUS_PORTABLE=1): all 1,241 recorded Demon's Souls programs translate with the constants on. --- .../V2/MetalRenderHost.BufferWordVariants.cs | 17 ++++++++++++++--- .../MetalBufferWordVariantTests.cs | 9 +++++++++ .../SharpEmu.Tools.ShaderDump/CorpusCommand.cs | 10 ++++++++++ 3 files changed, 33 insertions(+), 3 deletions(-) diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.BufferWordVariants.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.BufferWordVariants.cs index 05da3b9e0..ae9e51072 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.BufferWordVariants.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.BufferWordVariants.cs @@ -39,8 +39,12 @@ internal sealed partial class MetalRenderHost /// (PortableBufferWord.ConstantsEnabled), on with portable buffers unless /// SHARPEMU_METAL_V2_BUFFER_WORD_CONSTANTS=0, which restores today's MSL exactly. /// - internal static readonly bool BufferWordConstants = - PortableBuffers && Environment.GetEnvironmentVariable("SHARPEMU_METAL_V2_BUFFER_WORD_CONSTANTS") != "0"; + internal static bool BufferWordConstants => PortableBuffers && BufferWordConstantsRequested; + + // Read on its own: PortableBuffers is a static of another part of this class, and the order + // the parts' static initializers run in is not defined. + private static readonly bool BufferWordConstantsRequested = + Environment.GetEnvironmentVariable("SHARPEMU_METAL_V2_BUFFER_WORD_CONSTANTS") != "0"; /// The translation switches that decide the MSL, for the stamps of what is stored by them. internal static string TranslationSwitchStamp => @@ -455,7 +459,14 @@ private void RunBufferWordBuilder() { foreach (var (entry, variants, variant) in _bufferWordQueue.GetConsumingEnumerable()) { - BuildBufferWordVariant(entry, variants, variant); + // Ahead of need: a pipeline Metal refuses for a variant must not end the + // process (the generic pipeline draws the same), so a fatal inside the build + // is thrown to BuildBufferWordVariant, which counts the variant as failed. + SharpEmu.Libs.Gpu.Scheduling.GpuFatal.Speculatively(() => + { + BuildBufferWordVariant(entry, variants, variant); + return 0; + }); } } catch (ObjectDisposedException) diff --git a/tests/SharpEmu.Gpu.Metal.Tests/MetalBufferWordVariantTests.cs b/tests/SharpEmu.Gpu.Metal.Tests/MetalBufferWordVariantTests.cs index a66249464..22ab887d8 100644 --- a/tests/SharpEmu.Gpu.Metal.Tests/MetalBufferWordVariantTests.cs +++ b/tests/SharpEmu.Gpu.Metal.Tests/MetalBufferWordVariantTests.cs @@ -120,6 +120,15 @@ fragment float4 gen5_ps(PixelIn in [[stage_in]]) private static readonly Lazy Device = new(MetalNative.MTLCreateSystemDefaultDevice); + // The switch reads a static of another part of MetalRenderHost: computed on use, it cannot + // come out false because the parts' static initializers ran in another order. + [Fact] + public void TheSwitchFollowsPortableBuffersAndItsVariable() => + Assert.Equal( + MetalRenderHost.PortableBuffers && + Environment.GetEnvironmentVariable("SHARPEMU_METAL_V2_BUFFER_WORD_CONSTANTS") != "0", + MetalRenderHost.BufferWordConstants); + [Fact] public void AVariantIsListedUnderAnotherArchiveKeyThanTheGenericPipeline() { diff --git a/tools/SharpEmu.Tools.ShaderDump/CorpusCommand.cs b/tools/SharpEmu.Tools.ShaderDump/CorpusCommand.cs index 11304f0a4..b453c1048 100644 --- a/tools/SharpEmu.Tools.ShaderDump/CorpusCommand.cs +++ b/tools/SharpEmu.Tools.ShaderDump/CorpusCommand.cs @@ -22,6 +22,16 @@ public static int Run(string[] args) return 2; } + // SHARPEMU_CORPUS_PORTABLE=1: translate as the Metal host does by default, with portable + // buffers (each buffer's stride and format word read at run time) and, unless + // SHARPEMU_METAL_V2_BUFFER_WORD_CONSTANTS=0, those words as optional function constants. + if (Environment.GetEnvironmentVariable("SHARPEMU_CORPUS_PORTABLE") == "1") + { + SharpEmu.ShaderCompiler.Resources.PortableBufferWord.Enabled = true; + SharpEmu.ShaderCompiler.Resources.PortableBufferWord.ConstantsEnabled = + Environment.GetEnvironmentVariable("SHARPEMU_METAL_V2_BUFFER_WORD_CONSTANTS") != "0"; + } + var files = Directory.EnumerateFiles(directories[0], "*" + ShaderCorpus.FileExtension).Order(StringComparer.Ordinal).ToArray(); var failures = new List(); var succeeded = 0; From 49d1daa455328d915b38c9909088db95d615c595 Mon Sep 17 00:00:00 2001 From: kuba Date: Mon, 16 Nov 2026 23:33:42 +0000 Subject: [PATCH 157/178] [Metal] Dispatch through compute pipelines specialized for each dispatch's buffer words A compute pipeline whose program declares buffer-word constants keeps up to 16 variants in the same worker-only table render pipelines use. CommitBindings(Compute) notes the committed stage and the entry it was committed for; BindPipeline(Compute) chooses once per dispatch (ComputeStateOf: the variant once built, else the generic state, the reason counted, a stage committed for another entry counted unreadable); EnsureComputePipelineState binds that choice on every path that binds the program's state (direct, indirect, thread-unit indirect, tessellation hull dispatches). Variants build on the same two background builders at prewarm priority under GpuFatal.Speculatively; BuildComputePipelineState(variant: true) holds no runtime slot and never takes the empty-kernel stand-in (the generic state runs instead). A compute variant is stored as its own archive library file (ComputeBufferWordArchiveKey). Counters per kind; the PERF line adds buffer_words_compute=[...] with generic_off. SHARPEMU_METAL_V2_BUFFER_WORD_COMPUTE=0 keeps dispatches generic (no source change). A library Metal loads from an archive library file (every warm start) holds the function with its constants already resolved: a function specialized from it ignores the values, so render variants built on a warm start ran the generic code. Specialized functions now come from the module's MSL compiled again without the archive, once per module on the builder (RetainSpecializableLibrary), or for a compute variant a past session stored, from that variant's own file. --- docs/macos/configuration.md | 3 +- .../V2/MetalRenderHost.BufferWordVariants.cs | 372 ++++++++++++++---- .../V2/MetalRenderHost.CompilerRecovery.cs | 9 +- .../V2/MetalRenderHost.Descriptors.cs | 9 +- .../V2/MetalRenderHost.Pipelines.cs | 18 +- .../V2/MetalRenderHost.Rendering.cs | 19 +- .../SharpEmu.Gpu.Metal/V2/MetalRenderHost.cs | 1 + 7 files changed, 346 insertions(+), 85 deletions(-) diff --git a/docs/macos/configuration.md b/docs/macos/configuration.md index 99c337141..2f2f95557 100644 --- a/docs/macos/configuration.md +++ b/docs/macos/configuration.md @@ -106,7 +106,8 @@ undoes an optimization to isolate a miscompile: | `SHARPEMU_MSL_PERSISTENT_RECORDS` | on | Accesses multi-dword records of persistent-thread kernels dword by dword. | | `SHARPEMU_MSL_BYTEBIAS` | off | `1` keeps the per-buffer byte bias. | | `SHARPEMU_MSL_FUSE_MAD` | on | Emits the guest's legacy multiply-adds (`V_MAD_F32`, `V_MAC_F32`) as one fused operation in compute programs and pixel programs without depth export. Faster (about 5 ms of an 82 ms Demon's Souls frame) but not bit-exact for MAD/MAC: the guest rounds the product first. `0` restores the exact two-op form. | -| `SHARPEMU_METAL_V2_BUFFER_WORD_CONSTANTS` | on | With portable buffers (`SHARPEMU_METAL_V2_PORTABLE_BUFFERS`, on), each buffer stride and format word a program reads at run time is also a Metal function constant. A draw draws through its pipeline as before and, once a background compile has made it, through a variant whose functions have the draw's words folded in (same pixels, faster vertex stage). Up to 16 variants a pipeline; mesh, rectangle-list and tessellation pipelines and compute programs stay generic. The periodic counter line reports `buffer_words=[...]`. `0` restores the previous MSL exactly. | +| `SHARPEMU_METAL_V2_BUFFER_WORD_CONSTANTS` | on | With portable buffers (`SHARPEMU_METAL_V2_PORTABLE_BUFFERS`, on), each buffer stride and format word a program reads at run time is also a Metal function constant. A draw draws through its pipeline as before and, once a background compile has made it, through a variant whose functions have the draw's words folded in (same pixels, faster vertex stage). Up to 16 variants a pipeline; mesh, rectangle-list and tessellation pipelines stay generic. The periodic counter line reports `buffer_words=[...]`. `0` restores the previous MSL exactly. | +| `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. | ## Diagnostics diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.BufferWordVariants.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.BufferWordVariants.cs index ae9e51072..b633b969c 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.BufferWordVariants.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.BufferWordVariants.cs @@ -31,6 +31,15 @@ namespace SharpEmu.Gpu.Metal.V2; /// draw stays on the generic pipeline and is counted. Mesh, rectangle-list and tessellation /// pipelines stay generic, and so does the pixel stage of a pipeline with remapped colour /// outputs. SHARPEMU_METAL_V2_BUFFER_WORD_CONSTANTS=0 turns the constants off in translation. +/// +/// A compute pipeline does the same for its one program (Demon's Souls: 579 of 636 compute +/// programs declare buffer words): CommitBindings(Compute) notes the stage and the entry it +/// was committed for, BindPipeline(Compute) chooses the state from that stage's shader data +/// once per dispatch, and every path that then binds the program's state (direct, indirect, +/// thread-unit indirect) binds the chosen one through EnsureComputePipelineState. Its own +/// counters go on the PERF line as buffer_words_compute=[...]. +/// SHARPEMU_METAL_V2_BUFFER_WORD_COMPUTE=0 keeps compute pipelines generic (the source is the +/// same either way). /// internal sealed partial class MetalRenderHost { @@ -46,6 +55,19 @@ internal sealed partial class MetalRenderHost private static readonly bool BufferWordConstantsRequested = Environment.GetEnvironmentVariable("SHARPEMU_METAL_V2_BUFFER_WORD_CONSTANTS") != "0"; + /// + /// Compute pipelines take variants too, unless SHARPEMU_METAL_V2_BUFFER_WORD_COMPUTE=0 (or + /// the constants are off): then every dispatch runs the generic pipeline, while render + /// pipelines keep theirs. It changes no translated source, only which state a dispatch binds. + /// + internal static bool BufferWordComputeVariants => BufferWordConstants && BufferWordComputeRequested; + + private static readonly bool BufferWordComputeRequested = + Environment.GetEnvironmentVariable("SHARPEMU_METAL_V2_BUFFER_WORD_COMPUTE") != "0"; + + /// Whether this host's dispatches take compute variants; tests turn it off. + internal bool ComputeBufferWordVariants { get; set; } = BufferWordComputeVariants; + /// The translation switches that decide the MSL, for the stamps of what is stored by them. internal static string TranslationSwitchStamp => $"portable={(PortableBuffers ? 1 : 0)},buffer_word_constants={(BufferWordConstants ? 1 : 0)}"; @@ -160,9 +182,21 @@ internal static nint NewTranslatedFunction(nint library, Gen5MslShader shader, b internal static UInt128 BufferWordArchiveKey(UInt128 pixelPairKey, UInt128 values) => values == default ? pixelPairKey : pixelPairKey ^ values ^ new UInt128(0x4255464645525F57UL, 0x4F5244535F564152UL); + /// + /// The archive key a compute variant's library file (library and pipeline binary, + /// MetalBinaryArchive.CaptureCompute) is stored under: the module's library key mixed with + /// the variant's values, apart from the generic pipeline's file and from every other + /// variant's. None (zero) when the module has no key: the values alone would name the + /// same file for every program. + /// + internal static UInt128 ComputeBufferWordArchiveKey(UInt128 libraryKey, UInt128 values) => + libraryKey == default || values == default + ? libraryKey + : libraryKey ^ values ^ new UInt128(0x434F4D505554455FUL, 0x42575F5641524941UL); + // The constants of a pipeline's programs, its variants, and a scratch row for the values a // draw holds. On the GPU worker but for the builder's reads of Vertex, Pixel and a - // variant it was handed. + // variant it was handed. A compute pipeline's program is its Vertex; its Pixel is empty. private sealed class BufferWordVariants(Gen5MslShader.BufferWordConstant[] vertex, Gen5MslShader.BufferWordConstant[] pixel) { public readonly Gen5MslShader.BufferWordConstant[] Vertex = vertex; @@ -216,36 +250,62 @@ public override int GetHashCode() private MetalStageBindings? _bufferWordVertexStage; private MetalStageBindings? _bufferWordPixelStage; + // The compute stage CommitBindings(Compute) committed and the entry it committed it for, + // whose shader data BindPipeline(Compute) chooses the dispatch's state from; and that + // choice (zero: the generic state), which EnsureComputePipelineState binds for + // _pendingComputePipeline. On the GPU worker. + private MetalStageBindings? _bufferWordComputeStage; + private MetalPipelineEntry? _bufferWordComputeEntry; + private nint _pendingComputeState; + private readonly BlockingCollection<(MetalPipelineEntry Entry, BufferWordVariants Variants, BufferWordVariant Variant)> _bufferWordQueue = new(); private MetalCompileThread[]? _bufferWordBuilders; private volatile bool _bufferWordStopping; - private int _bufferWordPending; - - // Worker-only draw counters for programs that declare buffer words, taken by the PERF line. - private long _bufferWordDrawsVariant; - private long _bufferWordDrawsGeneric; - private long _bufferWordDrawsPending; - private long _bufferWordDrawsCapped; - private long _bufferWordDrawsGenericKind; - private long _bufferWordDrawsUnreadable; - private long _bufferWordDrawsFailed; - - // Builder counters. - private long _bufferWordVariantsBuilt; - private long _bufferWordVariantsFailed; - private long _bufferWordVariantsCapped; + + // The counters of one pipeline kind: the builder's (Interlocked), and the worker's per draw + // or dispatch of a program that declares buffer words, taken by the PERF line. + private sealed class BufferWordTally + { + public int Pending; + public long Built; + public long Failed; + public long Capped; + public long Variant; + public long Generic; + public long GenericPending; + public long GenericCapped; + public long GenericKind; + public long GenericUnreadable; + public long GenericFailed; + public long GenericOff; + } + + private readonly BufferWordTally _bufferWordRender = new(); + private readonly BufferWordTally _bufferWordCompute = new(); + + private BufferWordTally TallyOf(MetalPipelineEntry entry) => entry.Graphics ? _bufferWordRender : _bufferWordCompute; /// Runs on the builder before it compiles a variant; tests hold it. internal Action? BeforeBufferWordVariantBuild { get; set; } - /// Variants queued or compiling. - internal int BufferWordVariantsPending => Volatile.Read(ref _bufferWordPending); + /// Variants queued or compiling, render and compute. + internal int BufferWordVariantsPending => + Volatile.Read(ref _bufferWordRender.Pending) + Volatile.Read(ref _bufferWordCompute.Pending); - /// The variant counters since the host started, for tests. + /// The render variant counters since the host started, for tests. internal (long Built, long Failed, long Capped, long DrawsVariant, long DrawsGeneric, long DrawsPending, long DrawsCapped) BufferWordCounters => - (Interlocked.Read(ref _bufferWordVariantsBuilt), Interlocked.Read(ref _bufferWordVariantsFailed), - Interlocked.Read(ref _bufferWordVariantsCapped), _bufferWordDrawsVariant, _bufferWordDrawsGeneric, - _bufferWordDrawsPending, _bufferWordDrawsCapped); + CountersOf(_bufferWordRender); + + /// The compute variant counters since the host started (dispatches for draws), for tests. + internal (long Built, long Failed, long Capped, long DrawsVariant, long DrawsGeneric, long DrawsPending, long DrawsCapped) BufferWordComputeCounters => + CountersOf(_bufferWordCompute); + + /// Compute dispatches of declaring programs that ran generic because the compute switch was off, for tests. + internal long BufferWordComputeDispatchesOff => _bufferWordCompute.GenericOff; + + private static (long, long, long, long, long, long, long) CountersOf(BufferWordTally tally) => + (Interlocked.Read(ref tally.Built), Interlocked.Read(ref tally.Failed), Interlocked.Read(ref tally.Capped), + tally.Variant, tally.Generic, tally.GenericPending, tally.GenericCapped); /// Waits until no variant is queued or compiling, for tests. internal bool WaitForBufferWordVariants(TimeSpan timeout) @@ -292,6 +352,17 @@ private void NoteBufferWordStages(ReadOnlySpan stages) NoteBufferWordStages(vertex, pixel); } + /// The compute stage CommitBindings(Compute) committed for ; ResetBindings clears it. + private void NoteBufferWordComputeStage(MetalPipelineEntry? entry, ReadOnlySpan stages) + { + _bufferWordComputeEntry = entry; + _bufferWordComputeStage = stages.Length == 1 ? (MetalStageBindings)stages[0] : null; + } + + // The variants of a new compute pipeline entry: null when its program declares no buffer words. + private static BufferWordVariants? ComputeBufferWordVariantsFor(MetalShaderModule module) => + module.Shader.BufferWordConstants.Count == 0 ? null : new BufferWordVariants([.. module.Shader.BufferWordConstants], []); + // The variants of a new pipeline entry: null when neither program declares buffer words, // or when its kind stays generic (mesh, rectangle list, tessellation). private static BufferWordVariants? BufferWordVariantsFor( @@ -331,20 +402,71 @@ private nint GraphicsStateOf(MetalPipelineEntry entry) return entry.State; } + var tally = _bufferWordRender; if (entry.BufferWordVariants is not { } variants) { - _bufferWordDrawsGenericKind++; - _bufferWordDrawsGeneric++; + tally.GenericKind++; + tally.Generic++; return entry.State; } + var state = VariantStateOf(entry, variants, _bufferWordVertexStage, _bufferWordPixelStage, tally); + return state != 0 ? state : entry.State; + } + + /// + /// The variant state a dispatch of the compute binds, chosen from + /// the shader data of the stage CommitBindings(Compute) committed for that same entry, or + /// zero for the generic state, with the reason counted. On the GPU worker, once per + /// dispatch (BindPipeline). + /// + private nint ComputeStateOf(MetalPipelineEntry entry) + { + if (!entry.DeclaresBufferWords) + { + return 0; + } + + var tally = _bufferWordCompute; + if (!ComputeBufferWordVariants) + { + tally.GenericOff++; + tally.Generic++; + return 0; + } + + if (entry.BufferWordVariants is not { } variants) + { + tally.GenericKind++; + tally.Generic++; + return 0; + } + + if (!ReferenceEquals(_bufferWordComputeEntry, entry)) + { + // The committed stage is not this pipeline's (or none was): its words are not this dispatch's. + tally.GenericUnreadable++; + tally.Generic++; + return 0; + } + + return VariantStateOf(entry, variants, _bufferWordComputeStage, null, tally); + } + + // The ready variant for the words the stages hold, or zero with the reason the generic + // state is used counted: a hash of the declared words and a probe of a small + // open-addressed table; a new layout allocates its variant and queues its build. + private nint VariantStateOf( + MetalPipelineEntry entry, BufferWordVariants variants, MetalStageBindings? first, MetalStageBindings? second, + BufferWordTally tally) + { var values = variants.Scratch; - if (!TryReadBufferWords(_bufferWordVertexStage, variants.Vertex, values.AsSpan(0, variants.Vertex.Length)) || - !TryReadBufferWords(_bufferWordPixelStage, variants.Pixel, values.AsSpan(variants.Vertex.Length))) + if (!TryReadBufferWords(first, variants.Vertex, values.AsSpan(0, variants.Vertex.Length)) || + !TryReadBufferWords(second, variants.Pixel, values.AsSpan(variants.Vertex.Length))) { - _bufferWordDrawsUnreadable++; - _bufferWordDrawsGeneric++; - return entry.State; + tally.GenericUnreadable++; + tally.Generic++; + return 0; } var hash = XxHash3.HashToUInt64(MemoryMarshal.AsBytes(values.AsSpan())); @@ -357,44 +479,45 @@ private nint GraphicsStateOf(MetalPipelineEntry entry) switch (Volatile.Read(ref candidate.Status)) { case BufferWordVariantReady: - _bufferWordDrawsVariant++; + tally.Variant++; return candidate.State; case BufferWordVariantPending: - _bufferWordDrawsPending++; + tally.GenericPending++; break; case BufferWordVariantCapped: - _bufferWordDrawsCapped++; + tally.GenericCapped++; break; default: - _bufferWordDrawsFailed++; + tally.GenericFailed++; break; } - _bufferWordDrawsGeneric++; - return entry.State; + tally.Generic++; + return 0; } slot = (slot + 1) & (BufferWordVariantSlots - 1); } - _bufferWordDrawsGeneric++; + tally.Generic++; if (variants.Count >= MaxBufferWordVariantsPerPipeline) { - _bufferWordDrawsCapped++; + tally.GenericCapped++; MetalV2Diagnostics.WarnOnce( - "buffer-word-variant-cap", - $"A pipeline drew more buffer-word layouts than it keeps variants for; the rest draw generic: " + - $"pipeline={entry.Id} vertex=0x{entry.VertexHash:X16} variants={variants.Count}."); - return entry.State; + entry.Graphics ? "buffer-word-variant-cap" : "buffer-word-compute-variant-cap", + $"A pipeline {(entry.Graphics ? "drew" : "dispatched")} more buffer-word layouts than it keeps variants for; " + + $"the rest run generic: pipeline={entry.Id} {(entry.Graphics ? "vertex" : "compute")}=0x{entry.VertexHash:X16} " + + $"variants={variants.Count}."); + return 0; } var copy = values.ToArray(); var variant = new BufferWordVariant(copy, hash, VariantArchiveKey(copy, variants.Vertex.Length)); table[slot] = variant; variants.Count++; - _bufferWordDrawsPending++; + tally.GenericPending++; QueueBufferWordVariant(entry, variants, variant); - return entry.State; + return 0; } // The words a stage's shader data holds at the dwords its program declares constants for. @@ -445,11 +568,12 @@ private void QueueBufferWordVariant(MetalPipelineEntry entry, BufferWordVariants } } - Interlocked.Increment(ref _bufferWordPending); + var tally = TallyOf(entry); + Interlocked.Increment(ref tally.Pending); if (_bufferWordStopping || !_bufferWordQueue.TryAdd((entry, variants, variant))) { Interlocked.CompareExchange(ref variant.Status, BufferWordVariantFailed, BufferWordVariantPending); - Interlocked.Decrement(ref _bufferWordPending); + Interlocked.Decrement(ref tally.Pending); } } @@ -497,15 +621,38 @@ private void BuildBufferWordVariant(MetalPipelineEntry entry, BufferWordVariants return; } + // Made from now on: the bound keeps a module it made a pipeline from in the last + // seconds (TrimModules), as it does for the compiler threads' builds. + var now = System.Diagnostics.Stopwatch.GetTimestamp(); + if (!entry.Graphics) + { + var compute = entry.ComputeDescription ?? + throw new InvalidOperationException($"A compute buffer-word variant has no description: pipeline={entry.Id}."); + var module = RequireModule(compute.Program, onWorker: false); + module.LastUsedTicks = now; + // Made as the module's own function is: with the LOD statistics switch off. + var computeMip = module.Shader.UsesMipStatisticsConstant ? false : (bool?)null; + // Its own library file in the archive (library and pipeline binary), made from + // it again when a past session stored it. + var archiveKey = ComputeBufferWordArchiveKey(module.ArchiveKey, variant.ArchiveKey); + if ((vertexFunction = RetainSpecializedFunction(module, computeMip, variants.Vertex, variant.Values, archiveKey)) == 0) + { + status = BufferWordVariantCapped; + return; + } + + // No empty-kernel stand-in when the compiler fails: the generic state runs instead. + state = BuildComputePipelineState(vertexFunction, compute.Stage.Hash, archiveKey, variant: true); + status = BufferWordVariantReady; + return; + } + var description = entry.GraphicsDescription ?? throw new InvalidOperationException($"A buffer-word variant has no description: pipeline={entry.Id}."); var vertexModule = RequireModule(description.VertexProgram, onWorker: false); var pixelModule = description.PixelStage is not null && description.PixelProgram.IsValid ? RequireModule(description.PixelProgram, onWorker: false) : null; - // Made from now on: the bound keeps a module it made a pipeline from in the last - // seconds (TrimModules), as it does for the compiler threads' builds. - var now = System.Diagnostics.Stopwatch.GetTimestamp(); vertexModule.LastUsedTicks = now; if (pixelModule is not null) { @@ -546,8 +693,9 @@ private void BuildBufferWordVariant(MetalPipelineEntry entry, BufferWordVariants } Console.Error.WriteLine( - $"[METAL-V2][WARN] A buffer-word variant could not be built; its draws stay generic: " + - $"pipeline={entry.Id} vertex=0x{entry.VertexHash:X16} {exception.Message}"); + $"[METAL-V2][WARN] A buffer-word variant could not be built; its " + + $"{(entry.Graphics ? "draws" : "dispatches")} stay generic: pipeline={entry.Id} " + + $"{(entry.Graphics ? "vertex" : "compute")}=0x{entry.VertexHash:X16} {exception.Message}"); } finally { @@ -559,12 +707,13 @@ private void BuildBufferWordVariant(MetalPipelineEntry entry, BufferWordVariants } } - PublishBufferWordVariant(variant, status, state); - Interlocked.Decrement(ref _bufferWordPending); + var tally = TallyOf(entry); + PublishBufferWordVariant(variant, status, state, tally); + Interlocked.Decrement(ref tally.Pending); } } - private void PublishBufferWordVariant(BufferWordVariant variant, int status, nint state) + private void PublishBufferWordVariant(BufferWordVariant variant, int status, nint state, BufferWordTally tally) { if (status == BufferWordVariantReady) { @@ -587,15 +736,15 @@ private void PublishBufferWordVariant(BufferWordVariant variant, int status, nin if (status == BufferWordVariantReady) { - Interlocked.Increment(ref _bufferWordVariantsBuilt); + Interlocked.Increment(ref tally.Built); } else if (status == BufferWordVariantCapped) { - Interlocked.Increment(ref _bufferWordVariantsCapped); + Interlocked.Increment(ref tally.Capped); } else { - Interlocked.Increment(ref _bufferWordVariantsFailed); + Interlocked.Increment(ref tally.Failed); } } @@ -607,10 +756,10 @@ private void PublishBufferWordVariant(BufferWordVariant variant, int status, nin /// module, and must not wait for a specialization meanwhile. /// private nint RetainSpecializedFunction( - MetalShaderModule module, bool? mipStatistics, Gen5MslShader.BufferWordConstant[] declared, uint[] values) + MetalShaderModule module, bool? mipStatistics, Gen5MslShader.BufferWordConstant[] declared, uint[] values, + UInt128 storedVariant = default) { var key = new SpecializationKey(mipStatistics, values); - nint library; lock (module) { RequireResidentModule(module); @@ -624,9 +773,18 @@ private nint RetainSpecializedFunction( { return 0; } + } - library = module.Library; - MetalNative.Send(library, SelBufferWordRetain); + // A compute variant a past session stored (storedVariant): its file's library is the + // function as specialized with these values, and its pipeline binary is in the same + // file, so neither the front end nor the back end runs. Otherwise a library that still + // has the constants. + var library = storedVariant != default && MetalBinaryArchive.For(_device) is { } archive && archive.IsStored(storedVariant) + ? archive.TryLoadLibrary(storedVariant) + : 0; + if (library == 0) + { + library = RetainSpecializableLibrary(module); } nint function; @@ -648,7 +806,7 @@ private nint RetainSpecializedFunction( lock (module) { - if (module.Library != library || module.Function == 0) + if (module.Library == 0 || module.Function == 0) { MetalNative.SendVoid(function, SelRelease); throw new InvalidOperationException( @@ -680,9 +838,67 @@ static void RequireResidentModule(MetalShaderModule module) } } + /// + /// A library of whose functions can still be specialized, + /// retained for the caller. The module's own library is not one when it came from the + /// title's archive (TryCompileLibrary asks the archive first, so on every start after the + /// first): a library file holds the AIR of the function the pipeline that stored it was + /// made with, its constants already resolved, and a function made from it with buffer + /// words reads the shader data as the generic one does (measured: the values are ignored). + /// So the module's MSL is compiled once more, without asking the archive, on the variant + /// builder, and kept with the module. + /// + private nint RetainSpecializableLibrary(MetalShaderModule module) + { + lock (module) + { + if (module.SpecializationLibrary != 0) + { + MetalNative.Send(module.SpecializationLibrary, SelBufferWordRetain); + return module.SpecializationLibrary; + } + } + + var shader = module.Compiled.AcquireShader(); + var library = TryCompileLibrary(_device, shader.Source, shader.UsesPerVertexInputs, out var error, out _, askArchive: false); + if (library == 0) + { + throw new InvalidOperationException( + $"The module's library could not be compiled for specialization: hash=0x{module.Hash:X16} {error}"); + } + + lock (module) + { + if (module.Library == 0 || module.Function == 0) + { + MetalNative.SendVoid(library, SelRelease); + throw new InvalidOperationException($"The module's library was released while it was specialized: hash=0x{module.Hash:X16}."); + } + + if (module.SpecializationLibrary != 0) + { + // Another builder made it first. + MetalNative.SendVoid(library, SelRelease); + } + else + { + module.SpecializationLibrary = library; + } + + MetalNative.Send(module.SpecializationLibrary, SelBufferWordRetain); + return module.SpecializationLibrary; + } + } + // Under the module's lock. private static void ReleaseSpecializedFunctions(MetalShaderModule module) { + if (module.SpecializationLibrary != 0) + { + MetalNative.SendVoid(module.SpecializationLibrary, SelRelease); + module.SpecializationLibrary = 0; + } + if (module.SpecializedFunctions is not { } functions) { return; @@ -705,6 +921,12 @@ private void ReleaseBufferWordVariants(MetalPipelineEntry entry) return; } + if (ReferenceEquals(entry, _pendingComputePipeline)) + { + // The bound dispatch's choice goes with them: it runs the generic state, made again. + _pendingComputeState = 0; + } + var table = variants.Table; for (var index = 0; index < table.Length; index++) { @@ -744,15 +966,23 @@ private void StopBufferWordBuilders() // or failed; then draws of programs that declare buffer words on a variant, on the generic // pipeline, and of those why: variant not ready, a pipeline's cap, a kind that stays // generic, words not readable, or a variant that failed or was capped. - private string FormatBufferWordCounters() => + private string FormatBufferWordCounters() => FormatBufferWordCounters(_bufferWordRender, "draws"); + + // The same for compute pipelines, per dispatch, and the dispatches the compute switch + // (SHARPEMU_METAL_V2_BUFFER_WORD_COMPUTE=0) kept generic. + private string FormatBufferWordComputeCounters() => + FormatBufferWordCounters(_bufferWordCompute, "dispatches") + + string.Create(CultureInfo.InvariantCulture, $" generic_off={Interlocked.Exchange(ref _bufferWordCompute.GenericOff, 0)}"); + + private static string FormatBufferWordCounters(BufferWordTally tally, string work) => string.Create(CultureInfo.InvariantCulture, - $"built={Interlocked.Read(ref _bufferWordVariantsBuilt)} pending={BufferWordVariantsPending} " + - $"capped={Interlocked.Read(ref _bufferWordVariantsCapped)} failed={Interlocked.Read(ref _bufferWordVariantsFailed)} " + - $"draws_variant={Interlocked.Exchange(ref _bufferWordDrawsVariant, 0)} " + - $"draws_generic={Interlocked.Exchange(ref _bufferWordDrawsGeneric, 0)} " + - $"generic_pending={Interlocked.Exchange(ref _bufferWordDrawsPending, 0)} " + - $"generic_capped={Interlocked.Exchange(ref _bufferWordDrawsCapped, 0)} " + - $"generic_kind={Interlocked.Exchange(ref _bufferWordDrawsGenericKind, 0)} " + - $"generic_unreadable={Interlocked.Exchange(ref _bufferWordDrawsUnreadable, 0)} " + - $"generic_failed={Interlocked.Exchange(ref _bufferWordDrawsFailed, 0)}"); + $"built={Interlocked.Read(ref tally.Built)} pending={Volatile.Read(ref tally.Pending)} " + + $"capped={Interlocked.Read(ref tally.Capped)} failed={Interlocked.Read(ref tally.Failed)} " + + $"{work}_variant={Interlocked.Exchange(ref tally.Variant, 0)} " + + $"{work}_generic={Interlocked.Exchange(ref tally.Generic, 0)} " + + $"generic_pending={Interlocked.Exchange(ref tally.GenericPending, 0)} " + + $"generic_capped={Interlocked.Exchange(ref tally.GenericCapped, 0)} " + + $"generic_kind={Interlocked.Exchange(ref tally.GenericKind, 0)} " + + $"generic_unreadable={Interlocked.Exchange(ref tally.GenericUnreadable, 0)} " + + $"generic_failed={Interlocked.Exchange(ref tally.GenericFailed, 0)}"); } diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.CompilerRecovery.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.CompilerRecovery.cs index d796c1452..75c15c98b 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.CompilerRecovery.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.CompilerRecovery.cs @@ -70,9 +70,11 @@ private static nint RetryAfterCompilerServiceFailure(Func<(nint State, nint Erro /// /// What a failed compute build turns into: the same build tried again while the compiler /// service keeps going away, then an empty kernel. Returns 0 when the failure is a different - /// kind, or when SHARPEMU_METAL_V2_COMPILER_FAILURE_FATAL=1 is set after the retries. + /// kind, or when SHARPEMU_METAL_V2_COMPILER_FAILURE_FATAL=1 is set after the retries, + /// or without (a buffer-word variant, whose generic pipeline + /// computes the same) after the retries. /// - private nint RecoverComputePipelineState(nint function, UInt128 archiveKey, ulong hash, ref nint error) + private nint RecoverComputePipelineState(nint function, UInt128 archiveKey, ulong hash, ref nint error, bool emptyKernel = true) { var what = $"compute pipeline 0x{hash:X16}"; var state = RetryAfterCompilerServiceFailure( @@ -84,7 +86,8 @@ private nint RecoverComputePipelineState(nint function, UInt128 archiveKey, ulon }, what, ref error); - if (state != 0 || CompilerFailureFatal || error == 0 || !IsCompilerServiceFailure(MetalNative.DescribeError(error))) + if (state != 0 || !emptyKernel || CompilerFailureFatal || error == 0 || + !IsCompilerServiceFailure(MetalNative.DescribeError(error))) { return state; } diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Descriptors.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Descriptors.cs index 0c8a15a81..07f89eb48 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Descriptors.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Descriptors.cs @@ -270,7 +270,9 @@ public void ResetBindings() DisarmPendingCopy(); _pendingGraphicsPipeline = null; _pendingComputePipeline = null; + _pendingComputeState = 0; NoteBufferWordStages(null, null); + NoteBufferWordComputeStage(null, []); _vertexBufferCount = 0; _indexBuffer = 0; _acquisitionSequence++; @@ -1586,12 +1588,17 @@ private static string DescribeDwords(ReadOnlySpan bytes) public void CommitBindings(GpuBindPoint bindPoint, in PipelineHandle pipeline, ReadOnlySpan stages) { - _ = RequirePipelineEntry(in pipeline); + var committed = RequirePipelineEntry(in pipeline); if (bindPoint == GpuBindPoint.Graphics) { NoteJoinStages(stages); NoteBufferWordStages(stages); } + else + { + // The stage whose words BindPipeline(Compute) chooses this dispatch's state by. + NoteBufferWordComputeStage(committed, stages); + } Span pushData = stackalloc uint[(int)PushData.DwordCount]; pushData.Clear(); diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Pipelines.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Pipelines.cs index c4cb0127b..664e25ff7 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Pipelines.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Pipelines.cs @@ -132,6 +132,11 @@ private sealed class MetalShaderModule // variant builder the first time a variant needs them (RetainSpecializedFunction). public Dictionary? SpecializedFunctions; + // The library those functions are made from: the module's MSL compiled again without + // asking the archive, whose library holds the function with its constants already + // resolved (RetainSpecializableLibrary). Made with the first variant that needs it. + public nint SpecializationLibrary; + // The binary archive keys of the library and of the rectangle-list library (zero // with no archive): the pipeline made from them stores them under these. public UInt128 ArchiveKey; @@ -1562,16 +1567,18 @@ public bool TryCreateComputePipeline(ComputePipelineDescription description, out private static bool _prefetchingPipeline; // Runs on the compile pool: MTLDevice is thread safe, and nothing here touches - // the host's own state. - private nint BuildComputePipelineState(nint function, ulong hash, UInt128 archiveKey) + // the host's own state. A buffer-word variant (variant) compiles at prewarm priority, as + // its builder holds a prewarm slot, and is never stood in for by the empty kernel: it + // fails instead, and its dispatches keep the generic state, which computes the same. + private nint BuildComputePipelineState(nint function, ulong hash, UInt128 archiveKey, bool variant = false) { nint error = 0; - using var runtime = MetalCompileScheduler.Shared.Runtime(); + using var runtime = variant ? default : MetalCompileScheduler.Shared.Runtime(); var started = System.Diagnostics.Stopwatch.GetTimestamp(); var state = NewComputePipelineState(function, archiveKey, ref error); if (state == 0) { - state = RecoverComputePipelineState(function, archiveKey, hash, ref error); + state = RecoverComputePipelineState(function, archiveKey, hash, ref error, emptyKernel: !variant); } Interlocked.Add(ref _pipelineTicks, System.Diagnostics.Stopwatch.GetTimestamp() - started); @@ -1706,6 +1713,9 @@ private PipelineHandle RegisterComputePipeline( VertexHash = module.Hash, ComputeDescription = description, LastUsedTicks = System.Diagnostics.Stopwatch.GetTimestamp(), + // Dispatches bind the variant made for their buffer words (MetalRenderHost.BufferWordVariants). + DeclaresBufferWords = module.Shader.BufferWordConstants.Count != 0, + BufferWordVariants = ComputeBufferWordVariantsFor(module), }; _pipelineEntries[entry.Id] = entry; Interlocked.Increment(ref _residentPipelines); diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Rendering.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Rendering.cs index b29632d04..a3de2eea6 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Rendering.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Rendering.cs @@ -1547,14 +1547,19 @@ private nint EnsureComputeEncoder(bool materializeClears) return _computeEncoder; } - // An encoder opened again after the pipeline was bound has no pipeline state. + // An encoder opened again after the pipeline was bound has no pipeline state. The bound + // dispatch's pipeline binds the state BindPipeline chose for its buffer words (the + // variant, once built; MetalRenderHost.BufferWordVariants), any other its generic state. private void EnsureComputePipelineState(nint encoder, MetalPipelineEntry entry) { UsePipelineState(entry); - if (_boundComputePipeline != entry.State) + var state = _pendingComputeState != 0 && ReferenceEquals(entry, _pendingComputePipeline) + ? _pendingComputeState + : entry.State; + if (_boundComputePipeline != state) { - MetalNative.SendVoid(encoder, SelSetComputePipelineState, entry.State); - _boundComputePipeline = entry.State; + MetalNative.SendVoid(encoder, SelSetComputePipelineState, state); + _boundComputePipeline = state; SignpostPipeline(encoder, entry); } } @@ -1613,8 +1618,12 @@ public void BindPipeline(GpuBindPoint bindPoint, in PipelineHandle pipeline) return; } - EnsureComputePipelineState(EnsureComputeEncoder(), entry); + var encoder = EnsureComputeEncoder(); + // Once per dispatch: the variant made for the words the committed stage holds, once + // built, else the generic state (zero), with the reason counted. _pendingComputePipeline = entry; + _pendingComputeState = ComputeStateOf(entry); + EnsureComputePipelineState(encoder, entry); } private MetalPipelineEntry? _pendingComputePipeline; diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.cs index 5f8f0ec6e..a6edfba87 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.cs @@ -2899,6 +2899,7 @@ public void ReportCounters() $"leave_out=[{FormatLeaveOutCounters()}] " + // Pipelines specialized for a draw's buffer words, and the draws on them (FormatBufferWordCounters). $"buffer_words=[{FormatBufferWordCounters()}] " + + $"buffer_words_compute=[{FormatBufferWordComputeCounters()}] " + $"pipeline_waits_blocking={Interlocked.Exchange(ref _pipelineWaitsBlocking, 0)} " + $"async_compiles_inflight={PipelinesCompiling} " + // Read-aheads of the dispatches after one waiting on its pipeline, the dispatches From dca16b29fe7c63964c39ec63b6e000ef9eb3a902 Mon Sep 17 00:00:00 2001 From: kuba Date: Mon, 16 Nov 2026 23:33:42 +0000 Subject: [PATCH 158/178] [Tests] Compute buffer-word variants through the scene path, and what archive libraries do with constants --- .../MetalArchiveSpecializationTests.cs | 127 ++++++++ .../ComputeBufferWordVariantSceneTests.cs | 285 ++++++++++++++++++ 2 files changed, 412 insertions(+) create mode 100644 tests/SharpEmu.Gpu.Metal.Tests/MetalArchiveSpecializationTests.cs create mode 100644 tests/SharpEmu.Gpu.Metal.Tests/Scenes/ComputeBufferWordVariantSceneTests.cs diff --git a/tests/SharpEmu.Gpu.Metal.Tests/MetalArchiveSpecializationTests.cs b/tests/SharpEmu.Gpu.Metal.Tests/MetalArchiveSpecializationTests.cs new file mode 100644 index 000000000..8f982652d --- /dev/null +++ b/tests/SharpEmu.Gpu.Metal.Tests/MetalArchiveSpecializationTests.cs @@ -0,0 +1,127 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using SharpEmu.Gpu.Metal.V2; +using SharpEmu.ShaderCompiler.Metal; +using Xunit; +using Xunit.Abstractions; + +namespace SharpEmu.Gpu.Metal.Tests; + +/// +/// What buffer-word variants (MetalRenderHost.BufferWordVariants) rely on in Metal's binary +/// archives: a library file the archive wrote from a pipeline holds that pipeline's function +/// with its constants resolved, so a library loaded from the generic pipeline's file cannot be +/// specialized (the values given are ignored; logged, not asserted), while a library compiled +/// from the MSL can, and a variant's own file gives back the specialized function and finds +/// its pipeline. A kernel that writes its word times three tells them apart. +/// +public sealed unsafe class MetalArchiveSpecializationTests(ITestOutputHelper output) +{ + private const string Source = + """ + #include + using namespace metal; + constant uint c1 [[function_constant(1)]]; + constant bool c1_set = is_function_constant_defined(c1); + kernel void gen5_cs(device uint* d [[buffer(0)]], uint id [[thread_position_in_grid]]) + { + d[id] = (c1_set ? c1 : d[0]) * 3u + id; + } + """; + + [Fact] + public void ASpecializedFunctionComesFromTheSourceOrItsOwnFileNotTheGenericFile() + { + if (Environment.GetEnvironmentVariable("SHARPEMU_TEST_REQUIRE_DEVICE") != "1") return; + var device = MetalNative.MTLCreateSystemDefaultDevice(); + var root = Path.Combine(Path.GetTempPath(), $"p3probe-{Guid.NewGuid():N}"); + Gen5MslShader.BufferWordConstant[] declared = [new(1, 0)]; + var keyGeneric = new UInt128(11, 1); + var keyVariant = new UInt128(11, 2); + try + { + var lib1 = MetalRenderHost.TryCompileLibrary(device, Source, false, out var e1, out _, askArchive: false); + Assert.True(lib1 != 0, e1); + var g1 = MetalRenderHost.NewTranslatedFunction(lib1, "gen5_cs", null, declared, [], out _); + var v1 = MetalRenderHost.NewTranslatedFunction(lib1, "gen5_cs", null, declared, [7u], out _); + Assert.True(g1 != 0 && v1 != 0); + using (var archive = MetalBinaryArchive.Open(root, device, "translator-a", 64L << 20)) + { + archive.CaptureCompute(keyGeneric, g1); + archive.CaptureCompute(keyVariant, v1); + archive.Flush(wait: true); + } + + using (var archive = MetalBinaryArchive.Open(root, device, "translator-a", 64L << 20)) + { + var lib2 = MetalRenderHost.TryCompileLibrary(device, Source, false, out _, out _, askArchive: false); + var lib3 = archive.TryLoadLibrary(keyGeneric); + var lib4 = archive.TryLoadLibrary(keyVariant); + foreach (var (name, lib) in new[] { ("source", lib2), ("generic-file", lib3), ("variant-file", lib4), ("same-lib", lib1) }) + { + Assert.True(lib != 0, name); + var g = MetalRenderHost.NewTranslatedFunction(lib, "gen5_cs", null, declared, [], out _); + var v = MetalRenderHost.NewTranslatedFunction(lib, "gen5_cs", null, declared, [7u], out _); + var results = (GenericHit: Hit(device, archive, keyGeneric, g), VariantHit: Hit(device, archive, keyVariant, v), + Generic: Run(device, g), Variant: Run(device, v)); + output.WriteLine($"{name}: {results} (5*3=15 read from the data, 7*3=21 specialized)"); + if (name == "generic-file") + { + // Metal's behaviour today, which the design works around: not asserted. + continue; + } + + // The specialized function computes with the value given, and the archive has its pipeline. + Assert.Equal((21u, true), (results.Variant, results.VariantHit)); + if (name != "variant-file") + { + Assert.Equal((15u, true), (results.Generic, results.GenericHit)); + } + } + } + } + finally + { + if (Directory.Exists(root)) Directory.Delete(root, true); + } + } + + private static unsafe uint Run(nint device, nint function) + { + nint error = 0; + var state = MetalNative.Send(device, MetalNative.Selector("newComputePipelineStateWithFunction:error:"), function, ref error); + if (state == 0) return 0xDEAD; + var queue = MetalNative.Send(device, MetalNative.Selector("newCommandQueue")); + var buffer = MetalNative.SendNewBuffer(device, MetalNative.Selector("newBufferWithLength:options:"), 64, 0); + var words = (uint*)MetalNative.Send(buffer, MetalNative.Selector("contents")); + words[0] = 5; + var commands = MetalNative.Send(queue, MetalNative.Selector("commandBuffer")); + var encoder = MetalNative.Send(commands, MetalNative.Selector("computeCommandEncoder")); + MetalNative.SendVoid(encoder, MetalNative.Selector("setComputePipelineState:"), state); + MetalNative.SendSetBuffer(encoder, MetalNative.Selector("setBuffer:offset:atIndex:"), buffer, 0, 0); + MetalNative.SendDispatch(encoder, MetalNative.Selector("dispatchThreadgroups:threadsPerThreadgroup:"), + new MtlSize { Width = 1, Height = 1, Depth = 1 }, new MtlSize { Width = 1, Height = 1, Depth = 1 }); + MetalNative.SendVoid(encoder, MetalNative.Selector("endEncoding")); + MetalNative.SendVoid(commands, MetalNative.Selector("commit")); + MetalNative.SendVoid(commands, MetalNative.Selector("waitUntilCompleted")); + return words[0]; + } + + private static bool Hit(nint device, MetalBinaryArchive archive, UInt128 key, nint function) + { + var stored = archive.OpenLibraryArchive(key); + if (stored == 0) return false; + var descriptor = MetalNative.Send( + MetalNative.Send(MetalNative.Class("MTLComputePipelineDescriptor"), MetalNative.Selector("alloc")), + MetalNative.Selector("init")); + MetalNative.SendVoid(descriptor, MetalNative.Selector("setComputeFunction:"), function); + MetalNative.SendVoid(descriptor, MetalNative.Selector("setBinaryArchives:"), + MetalNative.Send(MetalNative.Class("NSArray"), MetalNative.Selector("arrayWithObject:"), stored)); + nint error = 0; + var state = MetalNative.SendNewMeshPipeline( + device, MetalNative.Selector("newComputePipelineStateWithDescriptor:options:reflection:error:"), + descriptor, MetalBinaryArchive.FailOnBinaryArchiveMiss, 0, ref error); + return state != 0; + } +} diff --git a/tests/SharpEmu.Gpu.Metal.Tests/Scenes/ComputeBufferWordVariantSceneTests.cs b/tests/SharpEmu.Gpu.Metal.Tests/Scenes/ComputeBufferWordVariantSceneTests.cs new file mode 100644 index 000000000..c083c4033 --- /dev/null +++ b/tests/SharpEmu.Gpu.Metal.Tests/Scenes/ComputeBufferWordVariantSceneTests.cs @@ -0,0 +1,285 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using SharpEmu.Gpu.Metal.V2; +using Xunit; +using Xunit.Abstractions; + +namespace SharpEmu.Gpu.Metal.Tests.Scenes; + +/// +/// Compute pipelines specialized for a dispatch's buffer words (MetalRenderHost.BufferWordVariants), +/// through the whole command path: PM4 dispatch, translation with the words as function +/// constants, CommitBindings(Compute), BindPipeline(Compute), Dispatch. The program loads a +/// formatted record by index (the stride and the format word are run-time words) and stores +/// what it read: the first dispatch of a layout runs the generic pipeline while its variant +/// builds, later ones the variant, which writes the same bytes; a pipeline keeps a bounded +/// number of variants; the compute switch keeps every dispatch generic; and a variant's +/// library file is stored and found under a key of its own. +/// +public sealed class ComputeBufferWordVariantSceneTests(ITestOutputHelper output) : SceneTestBase(output) +{ + private const uint Index = 2; + private const uint Records = 8; + private const int InputBytes = 1024; + private const uint Float32x4 = 77; + private const uint Unorm8x4 = 56; + private const uint Unorm16x2 = 23; + private static readonly TimeSpan BuildTimeout = TimeSpan.FromSeconds(60); + private static readonly Lazy Device = new(MetalNative.MTLCreateSystemDefaultDevice); + + /// + /// BUFFER_LOAD_FORMAT_XYZW of record s0 from the V# in s[8:11] (IDXEN: the stride multiplies + /// the index), its four dwords stored as read to the V# in s[12:15]. + /// + private static readonly uint[] LoadIndexedFormat = + [ + 0x7E020200, // v_mov_b32 v1, s0 + 0xE00C2000, 0x80020401, // buffer_load_format_xyzw v[4:7], v1, s[8:11] idxen + 0xE0700000, 0x80030400, // buffer_store_dword v4, off, s[12:15] + 0xE0700004, 0x80030500, // buffer_store_dword v5, off, s[12:15] offset:4 + 0xE0700008, 0x80030600, // buffer_store_dword v6, off, s[12:15] offset:8 + 0xE070000C, 0x80030700, // buffer_store_dword v7, off, s[12:15] offset:12 + 0xBF810000, // s_endpgm + ]; + + [Fact] + public void AComputeVariantIsStoredUnderAnotherArchiveKeyThanTheGenericPipeline() + { + var library = new UInt128(0x1111, 0x2222); + var first = new UInt128(1, 2); + var second = new UInt128(3, 4); + + Assert.Equal(library, MetalRenderHost.ComputeBufferWordArchiveKey(library, default)); + Assert.NotEqual(library, MetalRenderHost.ComputeBufferWordArchiveKey(library, first)); + Assert.NotEqual( + MetalRenderHost.ComputeBufferWordArchiveKey(library, first), + MetalRenderHost.ComputeBufferWordArchiveKey(library, second)); + // Another program's variant of the same values is another file. + Assert.NotEqual( + MetalRenderHost.ComputeBufferWordArchiveKey(library, first), + MetalRenderHost.ComputeBufferWordArchiveKey(new UInt128(0x3333, 0x4444), first)); + // A module with no key stores no variant: the values alone would name one file for every program. + Assert.Equal(default, MetalRenderHost.ComputeBufferWordArchiveKey(default, first)); + // Not the key a render variant's pair is listed under. + Assert.NotEqual( + MetalRenderHost.BufferWordArchiveKey(library, first), MetalRenderHost.ComputeBufferWordArchiveKey(library, first)); + } + + [Fact] + public void TheComputeSwitchFollowsTheConstantsAndItsVariable() => + Assert.Equal( + MetalRenderHost.BufferWordConstants && + Environment.GetEnvironmentVariable("SHARPEMU_METAL_V2_BUFFER_WORD_COMPUTE") != "0", + MetalRenderHost.BufferWordComputeVariants); + + [Fact] + public void TheFirstDispatchOfALayoutRunsGenericAndTheVariantWritesTheSameBytes() + { + using var rig = CreateRig(); + if (rig is null) return; + RequireVariants(rig); + using var gate = new ManualResetEventSlim(false); + rig.Host.BeforeBufferWordVariantBuild = () => gate.Wait(BuildTimeout); + try + { + var input = Input(rig); + foreach (var (format, stride) in new[] { (Float32x4, 16u), (Unorm8x4, 12u), (Unorm16x2, 20u), (Float32x4, 36u) }) + { + gate.Reset(); + var before = rig.Host.BufferWordComputeCounters; + var generic = Dispatch(rig, input, format, stride); + var during = rig.Host.BufferWordComputeCounters; + Assert.Equal( + (before.DrawsVariant, before.DrawsGeneric + 1, before.DrawsPending + 1, before.Built), + (during.DrawsVariant, during.DrawsGeneric, during.DrawsPending, during.Built)); + Assert.Equal(1, rig.Host.BufferWordVariantsPending); + + gate.Set(); + Assert.True(rig.Host.WaitForBufferWordVariants(BuildTimeout)); + var specialized = Dispatch(rig, input, format, stride); + var after = rig.Host.BufferWordComputeCounters; + Output.WriteLine( + $"format={format} stride={stride} generic={string.Join(",", generic.Select(Hex))} " + + $"built={after.Built} variant={after.DrawsVariant} failed={after.Failed}"); + Assert.Equal((before.Built + 1, before.Failed, during.DrawsVariant + 1), (after.Built, after.Failed, after.DrawsVariant)); + Assert.Equal(generic, specialized); + Assert.Contains(generic, word => word != 0); + if (format == Float32x4) + { + // The record's own four dwords: the stride picked the record. + Assert.Equal(rig.Read(input + Index * stride, 4), generic); + } + } + + // Draws kept their own counters. + Assert.Equal(0L, rig.Host.BufferWordCounters.DrawsGeneric + rig.Host.BufferWordCounters.DrawsVariant); + Assert.Empty(rig.Fatals); + } + finally + { + gate.Set(); + } + } + + [Fact] + public void LayoutsPastThePipelinesCapRunGenericAndAreCounted() + { + using var rig = CreateRig(); + if (rig is null) return; + RequireVariants(rig); + using var gate = new ManualResetEventSlim(false); + rig.Host.BeforeBufferWordVariantBuild = () => gate.Wait(BuildTimeout); + try + { + var input = Input(rig); + // A stride that changes from dispatch to dispatch: one layout each. + static uint Stride(int layout) => 16 + 4 * (uint)layout; + var results = new List(); + for (var layout = 0; layout <= MetalRenderHost.MaxBufferWordVariantsPerPipeline; layout++) + { + results.Add(Dispatch(rig, input, Float32x4, Stride(layout))); + } + + var counters = rig.Host.BufferWordComputeCounters; + Assert.Equal(MetalRenderHost.MaxBufferWordVariantsPerPipeline + 1L, counters.DrawsGeneric); + Assert.Equal(1L, counters.DrawsCapped); + Assert.Equal(MetalRenderHost.MaxBufferWordVariantsPerPipeline, rig.Host.BufferWordVariantsPending); + + gate.Set(); + Assert.True(rig.Host.WaitForBufferWordVariants(BuildTimeout)); + // The layout past the cap stays generic, now and later; the others run their variants. + var capped = MetalRenderHost.MaxBufferWordVariantsPerPipeline; + Assert.Equal(results[capped], Dispatch(rig, input, Float32x4, Stride(capped))); + Assert.Equal(results[0], Dispatch(rig, input, Float32x4, Stride(0))); + counters = rig.Host.BufferWordComputeCounters; + Assert.Equal((long)MetalRenderHost.MaxBufferWordVariantsPerPipeline, counters.Built); + Assert.Equal(2L, counters.DrawsCapped); + Assert.Equal(1L, counters.DrawsVariant); + for (var layout = 0; layout < results.Count; layout++) + { + Assert.Equal(rig.Read(input + Index * Stride(layout), 4), results[layout]); + } + } + finally + { + gate.Set(); + } + } + + [Fact] + public void TheComputeSwitchOffKeepsEveryDispatchGeneric() + { + using var rig = CreateRig(); + if (rig is null) return; + RequireVariants(rig); + rig.Host.ComputeBufferWordVariants = false; + var input = Input(rig); + var first = Dispatch(rig, input, Unorm8x4, 12); + Assert.True(rig.Host.WaitForBufferWordVariants(BuildTimeout)); + var second = Dispatch(rig, input, Unorm8x4, 12); + + var counters = rig.Host.BufferWordComputeCounters; + Assert.Equal((0L, 0L, 2L, 0L), (counters.Built, counters.DrawsVariant, counters.DrawsGeneric, counters.DrawsPending)); + Assert.Equal(2L, rig.Host.BufferWordComputeDispatchesOff); + Assert.Equal(0, rig.Host.BufferWordVariantsPending); + Assert.Equal(first, second); + } + + [Fact] + public void TheNextHostFindsTheComputeVariantInTheArchive() + { + if (Environment.GetEnvironmentVariable("SHARPEMU_TEST_REQUIRE_DEVICE") != "1") + { + Output.WriteLine("Scenes run on the device only behind the exclusive device gate (SHARPEMU_TEST_REQUIRE_DEVICE=1)."); + return; + } + + var root = Path.Combine(Path.GetTempPath(), $"sharpemu-compute-buffer-words-{Guid.NewGuid():N}"); + try + { + var first = Run(root); + Output.WriteLine($"first: {first}"); + // The generic pipeline's library file, and the variant's of its own. + Assert.Equal(2, first.LibrariesWritten); + + var second = Run(root); + Output.WriteLine($"second: {second}"); + // Both pipelines come from the archive: the generic one from its library's file, + // the variant, function and pipeline, from the file stored under its key (the + // generic file's library would ignore the values); nothing is written again. + Assert.Equal((2, 2, 0, 0), (second.LibraryHits, second.PipelineHits, second.PipelineMisses, second.LibrariesWritten)); + } + finally + { + if (Directory.Exists(root)) + { + Directory.Delete(root, recursive: true); + } + } + } + + private (int LibraryHits, int LibraryMisses, int Rejected, int LibrariesWritten, + int PipelineHits, int PipelineMisses, int PipelinesAdded, int LoadedSegments) Run(string root) + { + var archive = MetalBinaryArchive.Open(root, Device.Value, "translator-a", 64L << 20); + var previous = MetalBinaryArchive.Install(archive); + try + { + using (var rig = CreateRig()!) + { + RequireVariants(rig); + var input = Input(rig); + var generic = Dispatch(rig, input, Unorm8x4, 12); + Assert.True(rig.Host.WaitForBufferWordVariants(BuildTimeout)); + Assert.Equal(generic, Dispatch(rig, input, Unorm8x4, 12)); + var counters = rig.Host.BufferWordComputeCounters; + Assert.Equal((1L, 1L, 0L), (counters.Built, counters.DrawsVariant, counters.Failed)); + } + + archive.Flush(wait: true); + return archive.Counters; + } + finally + { + MetalBinaryArchive.Install(previous); + archive.Dispose(); + } + } + + // The scenes translate as the host does: with portable buffers and the words as constants. + private static void RequireVariants(SceneRig rig) + { + Assert.True(MetalRenderHost.BufferWordConstants, "Buffer-word constants are off in this process."); + Assert.True(rig.Host.ComputeBufferWordVariants || !MetalRenderHost.BufferWordComputeVariants); + } + + // A byte pattern no two records share, so a wrong stride or format reads other bytes. + private static ulong Input(SceneRig rig) + { + var address = rig.Memory.Allocate(InputBytes, 256); + var bytes = new byte[InputBytes]; + for (var at = 0; at < bytes.Length; at++) + { + bytes[at] = (byte)((at * 37) + 11); + } + + rig.Memory.Write(address, bytes); + return address; + } + + // One dispatch of the program over record Index of the input, read as format/stride; the four dwords it stored. + private static uint[] Dispatch(SceneRig rig, ulong input, uint format, uint stride) + { + var output = rig.Memory.Allocate(16, 256); + rig.Memory.Write(output, [0, 0, 0, 0]); + var userData = new uint[16]; + userData[0] = Index; + Descriptors.Buffer(input, stride, Records, format).CopyTo(userData, 8); + Descriptors.Buffer(output, 4, 4, format: 20).CopyTo(userData, 12); + rig.Submit(rig.Dispatch(new ScenePm4(), LoadIndexedFormat, userData, 1)); + return rig.Read(output, 4); + } + + private static string Hex(uint value) => $"0x{value:X8}"; +} From 7ade8ea5aeabbb18d7413ea3a9a9321e09de9c0b Mon Sep 17 00:00:00 2001 From: kuba Date: Mon, 16 Nov 2026 23:43:23 +0000 Subject: [PATCH 159/178] [Metal] Never write a buffer-word variant pipeline as a module's library file A noted render pipeline is written as the library file of either stage key that has none. A variant's functions carry one layout's strides and formats, so written under its modules' keys (their files evicted or rejected) the next start would load that layout as the library of every draw of the module. A variant is now listed under its pair only. --- .../SharpEmu.Gpu.Metal/V2/MetalBinaryArchive.cs | 17 +++++++++++++++-- .../V2/MetalRenderHost.Pipelines.cs | 3 ++- .../MetalBufferWordVariantTests.cs | 12 ++++++++++++ 3 files changed, 29 insertions(+), 3 deletions(-) diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalBinaryArchive.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalBinaryArchive.cs index d11922702..e1436aa1c 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalBinaryArchive.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalBinaryArchive.cs @@ -584,13 +584,17 @@ public long StoreLibrary(UInt128 key, PipelineKind kind, nint descriptor) /// from its MSL, and its file was never read. /// public void NoteRenderPipeline( - nint descriptor, PipelineKind kind, UInt128 vertexKey, UInt128 pixelKey, bool missed, UInt128? pixelPairKey = null) + nint descriptor, PipelineKind kind, UInt128 vertexKey, UInt128 pixelKey, bool missed, UInt128? pixelPairKey = null, + bool specialized = false) { if (descriptor == 0 || Volatile.Read(ref _disposed) != 0) { return; } + var pairKey = PairKey(vertexKey, pixelPairKey ?? pixelKey); + (vertexKey, pixelKey) = LibraryFileKeys(vertexKey, pixelKey, specialized); + // Before the segments are loaded nothing could hit; a pipeline they hold would be // stored twice, and one they do not is stored by a later start. missed &= _loaded.IsSet; @@ -602,7 +606,7 @@ public void NoteRenderPipeline( } MetalNative.Send(descriptor, SelRetain); - if (!TryEnqueue(new Job(JobKind.Capture, kind, descriptor, vertex, pixel, missed, null, PairKey(vertexKey, pixelPairKey ?? pixelKey)))) + if (!TryEnqueue(new Job(JobKind.Capture, kind, descriptor, vertex, pixel, missed, null, pairKey))) { Interlocked.Increment(ref _capturesDropped); MetalNative.SendVoid(descriptor, SelRelease); @@ -611,6 +615,15 @@ public void NoteRenderPipeline( } } + /// + /// The stage keys a noted pipeline may be written as the library file of. A pipeline of + /// specialized functions (a buffer-word variant) has none: written under its modules' + /// keys when their files are missing, the file would hold that variant's strides and + /// formats, and the next start would load it as the library of every draw of the module. + /// + internal static (UInt128 Vertex, UInt128 Pixel) LibraryFileKeys(UInt128 vertexKey, UInt128 pixelKey, bool specialized) => + specialized ? default : (vertexKey, pixelKey); + /// Serializes the current segment now; waits when . public void Flush(bool wait, TimeSpan? timeout = null) { diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Pipelines.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Pipelines.cs index 664e25ff7..a586ce846 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Pipelines.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Pipelines.cs @@ -1200,7 +1200,8 @@ private nint CreateRenderPipelineState( vertexArchiveKey, pixelLibraryKey, missed, - pixelArchiveKey); + pixelArchiveKey, + specialized: bufferWords is not null); } if (state == 0) diff --git a/tests/SharpEmu.Gpu.Metal.Tests/MetalBufferWordVariantTests.cs b/tests/SharpEmu.Gpu.Metal.Tests/MetalBufferWordVariantTests.cs index 22ab887d8..3352673fc 100644 --- a/tests/SharpEmu.Gpu.Metal.Tests/MetalBufferWordVariantTests.cs +++ b/tests/SharpEmu.Gpu.Metal.Tests/MetalBufferWordVariantTests.cs @@ -129,6 +129,18 @@ public void TheSwitchFollowsPortableBuffersAndItsVariable() => Environment.GetEnvironmentVariable("SHARPEMU_METAL_V2_BUFFER_WORD_CONSTANTS") != "0", MetalRenderHost.BufferWordConstants); + // A variant pipeline is listed under its pair, but is never written as the library file of + // its modules: that file is what every later draw of the module loads. + [Fact] + public void AVariantPipelineIsNeverWrittenAsAModulesLibraryFile() + { + var vertex = new UInt128(0x1111, 0x2222); + var pixel = new UInt128(0x1234, 0x5678); + + Assert.Equal((vertex, pixel), MetalBinaryArchive.LibraryFileKeys(vertex, pixel, specialized: false)); + Assert.Equal((default(UInt128), default(UInt128)), MetalBinaryArchive.LibraryFileKeys(vertex, pixel, specialized: true)); + } + [Fact] public void AVariantIsListedUnderAnotherArchiveKeyThanTheGenericPipeline() { From 72bcd6d5359cfd88837311b1447c7957574b06a9 Mon Sep 17 00:00:00 2001 From: kuba Date: Tue, 17 Nov 2026 00:55:27 +0000 Subject: [PATCH 160/178] [Metal] Build buffer-word variants from their own archive files, in a lane of their own A render variant's specialized stages are written as library files of their own (StageBufferWordArchiveKey: the module's library key, the LOD statistics switch and every value of the stage; zero for a module without a key or a stage without buffer words, never the module's key), and a later start loads each function from its file and the pipeline from the segment its pair is listed in: no front end, no back end. A file that does not load or lacks the function is counted (files_rejected) and the function is built instead. A module whose library this process compiled from its MSL (LibraryFromSource, kept through the source-key dedupe) is specialized directly; only a library that came from the archive needs its MSL compiled again, once per module (SpecializationGate keeps a second builder from compiling it twice). Variant builds no longer take the prewarm's slots, which the static precompile can hold for minutes: four builders, and compiles (an archive miss only) in a lane of their own (MetalCompileScheduler.EnterVariant, two slots, still behind the game's compiles). The GPU worker no longer waits on a builder: segments are read and opened outside the archive's lock; a builder never compiles or rebuilds a module, nor the LOD-statistics or remapped pixel function a generic stage needs (the variant is counted unresident and its draws stay generic); a capped layout no longer formats its warning on every draw. The PERF fields add from_file / from_library / from_msl, msl_compiles, pipelines_compiled, files_rejected, unresident, build_ms and wait_ms. --- docs/macos/configuration.md | 2 +- .../V2/MetalBinaryArchive.cs | 152 ++++--- .../V2/MetalCompileScheduler.cs | 63 ++- .../V2/MetalRenderHost.BufferWordVariants.cs | 425 +++++++++++++++--- .../V2/MetalRenderHost.Pipelines.cs | 91 ++-- .../V2/MetalRenderHost.SubsetJoin.cs | 2 +- 6 files changed, 572 insertions(+), 163 deletions(-) diff --git a/docs/macos/configuration.md b/docs/macos/configuration.md index 2f2f95557..a6f82ea6b 100644 --- a/docs/macos/configuration.md +++ b/docs/macos/configuration.md @@ -106,7 +106,7 @@ undoes an optimization to isolate a miscompile: | `SHARPEMU_MSL_PERSISTENT_RECORDS` | on | Accesses multi-dword records of persistent-thread kernels dword by dword. | | `SHARPEMU_MSL_BYTEBIAS` | off | `1` keeps the per-buffer byte bias. | | `SHARPEMU_MSL_FUSE_MAD` | on | Emits the guest's legacy multiply-adds (`V_MAD_F32`, `V_MAC_F32`) as one fused operation in compute programs and pixel programs without depth export. Faster (about 5 ms of an 82 ms Demon's Souls frame) but not bit-exact for MAD/MAC: the guest rounds the product first. `0` restores the exact two-op form. | -| `SHARPEMU_METAL_V2_BUFFER_WORD_CONSTANTS` | on | With portable buffers (`SHARPEMU_METAL_V2_PORTABLE_BUFFERS`, on), each buffer stride and format word a program reads at run time is also a Metal function constant. A draw draws through its pipeline as before and, once a background compile has made it, through a variant whose functions have the draw's words folded in (same pixels, faster vertex stage). Up to 16 variants a pipeline; mesh, rectangle-list and tessellation pipelines stay generic. The periodic counter line reports `buffer_words=[...]`. `0` restores the previous MSL exactly. | +| `SHARPEMU_METAL_V2_BUFFER_WORD_CONSTANTS` | on | With portable buffers (`SHARPEMU_METAL_V2_PORTABLE_BUFFERS`, on), each buffer stride and format word a program reads at run time is also a Metal function constant. A draw draws through its pipeline as before and, once a background compile has made it, through a variant whose functions have the draw's words folded in (same pixels, faster vertex stage). Up to 16 variants a pipeline; mesh, rectangle-list and tessellation pipelines stay generic. A variant built once is stored in the title's binary archive (each specialized stage's library file, the pipeline in its segment), so later starts load it instead of compiling. The periodic counter line reports `buffer_words=[...]`, with where built variants came from (`from_file`, `from_library`: this process's own library, `from_msl`: the module's MSL compiled again, `msl_compiles`), `pipelines_compiled`, `files_rejected`, `unresident` and the builders' `build_ms` / `wait_ms`. `0` restores the previous MSL exactly. | | `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. | diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalBinaryArchive.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalBinaryArchive.cs index e1436aa1c..1188391ba 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalBinaryArchive.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalBinaryArchive.cs @@ -421,7 +421,10 @@ public nint OpenLibraryArchive(UInt128 key) => /// /// The segments holding pipelines of the shader pair as an NSArray for a descriptor's /// binaryArchives, retained for the caller, or zero before the segments are listed or - /// when none holds the pair. Opens the ones that are closed (reading each whole). + /// when none holds the pair. Opens the ones that are closed (reading each whole) outside + /// the lock, so a lookup of the GPU worker never waits for a file another thread (a + /// buffer-word variant builder) is reading; two lookups that open the same segment at + /// once both read it, and the second copy is released. /// public nint AcquirePipelineArchives(UInt128 vertexKey, UInt128 pixelKey) { @@ -433,6 +436,7 @@ public nint AcquirePipelineArchives(UInt128 vertexKey, UInt128 pixelKey) var pair = PairKey(vertexKey, pixelKey); var acquireStarted = Stopwatch.GetTimestamp(); using var acquireTimer = new AcquireTimer(this, acquireStarted); + List<(int Sequence, string Path)>? closed = null; lock (_archivesLock) { if (Volatile.Read(ref _disposed) != 0 || !_segmentsByPair.TryGetValue(pair, out var sequences)) @@ -440,27 +444,75 @@ public nint AcquirePipelineArchives(UInt128 vertexKey, UInt128 pixelKey) return 0; } - var array = MetalNative.Send(MetalNative.Send(MetalNative.Class("NSMutableArray"), SelAlloc), SelInit); - var added = 0; if (sequences.Count > _maxSegmentsPerPair) _maxSegmentsPerPair = sequences.Count; - foreach (var sequence in sequences.ToArray()) + foreach (var sequence in sequences) { - var archive = OpenSegment(sequence, sequences); - if (archive != 0) + if (!_resident.ContainsKey(sequence)) { - MetalNative.SendVoid(array, MetalNative.Selector("addObject:"), archive); - added++; + (closed ??= []).Add((sequence, SegmentFile(sequence))); } } - if (added == 0) + if (closed is null) + { + return ResidentArray(sequences); + } + } + + var opened = new (nint Archive, long Length)[closed.Count]; + var started = Stopwatch.GetTimestamp(); + for (var index = 0; index < closed.Count; index++) + { + opened[index] = ReadSegment(closed[index].Path); + } + + Interlocked.Add(ref _segmentOpenTicks, Stopwatch.GetTimestamp() - started); + List? touched = null; + nint array; + lock (_archivesLock) + { + var disposed = Volatile.Read(ref _disposed) != 0; + _segmentsByPair.TryGetValue(pair, out var sequences); + for (var index = 0; index < closed.Count; index++) + { + var (sequence, path) = closed[index]; + var (archive, length) = opened[index]; + if (archive == 0) + { + Interlocked.Increment(ref _rejected); + if (!disposed) + { + DropSegment(sequence, path); + } + + continue; + } + + if (disposed || sequences is null || !sequences.Contains(sequence) || _resident.ContainsKey(sequence)) + { + // Gone, dropped meanwhile, or another lookup opened it first. + MetalNative.SendVoid(archive, SelRelease); + continue; + } + + AdmitSegment(sequence, archive, length, sequences); + (touched ??= []).Add(path); + } + + if (disposed || !_segmentsByPair.TryGetValue(pair, out sequences)) { - MetalNative.SendVoid(array, SelRelease); return 0; } - return array; + array = ResidentArray(sequences); + } + + foreach (var path in touched ?? []) + { + Touch(path); } + + return array; } /// @@ -585,7 +637,7 @@ public long StoreLibrary(UInt128 key, PipelineKind kind, nint descriptor) /// public void NoteRenderPipeline( nint descriptor, PipelineKind kind, UInt128 vertexKey, UInt128 pixelKey, bool missed, UInt128? pixelPairKey = null, - bool specialized = false) + bool specialized = false, UInt128 variantVertexFile = default, UInt128 variantPixelFile = default) { if (descriptor == 0 || Volatile.Read(ref _disposed) != 0) { @@ -593,7 +645,7 @@ public void NoteRenderPipeline( } var pairKey = PairKey(vertexKey, pixelPairKey ?? pixelKey); - (vertexKey, pixelKey) = LibraryFileKeys(vertexKey, pixelKey, specialized); + (vertexKey, pixelKey) = LibraryFileKeys(vertexKey, pixelKey, specialized, variantVertexFile, variantPixelFile); // Before the segments are loaded nothing could hit; a pipeline they hold would be // stored twice, and one they do not is stored by a later start. @@ -617,12 +669,15 @@ public void NoteRenderPipeline( /// /// The stage keys a noted pipeline may be written as the library file of. A pipeline of - /// specialized functions (a buffer-word variant) has none: written under its modules' - /// keys when their files are missing, the file would hold that variant's strides and - /// formats, and the next start would load it as the library of every draw of the module. + /// specialized functions (a buffer-word variant) is never written under its modules' keys: + /// the file would hold that variant's strides and formats, and the next start would load + /// it as the library of every draw of the module. It is written under the keys of its + /// specialized stages instead (MetalRenderHost.StageBufferWordArchiveKey, zero for a stage + /// that declares none or a module with no key), which name exactly those values. /// - internal static (UInt128 Vertex, UInt128 Pixel) LibraryFileKeys(UInt128 vertexKey, UInt128 pixelKey, bool specialized) => - specialized ? default : (vertexKey, pixelKey); + internal static (UInt128 Vertex, UInt128 Pixel) LibraryFileKeys( + UInt128 vertexKey, UInt128 pixelKey, bool specialized, UInt128 variantVertexFile = default, UInt128 variantPixelFile = default) => + specialized ? (variantVertexFile, variantPixelFile) : (vertexKey, pixelKey); /// Serializes the current segment now; waits when . public void Flush(bool wait, TimeSpan? timeout = null) @@ -1359,39 +1414,40 @@ private void LoadSegments() $"segment_mb={listedBytes / 1048576.0:F1} other_translator_segments={foreign.Count}"); } - // Under _archivesLock. Opens a segment for a lookup, closing the least recently used - // past ResidentLimit (never the ones of the lookup: they are in wanted); zero when its - // file does not check out any more. - private nint OpenSegment(int sequence, List wanted) + // Under _archivesLock: the resident segments of a pair's list as an NSArray retained for + // the caller (zero when none is), each marked as just used. + private nint ResidentArray(List sequences) { - if (_resident.TryGetValue(sequence, out var open)) + nint array = 0; + foreach (var sequence in sequences) { + if (!_resident.TryGetValue(sequence, out var open)) + { + continue; + } + open.Tick = ++_residentTick; - return open.Archive; - } + if (array == 0) + { + array = MetalNative.Send(MetalNative.Send(MetalNative.Class("NSMutableArray"), SelAlloc), SelInit); + } - var started = Stopwatch.GetTimestamp(); - try - { - return OpenSegmentFile(sequence, wanted); - } - finally - { - Interlocked.Add(ref _segmentOpenTicks, Stopwatch.GetTimestamp() - started); + MetalNative.SendVoid(array, MetalNative.Selector("addObject:"), open.Archive); } + + return array; } - // Under _archivesLock: reads and checks the whole file, then has Metal read it again. - private nint OpenSegmentFile(int sequence, List wanted) - { - var path = SegmentFile(sequence); - if (!TryVerify(path, out var length)) - { - Interlocked.Increment(ref _rejected); - DropSegment(sequence, path); - return 0; - } + // Outside _archivesLock: reads and checks the whole file, then has Metal read it again. + // The archive and the file's length, or zero when the file fails its trailer or Metal + // will not open it. + private (nint Archive, long Length) ReadSegment(string path) => + TryVerify(path, out var length) && OpenArchive(path) is var archive and not 0 ? (archive, length) : (0, 0); + // Under _archivesLock: an opened segment becomes resident, closing the least recently + // used past ResidentLimit (never one of the lookup's: they are in wanted). + private void AdmitSegment(int sequence, nint archive, long length, List wanted) + { while (_residentBytes + length > ResidentLimit) { var victim = -1; @@ -1415,19 +1471,9 @@ private nint OpenSegmentFile(int sequence, List wanted) _resident.Remove(victim); } - var archive = OpenArchive(path); - if (archive == 0) - { - Interlocked.Increment(ref _rejected); - DropSegment(sequence, path); - return 0; - } - _resident[sequence] = new ResidentSegment(archive, length) { Tick = ++_residentTick }; _residentBytes += length; Interlocked.Increment(ref _segmentsOpened); - Touch(path); - return archive; } private void DropSegment(int sequence, string path) diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalCompileScheduler.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalCompileScheduler.cs index b94e64b7c..feb27d56b 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalCompileScheduler.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalCompileScheduler.cs @@ -26,6 +26,12 @@ namespace SharpEmu.Gpu.Metal.V2; /// So that the prewarm is not starved forever while the game compiles continuously, a /// prewarm thread that has waited for may start one compile /// whenever no other prewarm compile is in the driver: a trickle of one. +/// +/// Buffer-word variants (MetalRenderHost.BufferWordVariants) compile through a lane of their +/// own (): the same rule against the game's compiles, but their own +/// slots, so the static precompile, which can hold every prewarm slot for many minutes, does +/// not starve them, and they take none of its slots either. A variant that loads from the +/// title's archive enters no lane at all. /// internal sealed class MetalCompileScheduler { @@ -36,14 +42,17 @@ internal sealed class MetalCompileScheduler private int _runtimePending; private long _lastRuntimeDoneTicks; private int _prewarmInFlight; + private readonly int _variantSlots; + private int _variantInFlight; private int _waiters; private long _heldTicks; private long _trickled; private long _runtimeCompiles; - public MetalCompileScheduler(int prewarmSlots, TimeSpan quiet, TimeSpan starvationLimit) + public MetalCompileScheduler(int prewarmSlots, TimeSpan quiet, TimeSpan starvationLimit, int variantSlots = DefaultVariantSlots) { _prewarmSlots = Math.Max(1, prewarmSlots); + _variantSlots = Math.Max(1, variantSlots); _quietTicks = (long)(quiet.TotalSeconds * Stopwatch.Frequency); _starvationTicks = (long)(starvationLimit.TotalSeconds * Stopwatch.Frequency); StarvationLimit = starvationLimit; @@ -57,8 +66,17 @@ public MetalCompileScheduler(int prewarmSlots, TimeSpan quiet, TimeSpan starvati public static MetalCompileScheduler Shared { get; } = new( MetalShaderPrewarm.WorkerCount, TimeSpan.FromMilliseconds(100), TimeSpan.FromSeconds(1)); + /// + /// Variant compiles in the driver at once: the two the variant builders compiled with when + /// they shared the prewarm's slots. + /// + public const int DefaultVariantSlots = 2; + public TimeSpan StarvationLimit { get; } + /// Variant compiles in the driver right now. + public int VariantInFlight => Volatile.Read(ref _variantInFlight); + /// Runtime compiles asked for and not yet done. public int RuntimePending => Volatile.Read(ref _runtimePending); @@ -97,10 +115,19 @@ public RuntimeScope Runtime() /// slot until the returned scope is disposed. A default scope when /// turned true while waiting; the caller then compiles nothing. /// - public PrewarmScope EnterPrewarm(Func stopping) + public PrewarmScope EnterPrewarm(Func stopping) => Enter(stopping, variant: false); + + /// + /// As , a slot of the buffer-word variants' own lane: the same + /// wait for the game's compiles, but none for the prewarm's. + /// + public PrewarmScope EnterVariant(Func stopping) => Enter(stopping, variant: true); + + private PrewarmScope Enter(Func stopping, bool variant) { var started = Stopwatch.GetTimestamp(); var waited = false; + var slots = variant ? _variantSlots : _prewarmSlots; lock (_sync) { _waiters++; @@ -113,15 +140,16 @@ public PrewarmScope EnterPrewarm(Func stopping) return default; } + var inFlight = variant ? _variantInFlight : _prewarmInFlight; var now = Stopwatch.GetTimestamp(); var quiet = Volatile.Read(ref _runtimePending) == 0 && now - Volatile.Read(ref _lastRuntimeDoneTicks) >= _quietTicks; - if (quiet && _prewarmInFlight < _prewarmSlots) + if (quiet && inFlight < slots) { break; } - if (!quiet && _prewarmInFlight == 0 && now - started >= _starvationTicks) + if (!quiet && inFlight == 0 && now - started >= _starvationTicks) { Interlocked.Increment(ref _trickled); break; @@ -133,7 +161,14 @@ public PrewarmScope EnterPrewarm(Func stopping) Monitor.Wait(_sync, 10); } - _prewarmInFlight++; + if (variant) + { + _variantInFlight++; + } + else + { + _prewarmInFlight++; + } } finally { @@ -146,14 +181,22 @@ public PrewarmScope EnterPrewarm(Func stopping) Interlocked.Add(ref _heldTicks, Stopwatch.GetTimestamp() - started); } - return new PrewarmScope(this); + return new PrewarmScope(this, variant); } - private void PrewarmDone() + private void PrewarmDone(bool variant) { lock (_sync) { - _prewarmInFlight--; + if (variant) + { + _variantInFlight--; + } + else + { + _prewarmInFlight--; + } + Monitor.PulseAll(_sync); } } @@ -172,12 +215,12 @@ public readonly struct RuntimeScope(MetalCompileScheduler? scheduler) : IDisposa public void Dispose() => scheduler?.RuntimeDone(); } - public readonly struct PrewarmScope(MetalCompileScheduler? scheduler) : IDisposable + public readonly struct PrewarmScope(MetalCompileScheduler? scheduler, bool variant = false) : IDisposable { /// False when the prewarm stopped while waiting: nothing may be compiled. public bool Entered => scheduler is not null; - public void Dispose() => scheduler?.PrewarmDone(); + public void Dispose() => scheduler?.PrewarmDone(variant); } [ThreadStatic] diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.BufferWordVariants.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.BufferWordVariants.cs index b633b969c..10eba58a2 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.BufferWordVariants.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.BufferWordVariants.cs @@ -24,8 +24,14 @@ namespace SharpEmu.Gpu.Metal.V2; /// /// /// The first draw of a layout draws through the generic pipeline, as today, and queues the -/// variant on a background builder that compiles at prewarm priority (MetalCompileScheduler); -/// later draws take the variant once it is ready. Nothing is skipped or waited for. A pipeline +/// variant on a background builder; later draws take the variant once it is ready. Nothing is +/// skipped or waited for. A variant a past session built loads from the title's archive: each +/// specialized stage's function from a library file of its own (StageBufferWordArchiveKey), +/// the pipeline from the segment its pair is listed in, no compiler run. Anything else +/// compiles in the variants' own lane of MetalCompileScheduler (EnterVariant), which gives way +/// to the game's compiles but not to the prewarm's, and specializes the module's own library +/// when this process compiled it from MSL, its MSL compiled again only when that library came +/// from the archive (RetainSpecializableLibrary). A pipeline /// keeps at most variants and a module at most /// specialized functions; past either the /// draw stays on the generic pipeline and is counted. Mesh, rectangle-list and tessellation @@ -82,6 +88,15 @@ internal sealed partial class MetalRenderHost /// internal const int MaxBufferWordSpecializationsPerModule = 64; + /// + /// Threads that build variants: a variant from files is a few file reads and lookups, so + /// the builders outnumber the variants' compile slots (MetalCompileScheduler.DefaultVariantSlots). + /// + internal const int DefaultBufferWordBuilders = 4; + + /// The builder threads this host starts with its first variant; tests set it before. + internal int BufferWordBuilderCount { get; set; } = DefaultBufferWordBuilders; + private static readonly nint SelBufferWordRetain = MetalNative.Selector("retain"); private const int BufferWordVariantSlots = 32; private const nuint MetalDataTypeUInt = 33; @@ -182,6 +197,33 @@ internal static nint NewTranslatedFunction(nint library, Gen5MslShader shader, b internal static UInt128 BufferWordArchiveKey(UInt128 pixelPairKey, UInt128 values) => values == default ? pixelPairKey : pixelPairKey ^ values ^ new UInt128(0x4255464645525F57UL, 0x4F5244535F564152UL); + /// + /// The archive key of the library file a render variant's specialized stage is stored + /// under and loaded from: a hash of the stage module's library key (its MSL and compile + /// options), the LOD statistics switch the function was made with (none for a stage that + /// does not declare it) and every buffer-word value of the stage, so a file is only ever + /// loaded for exactly the function it holds. None (zero) when the module has no key (the + /// values alone would name the same file for every program) or the stage declares no + /// buffer words (it keeps its generic function and file); never the module's own key. + /// + internal static UInt128 StageBufferWordArchiveKey(UInt128 libraryKey, bool? mipStatistics, ReadOnlySpan values) + { + if (libraryKey == default || values.IsEmpty) + { + return default; + } + + Span head = stackalloc byte[24]; + MemoryMarshal.Write(head, in libraryKey); + // A tag no compute or pair key mixes in, then the switch: none, off, on. + MemoryMarshal.Write(head[16..], 0x4247_5354_5F57_4253UL ^ (ulong)(mipStatistics is null ? 0 : mipStatistics.Value ? 2 : 1)); + var hash = new XxHash128(0x5354_4147_455F_4257L); + hash.Append(head); + hash.Append(MemoryMarshal.AsBytes(values)); + var key = hash.GetCurrentHashAsUInt128(); + return key == default || key == libraryKey ? default : key; + } + /// /// The archive key a compute variant's library file (library and pipeline binary, /// MetalBinaryArchive.CaptureCompute) is stored under: the module's library key mixed with @@ -204,6 +246,7 @@ private sealed class BufferWordVariants(Gen5MslShader.BufferWordConstant[] verte public readonly uint[] Scratch = new uint[vertex.Length + pixel.Length]; public readonly BufferWordVariant?[] Table = new BufferWordVariant?[BufferWordVariantSlots]; public int Count; + public bool CapWarned; } // One variant: the values (vertex constants first), their hash, the archive key, and the @@ -218,8 +261,73 @@ private sealed class BufferWordVariant(uint[] values, ulong hash, UInt128 archiv public int Status; } - // The specialized functions a variant pipeline is made from; zero takes the generic one. - private sealed record BufferWordPipeline(nint VertexFunction, nint PixelFunction, uint[] Values, int VertexCount, UInt128 ArchiveKey); + // The specialized functions a variant pipeline is made from (zero takes the generic one), + // the library file keys of the specialized stages, and the build they belong to. + private sealed record BufferWordPipeline( + nint VertexFunction, nint PixelFunction, uint[] Values, int VertexCount, UInt128 ArchiveKey, + UInt128 VertexFile, UInt128 PixelFile, BufferWordBuild Build); + + // Where a specialized function came from, cheapest first: a variant counts its costliest. + private enum BufferWordSource : byte + { + None, + // Its own library file in the title's archive: no compiler run. + File, + // The module's library, compiled from its MSL in this process. + Library, + // The module's MSL compiled a second time (its library came from the archive). + Recompiled, + } + + // One variant build on a builder thread: its compile slot of the variants' lane, taken + // the first time the build has to compile (an archive miss), and what it took. + private sealed class BufferWordBuild(MetalRenderHost host, BufferWordTally tally) : IDisposable + { + private MetalCompileScheduler.PrewarmScope _slot; + private bool _entered; + public readonly BufferWordTally Tally = tally; + public BufferWordSource Source; + public bool PipelineCompiled; + public long WaitTicks; + + public void Note(BufferWordSource source) + { + if (source > Source) + { + Source = source; + } + } + + // Before any compile: waits for a slot of the variants' lane (the game's compiles + // first); throws when the host stops meanwhile. + public void EnterCompile(bool pipeline = false) + { + PipelineCompiled |= pipeline; + if (_entered) + { + return; + } + + var started = System.Diagnostics.Stopwatch.GetTimestamp(); + _slot = MetalCompileScheduler.Shared.EnterVariant(() => host._bufferWordStopping); + WaitTicks += System.Diagnostics.Stopwatch.GetTimestamp() - started; + if (!_slot.Entered) + { + throw new OperationCanceledException("The host is stopping."); + } + + _entered = true; + } + + public void Dispose() + { + if (_entered) + { + _entered = false; + _slot.Dispose(); + } + } + } // A module's specialized function, by its values (and the LOD statistics switch of a pixel function). private sealed class SpecializationKey(bool? mipStatistics, uint[] values) : IEquatable @@ -278,6 +386,19 @@ private sealed class BufferWordTally public long GenericUnreadable; public long GenericFailed; public long GenericOff; + // Built variants by their costliest function's source, the module MSL compiled a second + // time, pipelines the archive missed, variant files that failed to load, variants + // refused because a module was not resident, and builder time spent building and + // waiting for a compile slot. + public long FromFile; + public long FromLibrary; + public long FromRecompile; + public long Recompiles; + public long PipelinesCompiled; + public long FilesRejected; + public long Unresident; + public long BuildTicks; + public long WaitTicks; } private readonly BufferWordTally _bufferWordRender = new(); @@ -300,6 +421,22 @@ private sealed class BufferWordTally internal (long Built, long Failed, long Capped, long DrawsVariant, long DrawsGeneric, long DrawsPending, long DrawsCapped) BufferWordComputeCounters => CountersOf(_bufferWordCompute); + /// + /// Where the built variants of a kind came from (render, or compute with + /// ), for tests: by their costliest function's source, the + /// module MSL compiled again, pipelines the archive missed, and the builders' build time. + /// + internal (long FromFile, long FromLibrary, long FromRecompile, long Recompiles, long PipelinesCompiled, + long FilesRejected, long Unresident, double BuildMilliseconds) BufferWordSources(bool compute = false) + { + var tally = compute ? _bufferWordCompute : _bufferWordRender; + return (Interlocked.Read(ref tally.FromFile), Interlocked.Read(ref tally.FromLibrary), + Interlocked.Read(ref tally.FromRecompile), Interlocked.Read(ref tally.Recompiles), + Interlocked.Read(ref tally.PipelinesCompiled), Interlocked.Read(ref tally.FilesRejected), + Interlocked.Read(ref tally.Unresident), + Interlocked.Read(ref tally.BuildTicks) * 1000.0 / System.Diagnostics.Stopwatch.Frequency); + } + /// Compute dispatches of declaring programs that ran generic because the compute switch was off, for tests. internal long BufferWordComputeDispatchesOff => _bufferWordCompute.GenericOff; @@ -503,11 +640,17 @@ private nint VariantStateOf( if (variants.Count >= MaxBufferWordVariantsPerPipeline) { tally.GenericCapped++; - MetalV2Diagnostics.WarnOnce( - entry.Graphics ? "buffer-word-variant-cap" : "buffer-word-compute-variant-cap", - $"A pipeline {(entry.Graphics ? "drew" : "dispatched")} more buffer-word layouts than it keeps variants for; " + - $"the rest run generic: pipeline={entry.Id} {(entry.Graphics ? "vertex" : "compute")}=0x{entry.VertexHash:X16} " + - $"variants={variants.Count}."); + if (!variants.CapWarned) + { + // Once per pipeline: the line is not formatted again for its later draws. + variants.CapWarned = true; + MetalV2Diagnostics.WarnOnce( + entry.Graphics ? "buffer-word-variant-cap" : "buffer-word-compute-variant-cap", + $"A pipeline {(entry.Graphics ? "drew" : "dispatched")} more buffer-word layouts than it keeps variants for; " + + $"the rest run generic: pipeline={entry.Id} {(entry.Graphics ? "vertex" : "compute")}=0x{entry.VertexHash:X16} " + + $"variants={variants.Count}."); + } + return 0; } @@ -559,8 +702,8 @@ private void QueueBufferWordVariant(MetalPipelineEntry entry, BufferWordVariants { if (_bufferWordBuilders is null) { - // Two builders: a variant waits behind the game's compiles anyway (EnterPrewarm). - _bufferWordBuilders = new MetalCompileThread[2]; + // Mostly file loads on a warm start; compiles are bounded by the lane's slots. + _bufferWordBuilders = new MetalCompileThread[Math.Max(1, BufferWordBuilderCount)]; for (var index = 0; index < _bufferWordBuilders.Length; index++) { _bufferWordBuilders[index] = MetalCompileThread.Start( @@ -605,6 +748,9 @@ private void BuildBufferWordVariant(MetalPipelineEntry entry, BufferWordVariants nint state = 0; nint vertexFunction = 0; nint pixelFunction = 0; + var tally = TallyOf(entry); + var build = new BufferWordBuild(this, tally); + long started = 0; try { if (_bufferWordStopping || Volatile.Read(ref variant.Status) != BufferWordVariantPending) @@ -614,63 +760,66 @@ private void BuildBufferWordVariant(MetalPipelineEntry entry, BufferWordVariants } BeforeBufferWordVariantBuild?.Invoke(); - using var slot = MetalCompileScheduler.Shared.EnterPrewarm(() => _bufferWordStopping); - if (!slot.Entered) - { - status = BufferWordVariantAbandoned; - return; - } - - // Made from now on: the bound keeps a module it made a pipeline from in the last - // seconds (TrimModules), as it does for the compiler threads' builds. - var now = System.Diagnostics.Stopwatch.GetTimestamp(); + started = System.Diagnostics.Stopwatch.GetTimestamp(); if (!entry.Graphics) { var compute = entry.ComputeDescription ?? throw new InvalidOperationException($"A compute buffer-word variant has no description: pipeline={entry.Id}."); - var module = RequireModule(compute.Program, onWorker: false); - module.LastUsedTicks = now; + if (!TryResidentModule(compute.Program, started, out var module)) + { + Interlocked.Increment(ref tally.Unresident); + return; + } + // Made as the module's own function is: with the LOD statistics switch off. var computeMip = module.Shader.UsesMipStatisticsConstant ? false : (bool?)null; // Its own library file in the archive (library and pipeline binary), made from // it again when a past session stored it. var archiveKey = ComputeBufferWordArchiveKey(module.ArchiveKey, variant.ArchiveKey); - if ((vertexFunction = RetainSpecializedFunction(module, computeMip, variants.Vertex, variant.Values, archiveKey)) == 0) + if ((vertexFunction = RetainSpecializedFunction(module, computeMip, variants.Vertex, variant.Values, archiveKey, build)) == 0) { status = BufferWordVariantCapped; return; } // No empty-kernel stand-in when the compiler fails: the generic state runs instead. - state = BuildComputePipelineState(vertexFunction, compute.Stage.Hash, archiveKey, variant: true); + state = BuildComputePipelineState(vertexFunction, compute.Stage.Hash, archiveKey, build); status = BufferWordVariantReady; return; } var description = entry.GraphicsDescription ?? throw new InvalidOperationException($"A buffer-word variant has no description: pipeline={entry.Id}."); - var vertexModule = RequireModule(description.VertexProgram, onWorker: false); - var pixelModule = description.PixelStage is not null && description.PixelProgram.IsValid - ? RequireModule(description.PixelProgram, onWorker: false) - : null; - vertexModule.LastUsedTicks = now; - if (pixelModule is not null) + MetalShaderModule? pixelModule = null; + var pixelProgram = description.PixelStage is not null && description.PixelProgram.IsValid; + if (!TryResidentModule(description.VertexProgram, started, out var vertexModule) || + (pixelProgram && !TryResidentModule(description.PixelProgram, started, out pixelModule)) || + (pixelModule is not null && variants.Pixel.Length == 0 && !GenericPixelFunctionReady(pixelModule, description))) { - pixelModule.LastUsedTicks = now; + // Building or rebuilding a module (or a function of it) here would hold its + // lock across a compile the GPU worker may need meanwhile: the draws of this + // layout stay generic, counted. + Interlocked.Increment(ref tally.Unresident); + return; } var vertexCount = variants.Vertex.Length; + var vertexValues = variant.Values[..vertexCount]; + var vertexFile = StageBufferWordArchiveKey(vertexModule.ArchiveKey, null, vertexValues); if (vertexCount != 0 && - (vertexFunction = RetainSpecializedFunction(vertexModule, null, variants.Vertex, variant.Values[..vertexCount])) == 0) + (vertexFunction = RetainSpecializedFunction(vertexModule, null, variants.Vertex, vertexValues, vertexFile, build)) == 0) { status = BufferWordVariantCapped; return; } + var pixelFile = default(UInt128); if (variants.Pixel.Length != 0) { var mip = pixelModule!.Shader.UsesMipStatisticsConstant ? description.LodStatistics : (bool?)null; - if ((pixelFunction = RetainSpecializedFunction(pixelModule, mip, variants.Pixel, variant.Values[vertexCount..])) == 0) + var pixelValues = variant.Values[vertexCount..]; + pixelFile = StageBufferWordArchiveKey(pixelModule.ArchiveKey, mip, pixelValues); + if ((pixelFunction = RetainSpecializedFunction(pixelModule, mip, variants.Pixel, pixelValues, pixelFile, build)) == 0) { status = BufferWordVariantCapped; return; @@ -679,7 +828,9 @@ private void BuildBufferWordVariant(MetalPipelineEntry entry, BufferWordVariants state = CreateRenderPipelineState( description, vertexModule, pixelModule, null, false, Mtl.ControlPointIndexTypeNone, out _, - new BufferWordPipeline(vertexFunction, pixelFunction, variant.Values, vertexCount, variant.ArchiveKey)); + new BufferWordPipeline( + vertexFunction, pixelFunction, variant.Values, vertexCount, variant.ArchiveKey, + vertexCount != 0 ? vertexFile : default, pixelFunction != 0 ? pixelFile : default, build)); status = BufferWordVariantReady; } catch (Exception exception) @@ -699,6 +850,7 @@ private void BuildBufferWordVariant(MetalPipelineEntry entry, BufferWordVariants } finally { + build.Dispose(); foreach (var function in (ReadOnlySpan)[vertexFunction, pixelFunction]) { if (function != 0) @@ -707,13 +859,73 @@ private void BuildBufferWordVariant(MetalPipelineEntry entry, BufferWordVariants } } - var tally = TallyOf(entry); - PublishBufferWordVariant(variant, status, state, tally); + if (started != 0) + { + Interlocked.Add(ref tally.WaitTicks, build.WaitTicks); + Interlocked.Add(ref tally.BuildTicks, System.Diagnostics.Stopwatch.GetTimestamp() - started - build.WaitTicks); + } + + if (PublishBufferWordVariant(variant, status, state, tally) && status == BufferWordVariantReady) + { + if (build.Source == BufferWordSource.Recompiled) + { + Interlocked.Increment(ref tally.FromRecompile); + } + else if (build.Source == BufferWordSource.Library) + { + Interlocked.Increment(ref tally.FromLibrary); + } + else + { + Interlocked.Increment(ref tally.FromFile); + } + + if (build.PipelineCompiled) + { + Interlocked.Increment(ref tally.PipelinesCompiled); + } + } + Interlocked.Decrement(ref tally.Pending); } } - private void PublishBufferWordVariant(BufferWordVariant variant, int status, nint state, BufferWordTally tally) + // The module of a program when its library and function are there now, marked as used + // (the bound keeps a module it made a pipeline from in the last seconds, TrimModules). + // A builder never compiles or waits for a module: RequireModule would run a queued + // compile or a rebuild here, holding the module while the GPU worker may need it. + private bool TryResidentModule(in ShaderProgram program, long now, out MetalShaderModule module) + { + if (!TryPublishedModule(program.Module, out module) || + module.Compiling is { IsCompletedSuccessfully: false } || + Volatile.Read(ref module.Function) == 0) + { + return false; + } + + module.LastUsedTicks = now; + return true; + } + + // Whether the pixel function a variant whose pixel stage declares no buffer words draws + // with is made already (CreateRenderPipelineState then only takes it): the generic + // pipeline made it, unless the module was released and built again since. + private static bool GenericPixelFunctionReady(MetalShaderModule module, GraphicsPipelineDescription description) + { + var counters = description.LodStatistics && module.Shader.UsesMipStatisticsConstant; + lock (module) + { + if (description.ColorRemap != 0) + { + return module.RemappedFunctions?.ContainsKey((description.ColorRemap, counters)) == true; + } + + return !counters || module.LodFunction != 0; + } + } + + // Whether this build's outcome is the variant's (false when the entry let go of it first). + private bool PublishBufferWordVariant(BufferWordVariant variant, int status, nint state, BufferWordTally tally) { if (status == BufferWordVariantReady) { @@ -731,7 +943,7 @@ private void PublishBufferWordVariant(BufferWordVariant variant, int status, nin } Interlocked.CompareExchange(ref variant.Status, BufferWordVariantAbandoned, BufferWordVariantPending); - return; + return false; } if (status == BufferWordVariantReady) @@ -746,18 +958,24 @@ private void PublishBufferWordVariant(BufferWordVariant variant, int status, nin { Interlocked.Increment(ref tally.Failed); } + + return true; } /// /// The function of specialized with , /// made once and kept with the module like its LOD statistics function, retained for the /// caller; zero once the module has made . - /// The function is made outside the module's lock: the worker takes it to release an idle + /// From the library file stored under when a past session + /// stored it (no compiler run); else, in a compile slot of the variants' lane, from a + /// library that can still be specialized (RetainSpecializableLibrary). A file that does + /// not load or holds no such function is counted and the function is built instead. The + /// function is made outside the module's lock: the worker takes it to release an idle /// module, and must not wait for a specialization meanwhile. /// private nint RetainSpecializedFunction( MetalShaderModule module, bool? mipStatistics, Gen5MslShader.BufferWordConstant[] declared, uint[] values, - UInt128 storedVariant = default) + UInt128 storedVariant, BufferWordBuild build) { var key = new SpecializationKey(mipStatistics, values); lock (module) @@ -765,8 +983,9 @@ private nint RetainSpecializedFunction( RequireResidentModule(module); if (module.SpecializedFunctions?.TryGetValue(key, out var known) == true) { - MetalNative.Send(known, SelBufferWordRetain); - return known; + MetalNative.Send(known.Function, SelBufferWordRetain); + build.Note(known.Source); + return known.Function; } if ((module.SpecializedFunctions?.Count ?? 0) >= MaxBufferWordSpecializationsPerModule) @@ -775,27 +994,46 @@ private nint RetainSpecializedFunction( } } - // A compute variant a past session stored (storedVariant): its file's library is the - // function as specialized with these values, and its pipeline binary is in the same - // file, so neither the front end nor the back end runs. Otherwise a library that still - // has the constants. - var library = storedVariant != default && MetalBinaryArchive.For(_device) is { } archive && archive.IsStored(storedVariant) - ? archive.TryLoadLibrary(storedVariant) - : 0; - if (library == 0) + // A variant a past session stored: its file's library is the function as specialized + // with these values (the key names them), and the pipeline's binary is in the + // archive, so neither the front end nor the back end runs. + nint function = 0; + nint error = 0; + var source = BufferWordSource.File; + if (storedVariant != default && MetalBinaryArchive.For(_device) is { } archive && archive.IsStored(storedVariant)) { - library = RetainSpecializableLibrary(module); - } + var stored = archive.TryLoadLibrary(storedVariant); + if (stored != 0) + { + try + { + function = NewTranslatedFunction(stored, module.Shader.EntryPoint, mipStatistics, declared, values, out error); + } + finally + { + MetalNative.SendVoid(stored, SelRelease); + } + } - nint function; - nint error; - try - { - function = NewTranslatedFunction(library, module.Shader.EntryPoint, mipStatistics, declared, values, out error); + if (function == 0) + { + // Rejected by the archive (deleted there) or without the function: built below. + Interlocked.Increment(ref build.Tally.FilesRejected); + } } - finally + + if (function == 0) { - MetalNative.SendVoid(library, SelRelease); + build.EnterCompile(); + var library = RetainSpecializableLibrary(module, build.Tally, out source); + try + { + function = NewTranslatedFunction(library, module.Shader.EntryPoint, mipStatistics, declared, values, out error); + } + finally + { + MetalNative.SendVoid(library, SelRelease); + } } if (function == 0) @@ -818,14 +1056,15 @@ private nint RetainSpecializedFunction( { // Another builder made the same one first. MetalNative.SendVoid(function, SelRelease); - function = winner; + (function, source) = winner; } else { - module.SpecializedFunctions.Add(key, function); + module.SpecializedFunctions.Add(key, (function, source)); } MetalNative.Send(function, SelBufferWordRetain); + build.Note(source); return function; } @@ -840,15 +1079,44 @@ static void RequireResidentModule(MetalShaderModule module) /// /// A library of whose functions can still be specialized, - /// retained for the caller. The module's own library is not one when it came from the - /// title's archive (TryCompileLibrary asks the archive first, so on every start after the - /// first): a library file holds the AIR of the function the pipeline that stored it was - /// made with, its constants already resolved, and a function made from it with buffer - /// words reads the shader data as the generic one does (measured: the values are ignored). - /// So the module's MSL is compiled once more, without asking the archive, on the variant - /// builder, and kept with the module. + /// retained for the caller. The module's own library is one when this process compiled it + /// from its MSL (LibraryFromSource): it is specialized directly. It is not one when it came + /// from the title's archive (TryCompileLibrary asks the archive first, so on every start + /// after the first): a library file holds the AIR of the function the pipeline that + /// stored it was made with, its constants already resolved, and a function made from it + /// with buffer words reads the shader data as the generic one does (measured: the values + /// are ignored). So the module's MSL is compiled once more, without asking the archive, on + /// the variant builder, and kept with the module. /// - private nint RetainSpecializableLibrary(MetalShaderModule module) + private nint RetainSpecializableLibrary(MetalShaderModule module, BufferWordTally tally, out BufferWordSource source) + { + lock (module) + { + if (module.Library != 0 && module.LibraryFromSource) + { + source = BufferWordSource.Library; + MetalNative.Send(module.Library, SelBufferWordRetain); + return module.Library; + } + + if (module.SpecializationLibrary != 0) + { + source = BufferWordSource.Recompiled; + MetalNative.Send(module.SpecializationLibrary, SelBufferWordRetain); + return module.SpecializationLibrary; + } + } + + source = BufferWordSource.Recompiled; + lock (module.SpecializationGate) + { + return CompileSpecializableLibrary(module, tally); + } + } + + // Under the module's SpecializationGate: the library another builder compiled meanwhile, + // or the module's MSL compiled once more. + private nint CompileSpecializableLibrary(MetalShaderModule module, BufferWordTally tally) { lock (module) { @@ -867,6 +1135,7 @@ private nint RetainSpecializableLibrary(MetalShaderModule module) $"The module's library could not be compiled for specialization: hash=0x{module.Hash:X16} {error}"); } + Interlocked.Increment(ref tally.Recompiles); lock (module) { if (module.Library == 0 || module.Function == 0) @@ -904,7 +1173,7 @@ private static void ReleaseSpecializedFunctions(MetalShaderModule module) return; } - foreach (var function in functions.Values) + foreach (var (function, _) in functions.Values) { MetalNative.SendVoid(function, SelRelease); } @@ -965,7 +1234,11 @@ private void StopBufferWordBuilders() // The PERF line's view: variants built, queued or compiling, and refused at a module's cap // or failed; then draws of programs that declare buffer words on a variant, on the generic // pipeline, and of those why: variant not ready, a pipeline's cap, a kind that stays - // generic, words not readable, or a variant that failed or was capped. + // generic, words not readable, or a variant that failed or was capped. Then, since the + // host started, where the built variants came from (their costliest function: their own + // archive files, this process's library, the module's MSL compiled again), the second MSL + // compiles, pipelines the archive missed, variant files rejected, variants refused for a + // module that was not resident, and the builders' time building and waiting for a slot. private string FormatBufferWordCounters() => FormatBufferWordCounters(_bufferWordRender, "draws"); // The same for compute pipelines, per dispatch, and the dispatches the compute switch @@ -984,5 +1257,11 @@ private static string FormatBufferWordCounters(BufferWordTally tally, string wor $"generic_capped={Interlocked.Exchange(ref tally.GenericCapped, 0)} " + $"generic_kind={Interlocked.Exchange(ref tally.GenericKind, 0)} " + $"generic_unreadable={Interlocked.Exchange(ref tally.GenericUnreadable, 0)} " + - $"generic_failed={Interlocked.Exchange(ref tally.GenericFailed, 0)}"); + $"generic_failed={Interlocked.Exchange(ref tally.GenericFailed, 0)} " + + $"from_file={Interlocked.Read(ref tally.FromFile)} from_library={Interlocked.Read(ref tally.FromLibrary)} " + + $"from_msl={Interlocked.Read(ref tally.FromRecompile)} msl_compiles={Interlocked.Read(ref tally.Recompiles)} " + + $"pipelines_compiled={Interlocked.Read(ref tally.PipelinesCompiled)} " + + $"files_rejected={Interlocked.Read(ref tally.FilesRejected)} unresident={Interlocked.Read(ref tally.Unresident)} " + + $"build_ms={Interlocked.Read(ref tally.BuildTicks) * 1000.0 / System.Diagnostics.Stopwatch.Frequency:F0} " + + $"wait_ms={Interlocked.Read(ref tally.WaitTicks) * 1000.0 / System.Diagnostics.Stopwatch.Frequency:F0}"); } diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Pipelines.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Pipelines.cs index a586ce846..15b6fe335 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Pipelines.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Pipelines.cs @@ -129,14 +129,26 @@ private sealed class MetalShaderModule public Dictionary<(uint Remap, bool LodStatistics), (nint Library, nint Function, UInt128 ArchiveKey)>? RemappedFunctions; // The functions specialized with buffer words for variant pipelines, made on the - // variant builder the first time a variant needs them (RetainSpecializedFunction). - public Dictionary? SpecializedFunctions; - - // The library those functions are made from: the module's MSL compiled again without - // asking the archive, whose library holds the function with its constants already - // resolved (RetainSpecializableLibrary). Made with the first variant that needs it. + // variant builder the first time a variant needs them (RetainSpecializedFunction), + // with where each came from. + public Dictionary? SpecializedFunctions; + + // The library those functions are made from when Library cannot be specialized: the + // module's MSL compiled again without asking the archive, whose library holds the + // function with its constants already resolved (RetainSpecializableLibrary). Made + // with the first variant that needs it. public nint SpecializationLibrary; + // Held by a variant builder while it compiles SpecializationLibrary, so a second + // builder waits for that compile instead of running another; never the GPU worker's + // (it takes the module itself, which no compile is made under). + public readonly object SpecializationGate = new(); + + // Whether Library was compiled from the module's MSL in this process (not loaded from + // the title's archive, nor taken from the library prewarm, whose origin is not + // known): its functions can still be specialized, and are, with no second compile. + public bool LibraryFromSource; + // The binary archive keys of the library and of the rectangle-list library (zero // with no archive): the pipeline made from them stores them under these. public UInt128 ArchiveKey; @@ -286,7 +298,7 @@ private void BuildModule(MetalShaderModule module, ShaderStage stage) // already compiled is taken from it instead. var library = CompileLibrary( shader.Source, module.Hash, shader.UsesPerVertexInputs, prewarmable: stage != ShaderStage.Compute, - out module.ArchiveKey, out module.SourceKey); + out module.ArchiveKey, out module.SourceKey, out var fromSource); Interlocked.Add(ref _libraryTicks, System.Diagnostics.Stopwatch.GetTimestamp() - started); var pool = MetalNative.objc_autoreleasePoolPush(); try @@ -301,6 +313,7 @@ private void BuildModule(MetalShaderModule module, ShaderStage stage) } module.Library = library; + module.LibraryFromSource = fromSource; Volatile.Write(ref module.Function, function); Interlocked.Increment(ref _residentModules); } @@ -364,7 +377,7 @@ private nint RequireRectangleFunction(MetalShaderModule module) var shader = module.Compiled.AcquireShader(); var library = CompileLibrary( Gen5MslRectangleList.BuildSource(shader), module.Hash, usesPerVertexInputs: false, prewarmable: true, - out module.RectangleArchiveKey, out module.RectangleSourceKey); + out module.RectangleArchiveKey, out module.RectangleSourceKey, out _); // The post-tessellation form carries the program's declarations: its buffer words // stay generic (MetalRenderHost.BufferWordVariants). var function = NewTranslatedFunction( @@ -391,6 +404,9 @@ private nint RequireRectangleFunction(MetalShaderModule module) Environment.GetEnvironmentVariable("SHARPEMU_METAL_V2_PIPELINE_DEDUPE") != "0"; private readonly MetalSharedHandleTable _libraries = new(); + // Whether the library registered under a source key was compiled from that source in + // this process (CompileLibraryUnshared); under _librariesGate, set with each registration. + private readonly Dictionary _librariesFromSource = new(); private readonly Dictionary _librariesBuilding = new(); private readonly object _librariesGate = new(); private long _moduleSameSource; @@ -398,14 +414,15 @@ private nint RequireRectangleFunction(MetalShaderModule module) // The library of this source, compiled by the first caller and shared with the rest. Any // thread: modules compile on the module pool. The caller owns one reference to give back - // through ReleaseLibrary. + // through ReleaseLibrary. fromSource: it was compiled from this MSL in this process. private nint CompileLibrary( - string source, ulong hash, bool usesPerVertexInputs, bool prewarmable, out UInt128 archiveKey, out UInt128 sourceKey) + string source, ulong hash, bool usesPerVertexInputs, bool prewarmable, out UInt128 archiveKey, out UInt128 sourceKey, + out bool fromSource) { if (!PipelineDedupe) { sourceKey = default; - return CompileLibraryUnshared(source, hash, usesPerVertexInputs, prewarmable, out archiveKey); + return CompileLibraryUnshared(source, hash, usesPerVertexInputs, prewarmable, out archiveKey, out fromSource); } sourceKey = MetalBinaryArchive.LibraryKey(source, usesPerVertexInputs); @@ -419,6 +436,7 @@ private nint CompileLibrary( { Interlocked.Increment(ref _moduleSameSource); archiveKey = sharedArchiveKey; + fromSource = _librariesFromSource.GetValueOrDefault(sourceKey); return shared; } @@ -440,13 +458,18 @@ private nint CompileLibrary( try { - var library = CompileLibraryUnshared(source, hash, usesPerVertexInputs, prewarmable, out archiveKey); + var library = CompileLibraryUnshared(source, hash, usesPerVertexInputs, prewarmable, out archiveKey, out fromSource); lock (_librariesGate) { if (!_libraries.Register(sourceKey, library, archiveKey, out var winner)) { ReleaseLibrary(library); library = winner; + fromSource = _librariesFromSource.GetValueOrDefault(sourceKey); + } + else + { + _librariesFromSource[sourceKey] = fromSource; } return library; @@ -474,8 +497,10 @@ private void ReleaseLibrary(nint library) } // Computes are left to the compute prewarm, which compiles them before the game runs. - private nint CompileLibraryUnshared(string source, ulong hash, bool usesPerVertexInputs, bool prewarmable, out UInt128 archiveKey) + private nint CompileLibraryUnshared( + string source, ulong hash, bool usesPerVertexInputs, bool prewarmable, out UInt128 archiveKey, out bool fromSource) { + fromSource = false; // The background prewarm gives way while the game compiles (MetalCompileScheduler). using var runtime = MetalCompileScheduler.Shared.Runtime(); var listed = prewarmable && MetalLibraryPrewarm.Active; @@ -489,12 +514,14 @@ private nint CompileLibraryUnshared(string source, ulong hash, bool usesPerVerte return prewarmed; } - var library = TryCompileLibrary(_device, source, usesPerVertexInputs, out var error, out archiveKey); + var library = TryCompileLibrary(_device, source, usesPerVertexInputs, out var error, out archiveKey, out var fromArchive); if (library == 0) { throw Fatal($"An MSL library failed to compile: hash=0x{hash:X16} {error}"); } + fromSource = !fromArchive; + if (listed) { MetalLibraryPrewarm.NoteCompiled(key, source, usesPerVertexInputs); @@ -513,16 +540,24 @@ internal static nint TryCompileLibrary(nint device, string source, bool usesPerV // front end to run (MetalBinaryArchive). The key comes back for storing it there later. // The static precompile, which knows the archive lacks it, does not ask. internal static nint TryCompileLibrary( - nint device, string source, bool usesPerVertexInputs, out string error, out UInt128 archiveKey, bool askArchive = true) + nint device, string source, bool usesPerVertexInputs, out string error, out UInt128 archiveKey, bool askArchive = true) => + TryCompileLibrary(device, source, usesPerVertexInputs, out error, out archiveKey, out _, askArchive); + + // fromArchive: the library is the archive's file, not compiled from the source here. + internal static nint TryCompileLibrary( + nint device, string source, bool usesPerVertexInputs, out string error, out UInt128 archiveKey, out bool fromArchive, + bool askArchive = true) { error = string.Empty; archiveKey = default; + fromArchive = false; if (askArchive && MetalBinaryArchive.For(device) is { } archive) { archiveKey = MetalBinaryArchive.LibraryKey(source, usesPerVertexInputs); var stored = archive.TryLoadLibrary(archiveKey); if (stored != 0) { + fromArchive = true; return stored; } } @@ -1141,7 +1176,7 @@ private nint CreateRenderPipelineState( } nint error = 0; - // A variant compiles at prewarm priority: its builder holds a prewarm slot. + // A variant compiles in its own lane, and only on an archive miss (below). using var runtime = bufferWords is null ? MetalCompileScheduler.Shared.Runtime() : default; var started = System.Diagnostics.Stopwatch.GetTimestamp(); var archive = MetalBinaryArchive.For(_device); @@ -1175,6 +1210,8 @@ private nint CreateRenderPipelineState( var missed = state == 0; if (missed) { + // A variant's builder takes a compile slot of the variants' lane only now. + bufferWords?.Build.EnterCompile(pipeline: true); state = NewRenderPipelineState(descriptor, mesh is not null, 0, ref error); if (state == 0) { @@ -1201,7 +1238,9 @@ private nint CreateRenderPipelineState( pixelLibraryKey, missed, pixelArchiveKey, - specialized: bufferWords is not null); + specialized: bufferWords is not null, + bufferWords?.VertexFile ?? default, + bufferWords?.PixelFile ?? default); } if (state == 0) @@ -1568,18 +1607,19 @@ public bool TryCreateComputePipeline(ComputePipelineDescription description, out private static bool _prefetchingPipeline; // Runs on the compile pool: MTLDevice is thread safe, and nothing here touches - // the host's own state. A buffer-word variant (variant) compiles at prewarm priority, as - // its builder holds a prewarm slot, and is never stood in for by the empty kernel: it - // fails instead, and its dispatches keep the generic state, which computes the same. - private nint BuildComputePipelineState(nint function, ulong hash, UInt128 archiveKey, bool variant = false) + // the host's own state. A buffer-word variant (variant) compiles in the variants' lane, + // which its builder enters only when the archive misses, and is never stood in for by the + // empty kernel: it fails instead, and its dispatches keep the generic state, which + // computes the same. + private nint BuildComputePipelineState(nint function, ulong hash, UInt128 archiveKey, BufferWordBuild? variant = null) { nint error = 0; - using var runtime = variant ? default : MetalCompileScheduler.Shared.Runtime(); + using var runtime = variant is not null ? default : MetalCompileScheduler.Shared.Runtime(); var started = System.Diagnostics.Stopwatch.GetTimestamp(); - var state = NewComputePipelineState(function, archiveKey, ref error); + var state = NewComputePipelineState(function, archiveKey, ref error, variant); if (state == 0) { - state = RecoverComputePipelineState(function, archiveKey, hash, ref error, emptyKernel: !variant); + state = RecoverComputePipelineState(function, archiveKey, hash, ref error, emptyKernel: variant is null); } Interlocked.Add(ref _pipelineTicks, System.Diagnostics.Stopwatch.GetTimestamp() - started); @@ -1595,7 +1635,7 @@ private nint BuildComputePipelineState(nint function, ulong hash, UInt128 archiv // A compute library's archive file holds its pipeline's binary too: that is asked // first, and a pipeline compiled here is stored with the library. - private nint NewComputePipelineState(nint function, UInt128 archiveKey, ref nint error) + private nint NewComputePipelineState(nint function, UInt128 archiveKey, ref nint error, BufferWordBuild? variant = null) { var archive = MetalBinaryArchive.For(_device); var stored = archive?.OpenLibraryArchive(archiveKey) ?? 0; @@ -1639,6 +1679,7 @@ private nint NewComputePipelineState(nint function, UInt128 archiveKey, ref nint } } + variant?.EnterCompile(pipeline: true); var compiled = MetalNative.Send( _device, MetalNative.Selector("newComputePipelineStateWithFunction:error:"), diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.SubsetJoin.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.SubsetJoin.cs index 5e00adc70..c4ca8c638 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.SubsetJoin.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.SubsetJoin.cs @@ -344,7 +344,7 @@ private bool PixelOutputsMovable(in ShaderProgram program) var slot = output < 8 ? (int)((remap >> (output * 4)) & 0xF) - 1 : -1; return slot < 0 ? match.Value : $"[[color({slot})"; }); - var library = CompileLibrary(source, module.Hash, shader.UsesPerVertexInputs, prewarmable: true, out var archiveKey, out _); + var library = CompileLibrary(source, module.Hash, shader.UsesPerVertexInputs, prewarmable: true, out var archiveKey, out _, out _); // Its buffer words stay generic (MetalRenderHost.BufferWordVariants). var function = NewTranslatedFunction(library, shader, mipStatistics: counters, out var error); if (function == 0) From ac81c83f316214ff4777fc0156ea11b0f0431190 Mon Sep 17 00:00:00 2001 From: kuba Date: Tue, 17 Nov 2026 00:55:27 +0000 Subject: [PATCH 161/178] [Tests] Render buffer-word variants from their files across archive sessions, stage keys, and the variant lane --- .../MetalBufferWordVariantTests.cs | 192 ++++++++++++++++++ .../MetalCompileSchedulerTests.cs | 33 ++- 2 files changed, 223 insertions(+), 2 deletions(-) diff --git a/tests/SharpEmu.Gpu.Metal.Tests/MetalBufferWordVariantTests.cs b/tests/SharpEmu.Gpu.Metal.Tests/MetalBufferWordVariantTests.cs index 3352673fc..a023982ca 100644 --- a/tests/SharpEmu.Gpu.Metal.Tests/MetalBufferWordVariantTests.cs +++ b/tests/SharpEmu.Gpu.Metal.Tests/MetalBufferWordVariantTests.cs @@ -139,6 +139,38 @@ public void AVariantPipelineIsNeverWrittenAsAModulesLibraryFile() Assert.Equal((vertex, pixel), MetalBinaryArchive.LibraryFileKeys(vertex, pixel, specialized: false)); Assert.Equal((default(UInt128), default(UInt128)), MetalBinaryArchive.LibraryFileKeys(vertex, pixel, specialized: true)); + // A variant's stages are written under their own keys, a module's under its own only. + var vertexFile = MetalRenderHost.StageBufferWordArchiveKey(vertex, null, [12, 0x1000]); + var pixelFile = MetalRenderHost.StageBufferWordArchiveKey(pixel, true, [8]); + Assert.Equal((vertexFile, pixelFile), MetalBinaryArchive.LibraryFileKeys(vertex, pixel, specialized: true, vertexFile, pixelFile)); + Assert.Equal((vertex, pixel), MetalBinaryArchive.LibraryFileKeys(vertex, pixel, specialized: false, vertexFile, pixelFile)); + } + + [Fact] + public void AStagesVariantFileKeyNamesItsModuleSwitchAndEveryValue() + { + var library = new UInt128(0x1111, 0x2222); + uint[] first = [12, 0x1000]; + UInt128 Key(UInt128 module, bool? mip, uint[] values) => MetalRenderHost.StageBufferWordArchiveKey(module, mip, values); + + var key = Key(library, null, first); + Assert.NotEqual(default, key); + Assert.NotEqual(library, key); + Assert.Equal(key, Key(library, null, [12, 0x1000])); + // Every value is in the key, and so are their order and count. + Assert.NotEqual(key, Key(library, null, [12, 0x1001])); + Assert.NotEqual(key, Key(library, null, [0x1000, 12])); + Assert.NotEqual(key, Key(library, null, [12, 0x1000, 0])); + // Another program's function of the same values is another file. + Assert.NotEqual(key, Key(new UInt128(0x3333, 0x4444), null, first)); + // No switch, the switch off, the switch on: three functions. + Assert.Equal(3, new[] { (bool?)null, false, true }.Select(mip => Key(library, mip, first)).Distinct().Count()); + // Not the files of the module's LOD statistics pair, a compute variant, or a pair key. + Assert.NotEqual(key, MetalBinaryArchive.LodStatisticsKey(library, counters: true)); + Assert.NotEqual(key, MetalRenderHost.ComputeBufferWordArchiveKey(library, key)); + // A module with no key and a stage with no buffer words store nothing. + Assert.Equal(default, Key(default, null, first)); + Assert.Equal(default, Key(library, true, [])); } [Fact] @@ -400,6 +432,166 @@ public void LayoutsPastThePipelinesCapDrawGenericAndAreCounted() } } + /// + /// A render variant built in one archive session is built in the next from its stage's + /// library file and the pipeline its pair is listed under: no MSL compiled (no library + /// missed the archive) and no pipeline compiled, with the values it was written with (the + /// variant draws what the generic pipeline draws, the layout's colour where the records + /// put it). With the variant files gone, the module's archive library cannot be + /// specialized, so its MSL is compiled once more and the variants are written again. Also + /// the bench of the three sources: the wall time to drain the builders' queue, per variant. + /// + [Fact] + public void TheNextHostBuildsRenderVariantsFromTheirFilesWithoutCompilingMsl() + { + if (!RequireDevice()) return; + const int Pipelines = 4; + var root = Path.Combine(Path.GetTempPath(), $"sharpemu-render-buffer-words-{Guid.NewGuid():N}"); + try + { + var cold = RunSession(root, Pipelines); + output.WriteLine($"cold: {cold}"); + var variants = Pipelines * MetalRenderHost.MaxBufferWordVariantsPerPipeline; + // This process compiled the modules from MSL: their libraries are specialized directly. + Assert.Equal((0L, (long)variants, 0L, 0L), (cold.Sources.FromFile, cold.Sources.FromLibrary, cold.Sources.FromRecompile, cold.Sources.Recompiles)); + // The two modules' files and one file per variant's vertex stage (the pixel stage declares none). + Assert.Equal(2 + variants, cold.Archive.LibrariesWritten); + + var warm = RunSession(root, Pipelines); + output.WriteLine($"warm: {warm}"); + Assert.Equal(((long)variants, 0L, 0L, 0L, 0L, 0L), (warm.Sources.FromFile, warm.Sources.FromLibrary, + warm.Sources.FromRecompile, warm.Sources.Recompiles, warm.Sources.PipelinesCompiled, warm.Sources.FilesRejected)); + // No library missed the archive (nothing compiled from MSL): the two modules' and + // every variant's from their files; every pipeline from the segments; nothing written. + Assert.Equal((2 + variants, 0, 0), (warm.Archive.LibraryHits, warm.Archive.LibraryMisses, warm.Archive.LibrariesWritten)); + Assert.Equal((1 + variants, 0), (warm.Archive.PipelineHits, warm.Archive.PipelineMisses)); + + // The variants' files go; the modules' stay. + var deleted = 0; + for (var pipeline = 0; pipeline < Pipelines; pipeline++) + { + for (var index = 0; index < MetalRenderHost.MaxBufferWordVariantsPerPipeline; index++) + { + var layout = BenchLayout(pipeline, index); + var key = MetalRenderHost.StageBufferWordArchiveKey( + MetalBinaryArchive.LibraryKey(VertexSource, usesPerVertexInputs: false), null, [layout.Stride, layout.Word3]); + var path = Path.Combine(warm.LibraryDirectory, key.ToString("x32", System.Globalization.CultureInfo.InvariantCulture) + MetalBinaryArchive.Extension); + if (File.Exists(path)) + { + File.Delete(path); + deleted++; + } + } + } + + Assert.Equal(variants, deleted); + var recompiled = RunSession(root, Pipelines); + output.WriteLine($"recompiled: {recompiled}"); + // One second compile per module (each pipeline's vertex program is a module of its own). + Assert.Equal((0L, 0L, (long)variants, (long)Pipelines), (recompiled.Sources.FromFile, recompiled.Sources.FromLibrary, + recompiled.Sources.FromRecompile, recompiled.Sources.Recompiles)); + Assert.Equal(variants, recompiled.Archive.LibrariesWritten); + + foreach (var (name, session) in new[] { ("cold (this process's library)", cold), ("warm (files)", warm), ("recompiled (MSL again)", recompiled) }) + { + output.WriteLine( + $"{name}: variants={variants} drain_ms={session.DrainMilliseconds:F1} " + + $"wall_ms_per_variant={session.DrainMilliseconds / variants:F2} " + + $"build_ms_per_variant={session.Sources.BuildMilliseconds / variants:F2} builders={MetalRenderHost.DefaultBufferWordBuilders}"); + } + } + finally + { + if (Directory.Exists(root)) + { + Directory.Delete(root, recursive: true); + } + } + } + + private readonly record struct Session( + (int LibraryHits, int LibraryMisses, int Rejected, int LibrariesWritten, + int PipelineHits, int PipelineMisses, int PipelinesAdded, int LoadedSegments) Archive, + (long FromFile, long FromLibrary, long FromRecompile, long Recompiles, long PipelinesCompiled, + long FilesRejected, long Unresident, double BuildMilliseconds) Sources, + double DrainMilliseconds, + string LibraryDirectory); + + // A layout of its own for each pipeline and index: the same records, another format word, + // so the pipelines' variants are distinct functions and distinct pipeline states. + private static VertexLayout BenchLayout(int pipeline, int index) => + Layout(Float32x2, 8, 0x100) with { Word3 = (Float32x2 << 12) | (uint)(0x100 + pipeline * 0x20 + index) }; + + // One archive session: every pipeline draws each of its layouts generic while the builders + // are held, then the builders drain the queue (timed), then each layout draws again through + // its variant, which must draw the same pixels. + private Session RunSession(string root, int pipelines) + { + var archive = MetalBinaryArchive.Open(root, Device.Value, "translator-a", 256L << 20); + Assert.True(archive.WaitLoaded(TimeSpan.FromSeconds(30))); + var previous = MetalBinaryArchive.Install(archive); + try + { + Session session; + using (var rig = new MetalPassRig(Device.Value, 1024 * 1024)) + using (var gate = new ManualResetEventSlim(false)) + { + rig.Host.BeforeBufferWordVariantBuild = () => gate.Wait(BuildTimeout); + var buffer = NewBuffer(BenchLayout(0, 0)); + try + { + var handles = Enumerable.Range(0, pipelines).Select(index => Pipeline(rig, 0x7400_0000UL + (ulong)index * 0x10)).ToArray(); + var generic = new byte[pipelines, MetalRenderHost.MaxBufferWordVariantsPerPipeline][]; + for (var pipeline = 0; pipeline < pipelines; pipeline++) + { + for (var index = 0; index < MetalRenderHost.MaxBufferWordVariantsPerPipeline; index++) + { + var layout = BenchLayout(pipeline, index); + generic[pipeline, index] = DrawInto(rig, handles[pipeline], FirstTarget, buffer, Stage(layout, unread: 0)); + AssertDrawn(generic[pipeline, index], layout); + } + } + + var variants = pipelines * MetalRenderHost.MaxBufferWordVariantsPerPipeline; + Assert.Equal(variants, rig.Host.BufferWordVariantsPending); + var started = System.Diagnostics.Stopwatch.GetTimestamp(); + gate.Set(); + Assert.True(rig.Host.WaitForBufferWordVariants(BuildTimeout)); + var drain = System.Diagnostics.Stopwatch.GetElapsedTime(started).TotalMilliseconds; + + var before = rig.Host.BufferWordCounters; + for (var pipeline = 0; pipeline < pipelines; pipeline++) + { + for (var index = 0; index < MetalRenderHost.MaxBufferWordVariantsPerPipeline; index++) + { + var layout = BenchLayout(pipeline, index); + Assert.Equal(generic[pipeline, index], DrawInto(rig, handles[pipeline], FirstTarget + 0x1000, buffer, Stage(layout, unread: 0))); + } + } + + var after = rig.Host.BufferWordCounters; + Assert.Equal((long)variants, after.Built); + Assert.Equal((long)variants, after.DrawsVariant - before.DrawsVariant); + Assert.Equal((0L, 0L), (after.Failed, after.Capped)); + session = new Session(default, rig.Host.BufferWordSources(), drain, archive.LibraryDirectory); + } + finally + { + gate.Set(); + MetalNative.SendVoid(buffer, MetalNative.Selector("release")); + } + } + + archive.Flush(wait: true); + return session with { Archive = archive.Counters }; + } + finally + { + MetalBinaryArchive.Install(previous); + archive.Dispose(); + } + } + private readonly record struct VertexLayout(uint Format, uint Stride, uint Word3Low) { public uint Word3 { get; init; } = (Format << 12) | Word3Low; diff --git a/tests/SharpEmu.Gpu.Metal.Tests/MetalCompileSchedulerTests.cs b/tests/SharpEmu.Gpu.Metal.Tests/MetalCompileSchedulerTests.cs index 9139cb0f8..3372ad13a 100644 --- a/tests/SharpEmu.Gpu.Metal.Tests/MetalCompileSchedulerTests.cs +++ b/tests/SharpEmu.Gpu.Metal.Tests/MetalCompileSchedulerTests.cs @@ -230,9 +230,38 @@ public void PrewarmWaitsAreCollectedOnTheThreadThatWaited() Assert.Equal(0, MetalCompileScheduler.TakeThreadPrewarmWait()); } - private static Task Enter(MetalCompileScheduler scheduler) => + // Buffer-word variants compile in a lane of their own: a prewarm holding every one of its + // slots does not hold them back, they hold none of its slots, and the game's compiles + // hold them back as they do the prewarm. + [Fact] + public void VariantCompilesHaveTheirOwnSlotsAndStillGiveWayToTheGame() + { + var scheduler = new MetalCompileScheduler(1, TimeSpan.Zero, Forever, variantSlots: 2); + using var prewarm = scheduler.EnterPrewarm(static () => false); + var first = scheduler.EnterVariant(static () => false); + Assert.True(first.Entered); + using var second = scheduler.EnterVariant(static () => false); + Assert.Equal((1, 2), (scheduler.PrewarmInFlight, scheduler.VariantInFlight)); + var third = Enter(scheduler, variant: true); + Assert.False(third.Wait(Held)); + + first.Dispose(); + Assert.True(third.Wait(Released)); + third.Result.Dispose(); + Assert.Equal(1, scheduler.VariantInFlight); + + scheduler.RuntimeStarted(); + var held = Enter(scheduler, variant: true); + Assert.False(held.Wait(Held)); + scheduler.RuntimeDone(); + Assert.True(held.Wait(Released)); + held.Result.Dispose(); + Assert.Equal(1, scheduler.PrewarmInFlight); + } + + private static Task Enter(MetalCompileScheduler scheduler, bool variant = false) => Task.Factory.StartNew( - () => scheduler.EnterPrewarm(static () => false), + () => variant ? scheduler.EnterVariant(static () => false) : scheduler.EnterPrewarm(static () => false), CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default); From 7d614ee9c4529cf93edde21781a08d8edf402f53 Mon Sep 17 00:00:00 2001 From: kuba Date: Tue, 17 Nov 2026 03:04:48 +0000 Subject: [PATCH 162/178] [Tests] Bench program resolution as N independent shards on N threads SHARPEMU_DS_SHARD_BENCH_OUTPUT captures the program takes of one worker round of the DS-shaped stream and replays their resolution (inputs, resolution in the host's concurrent-read scope, binding packets) on N shards, each a ShaderPipelineCache + RenderExecutor of its own, routed by a hash of the program pair (or of the job index). Reports jobs/s, ms per frame, thread CPU and wall per job, and the resolve memo mix per shard. Inert without the variable. --- .../Scenes/DsDrawCostBenchTests.Shards.cs | 425 ++++++++++++++++++ .../Scenes/DsDrawCostBenchTests.cs | 70 ++- 2 files changed, 492 insertions(+), 3 deletions(-) create mode 100644 tests/SharpEmu.Gpu.Metal.Tests/Scenes/DsDrawCostBenchTests.Shards.cs diff --git a/tests/SharpEmu.Gpu.Metal.Tests/Scenes/DsDrawCostBenchTests.Shards.cs b/tests/SharpEmu.Gpu.Metal.Tests/Scenes/DsDrawCostBenchTests.Shards.cs new file mode 100644 index 000000000..73d061884 --- /dev/null +++ b/tests/SharpEmu.Gpu.Metal.Tests/Scenes/DsDrawCostBenchTests.Shards.cs @@ -0,0 +1,425 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using System.Diagnostics; +using System.Reflection; +using SharpEmu.Gpu.Metal.V2; +using SharpEmu.HLE; +using SharpEmu.HLE.Diagnostics; +using SharpEmu.HLE.Host; +using SharpEmu.Libs.Agc; +using SharpEmu.Libs.Gpu; +using SharpEmu.Libs.Gpu.GpuCommands.Registers; +using SharpEmu.Libs.Gpu.Pipelines; +using SharpEmu.Libs.Gpu.Rendering; +using Xunit; + +namespace SharpEmu.Gpu.Metal.Tests.Scenes; + +/// +/// Does program resolution scale as N independent shards on N threads? Each shard is a ShaderPipelineCache (with its +/// program, materialization and resolve-memo caches and its _resolveGate) and a RenderExecutor over it, built as +/// CommandStreamTranslation builds the worker's, on a CpuContext of its own; a job goes to the shard a stable hash of +/// its vertex and pixel (or compute) program addresses names. The jobs are the program takes of one worker round, +/// replayed as ParallelProgramPrefetch.ResolveCore runs them (inputs, resolution inside the host's concurrent-read +/// scope, binding packets), with the round's descriptor-word and user-data churn applied between frames. What the +/// shards still share is the one Metal host (its concurrent-read ownership tests, assumption pool and packet pool), +/// the guest memory and the process-wide statics of the shader compiler and materializer. +/// +public sealed partial class DsDrawCostBenchTests +{ + private static readonly FieldInfo TranslationField = + typeof(MetalRenderHost).GetField("_translation", BindingFlags.Instance | BindingFlags.NonPublic)!; + + private static readonly FieldInfo TranslationExecutor = + typeof(AgcExports.CommandStreamTranslation).GetField("_executor", BindingFlags.Instance | BindingFlags.NonPublic)!; + + private static readonly FieldInfo TranslationContext = + typeof(AgcExports.CommandStreamTranslation).GetField("_context", BindingFlags.Instance | BindingFlags.NonPublic)!; + + private static readonly FieldInfo ExecutorHost = + typeof(RenderExecutor).GetField("_host", BindingFlags.Instance | BindingFlags.NonPublic)!; + + private static readonly Type PipelineCacheType = + typeof(GraphicsPrograms).Assembly.GetType("SharpEmu.Libs.Gpu.Pipelines.ShaderPipelineCache", throwOnError: true)!; + + private static readonly MethodInfo CreateHeaderRegistry = + typeof(AgcExports).GetMethod("CreateShaderHeaderRegistry", BindingFlags.Static | BindingFlags.NonPublic)!; + + // The resolve memo's per-thread counters (GraphicsResolveMemo), read on the shard's own thread. + private static readonly FieldInfo CounterLocal = + typeof(ThreadCounters).GetField("_local", BindingFlags.Static | BindingFlags.NonPublic)!; + + private static readonly FieldInfo CounterId = + typeof(ThreadCounter).GetField("_id", BindingFlags.Instance | BindingFlags.NonPublic)!; + + private static readonly Type MemoType = + typeof(GraphicsPrograms).Assembly.GetType("SharpEmu.Libs.Gpu.Pipelines.GraphicsResolveMemo", throwOnError: true)!; + + private static int[] MemoCounterIds(string field) + { + var value = MemoType.GetField(field, BindingFlags.Static | BindingFlags.NonPublic)!.GetValue(null)!; + return value is Array counters + ? counters.Cast().Select(counter => (int)CounterId.GetValue(counter)!).ToArray() + : [(int)CounterId.GetValue(value)!]; + } + + // hits, miss_by new, miss_by words, words_rebuilt, every miss, every uncacheable. + private const int MemoHits = 0, MemoNew = 1, MemoWords = 2, MemoRebuilt = 3, MemoMisses = 4, MemoUncacheable = 5, MemoCounts = 6; + + private static readonly int[][] MemoIds = + [ + MemoCounterIds("_hits"), + [MemoCounterIds("_misses")[0]], + [MemoCounterIds("_misses")[6]], + MemoCounterIds("_rebuilt"), + MemoCounterIds("_misses"), + MemoCounterIds("_uncacheable"), + ]; + + private static void ReadMemoCounters(Span into) + { + var local = (long[]?)CounterLocal.GetValue(null); + for (var index = 0; index < MemoCounts; index++) + { + var total = 0L; + if (local is not null) + { + foreach (var id in MemoIds[index]) total += local[id]; + } + + into[index] = total; + } + } + + private sealed record ComputeArguments(uint Initiator, uint GroupsX, uint GroupsY, uint GroupsZ, bool Indirect); + + private sealed class CapturedJob(RegisterBanks banks, GraphicsProgramInputs inputs, ComputeArguments? compute) + { + public readonly RegisterBanks Banks = banks; + public readonly GraphicsProgramInputs Inputs = inputs; + public readonly ComputeArguments? Compute = compute; + // The pixel user-data word holding the per-round pixel constants address (GameWords' new keys), or -1. + public int KeyWord = -1; + } + + // The worker's program takes, in order, while Jobs is set; everything else goes to the resolver it wraps. + private sealed class CapturingPrefetch(IProgramPrefetch inner) : IProgramPrefetch + { + public readonly IProgramPrefetch Inner = inner; + public List? Jobs; + + public bool TryTakeGraphics(RegisterBanks banks, in GraphicsProgramInputs inputs, out GraphicsPrograms programs) + { + Jobs?.Add(new CapturedJob(banks.Clone(), inputs, null)); + return Inner.TryTakeGraphics(banks, in inputs, out programs); + } + + public bool TryTakeCompute(RegisterBanks banks, uint dispatchInitiator, uint groupsX, uint groupsY, uint groupsZ, bool indirect, + out ComputeProgram program) + { + Jobs?.Add(new CapturedJob(banks.Clone(), GraphicsProgramInputs.Create(), + new ComputeArguments(dispatchInitiator, groupsX, groupsY, groupsZ, indirect))); + return Inner.TryTakeCompute(banks, dispatchInitiator, groupsX, groupsY, groupsZ, indirect, out program); + } + + public void NoteDispatchEffect() => Inner.NoteDispatchEffect(); + + public void NoteDispatchProgram(ComputeProgram program) => Inner.NoteDispatchProgram(program); + } + + // Marks the draws whose pixel user data carries the captured round's pixel constants copy (low address word), and + // with newEvery one draw in that many more of those that carry the plain pixel constants. + private static CapturedJob[] CapturedJobs(List jobs, uint keyLow, uint plainLow, int newEvery) + { + var draw = 0; + foreach (var job in jobs.Where(job => job.Compute is null)) + { + var scalars = job.Banks.Shader.Pixel.UserScalars; + var values = scalars.ValueSpan((int)scalars.Count); + var low = newEvery != 0 && draw++ % newEvery == newEvery / 2 && values.IndexOf(keyLow) < 0 ? plainLow : keyLow; + var at = values.IndexOf(low); + if (at >= 0 && values[(at + 1)..].IndexOf(low) < 0) job.KeyWord = at; + } + + return [.. jobs]; + } + + private static ulong Mix(ulong value) + { + value ^= value >> 33; + value *= 0xFF51AFD7ED558CCDUL; + value ^= value >> 33; + value *= 0xC4CEB53FE85A87DUL; + value ^= value >> 33; + return value; + } + + // SHARPEMU_DS_SHARD_BENCH_ROUTE=pair (default): by the program pair; =index: by a hash of the job's index (balanced + // to a few percent, and stable across frames here only because every frame replays the same stream). + private static int ShardOf(CapturedJob job, int index, int shards, bool byIndex) + { + if (byIndex) return (int)(Mix((ulong)index + 1) % (ulong)shards); + var shader = job.Banks.Shader; + var identity = job.Compute is not null + ? Mix(shader.Compute.Address ^ 0x5A5A5A5A5A5A5A5AUL) + : Mix(Mix(shader.Vertex.ExportAddress) ^ shader.Pixel.Address); + return (int)(identity % (ulong)shards); + } + + private sealed class Shard + { + public required RenderExecutor Executor; + public required CapturedJob[] Jobs; + public int Graphics; + public long[] CpuNanoseconds = []; + public long[] WallTicks = []; + public long[][] Memo = []; + public long[] Abandoned = []; + public Exception? Failure; + } + + private static void ResolveJob(MetalRenderHost host, IRenderHost renderHost, RenderExecutor executor, CapturedJob job, ref long abandoned) + { + IConcurrentResolveHost concurrent = host; + GraphicsPrograms? programs = null; + ComputeProgram? compute = null; + var pixelActive = false; + host.BeginConcurrentResolve(); + try + { + if (job.Compute is { } arguments) + { + compute = executor.ResolveComputeProgramAhead(job.Banks, arguments.Initiator, arguments.GroupsX, arguments.GroupsY, + arguments.GroupsZ, arguments.Indirect, out _); + } + else + { + var inputs = RenderExecutor.ProgramInputsOf(job.Banks, renderHost.FormatSupport, renderHost.Fatal, job.Inputs.Indexed, + job.Inputs.StartInstanceUserData); + pixelActive = inputs.PixelActive; + programs = executor.ResolveGraphicsPrograms(job.Banks, in inputs); + } + } + catch (Exception) + { + // As ParallelProgramPrefetch: the worker would resolve it itself. + abandoned++; + } + + var assumptions = host.EndConcurrentResolve(); + if (compute is { Available: true, Consumed: false, ImageCopy: null }) + { + concurrent.PrepareBindingsAhead(compute.Input.Stage, dispatch: true); + } + else if (programs is { Available: true }) + { + if (programs.VertexInput.Stage.Program is not null) concurrent.PrepareBindingsAhead(programs.VertexInput.Stage, dispatch: false); + if (pixelActive && programs.PixelInput.Stage.Program is not null) concurrent.PrepareBindingsAhead(programs.PixelInput.Stage, dispatch: false); + } + + host.ReleaseConcurrentAssumptions(assumptions); + } + + private object RunShardBench(SceneRig rig, object translation, string variation, CapturedJob[] jobs, Action prepareFrame, Action finishFrame, + int firstFrame) + { + int Setting(string name, int fallback) => + int.TryParse(Environment.GetEnvironmentVariable($"SHARPEMU_DS_SHARD_BENCH_{name}"), out var value) && value > 0 ? value : fallback; + var frames = Setting("FRAMES", 8); + var warmFrames = Setting("WARM_FRAMES", 4); + var byIndex = Environment.GetEnvironmentVariable("SHARPEMU_DS_SHARD_BENCH_ROUTE") == "index"; + var arms = (Environment.GetEnvironmentVariable("SHARPEMU_DS_SHARD_BENCH_ARMS") ?? "1,2,3,3,2,1,1,2,3,3,2,1") + .Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries).Select(int.Parse).ToArray(); + var liveContext = (CpuContext)TranslationContext.GetValue(translation)!; + var renderHost = (IRenderHost)ExecutorHost.GetValue(TranslationExecutor.GetValue(translation))!; + var host = rig.Host; + var graphicsJobs = jobs.Count(job => job.Compute is null); + var keyJobs = jobs.Count(job => job.KeyWord >= 0); + Output.WriteLine($"shard bench: {variation}, {jobs.Length} jobs a frame ({graphicsJobs} draws, {jobs.Length - graphicsJobs} dispatches, " + + $"{keyJobs} with per-frame pixel constants), route {(byIndex ? "index" : "pair")}, {warmFrames} warm + {frames} measured frames per arm, " + + $"arms {string.Join(",", arms)}, {Environment.ProcessorCount} cpus"); + + // Built as CommandStreamTranslation builds the worker's: a pipeline cache over the same host and backend, its own + // context and shader header registry (the registrations are process-wide), and an executor over it. + RenderExecutor NewShardExecutor() + { + var context = new CpuContext(liveContext.Memory, liveContext.TargetGeneration); + var registry = CreateHeaderRegistry.Invoke(null, [context])!; + var cache = (IShaderPipelineProvider)Activator.CreateInstance(PipelineCacheType, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, + null, [context, (IShaderPipelineHost)host, GuestGpu.Current, registry], null)!; + return new RenderExecutor(renderHost, cache); + } + + var frame = firstFrame; + var armResults = new List<(int Count, double JobsPerSecond, double WallMedianMs, Shard[] Shards, double[] Wall, long Contention, double BytesPerJob, int Gen0)>(); + foreach (var count in arms) + { + var routed = Enumerable.Range(0, count).Select(_ => new List()).ToArray(); + for (var index = 0; index < jobs.Length; index++) routed[ShardOf(jobs[index], index, count, byIndex)].Add(jobs[index]); + var total = warmFrames + frames; + var shards = routed.Select(list => new Shard + { + Executor = NewShardExecutor(), + Jobs = [.. list], + Graphics = list.Count(job => job.Compute is null), + CpuNanoseconds = new long[total], + WallTicks = new long[total], + Memo = Enumerable.Range(0, total).Select(_ => new long[MemoCounts]).ToArray(), + Abandoned = new long[total], + }).ToArray(); + using var start = new Barrier(count + 1); + using var done = new Barrier(count + 1); + var slot = 0; + var stop = false; + var threads = shards.Select((shard, index) => HostHelperThread.Start($"SharpEmu shard bench {index}", 16 * 1024 * 1024, () => + { + Span before = stackalloc long[MemoCounts]; + Span after = stackalloc long[MemoCounts]; + while (true) + { + start.SignalAndWait(); + if (Volatile.Read(ref stop)) return; + var at = Volatile.Read(ref slot); + try + { + ReadMemoCounters(before); + long abandoned = 0; + var cpuStarted = ThreadCpuNanoseconds(); + var wallStarted = Stopwatch.GetTimestamp(); + foreach (var job in shard.Jobs) ResolveJob(host, renderHost, shard.Executor, job, ref abandoned); + shard.WallTicks[at] = Stopwatch.GetTimestamp() - wallStarted; + shard.CpuNanoseconds[at] = (long)(ThreadCpuNanoseconds() - cpuStarted); + ReadMemoCounters(after); + for (var counter = 0; counter < MemoCounts; counter++) shard.Memo[at][counter] = after[counter] - before[counter]; + shard.Abandoned[at] = abandoned; + } + catch (Exception exception) + { + shard.Failure ??= exception; + } + + done.SignalAndWait(); + } + })).ToArray(); + + var wall = new double[total]; + var contentionBefore = 0L; + var allocatedBefore = 0L; + var gen0Before = 0; + for (var index = 0; index < total; index++) + { + if (index == warmFrames) + { + contentionBefore = Monitor.LockContentionCount; + allocatedBefore = GC.GetTotalAllocatedBytes(precise: false); + gen0Before = GC.CollectionCount(0); + } + + prepareFrame(frame++); + Volatile.Write(ref slot, index); + var started = Stopwatch.GetTimestamp(); + start.SignalAndWait(); + Assert.True(done.SignalAndWait(TimeSpan.FromMinutes(2)), "A shard did not finish its frame."); + wall[index] = (Stopwatch.GetTimestamp() - started) * 1000.0 / Stopwatch.Frequency; + finishFrame(); + } + + var contention = Monitor.LockContentionCount - contentionBefore; + var bytesPerJob = (GC.GetTotalAllocatedBytes(precise: false) - allocatedBefore) / (double)(frames * jobs.Length); + var gen0 = GC.CollectionCount(0) - gen0Before; + Volatile.Write(ref stop, true); + start.SignalAndWait(); + foreach (var thread in threads) Assert.True(thread.Join(TimeSpan.FromSeconds(30))); + foreach (var shard in shards) + { + if (shard.Failure is not null) throw new InvalidOperationException("A shard failed.", shard.Failure); + } + + var measured = wall[warmFrames..]; + var sorted = measured.Order().ToArray(); + var jobsPerSecond = frames * jobs.Length / (measured.Sum() / 1000.0); + armResults.Add((count, jobsPerSecond, sorted[sorted.Length / 2], shards, measured, contention, bytesPerJob, gen0)); + var line = new System.Text.StringBuilder(( + $"N={count}: {jobsPerSecond / 1000.0:F0}k jobs/s, wall median {sorted[sorted.Length / 2]:F2} ms/frame (min {sorted[0]:F2}), " + + $"largest shard {shards.Max(shard => shard.Jobs.Length) / (double)jobs.Length:P1} of jobs, lock contention {contention}, " + + $"{bytesPerJob:F0} B/job, gen0 {gen0};")); + for (var index = 0; index < shards.Length; index++) + { + var shard = shards[index]; + var cpu = shard.CpuNanoseconds[warmFrames..].Sum() / 1000.0 / Math.Max(1, frames * shard.Jobs.Length); + var shardWall = shard.WallTicks[warmFrames..].Sum() * 1e6 / Stopwatch.Frequency / Math.Max(1, frames * shard.Jobs.Length); + long Memo(int counter) => shard.Memo[warmFrames..].Sum(values => values[counter]); + var draws = Math.Max(1.0, (double)frames * shard.Graphics); + line.Append(( + $" [{index}: {shard.Jobs.Length} jobs ({shard.Graphics} draws), cpu {cpu:F2} us/job (own wall {shardWall:F2}), memo hit {Memo(MemoHits) / draws:P1} " + + $"words {Memo(MemoWords) / draws:P1} (rebuilt {Memo(MemoRebuilt) / draws:P1}) new {Memo(MemoNew) / draws:P1} " + + $"misses {Memo(MemoMisses) / draws:P1} uncacheable {Memo(MemoUncacheable) / draws:P1}, abandoned {shard.Abandoned[warmFrames..].Sum()}]")); + } + + Output.WriteLine(line.ToString()); + } + + // Per N: the medians over its arms; the speed-up against N=1 from those medians. + var byCount = armResults.GroupBy(arm => arm.Count).OrderBy(group => group.Key).Select(group => + { + static double Median(IEnumerable values) + { + var sorted = values.Order().ToArray(); + return sorted.Length % 2 == 1 ? sorted[sorted.Length / 2] : (sorted[sorted.Length / 2 - 1] + sorted[sorted.Length / 2]) / 2; + } + + var shardRows = Enumerable.Range(0, group.Key).Select(index => new + { + shard = index, + jobs = group.First().Shards[index].Jobs.Length, + draws = group.First().Shards[index].Graphics, + cpuMicrosecondsPerJob = Median(group.Select(arm => arm.Shards[index].CpuNanoseconds[warmFrames..].Sum() / 1000.0 / + Math.Max(1, frames * arm.Shards[index].Jobs.Length))), + wallMicrosecondsPerJob = Median(group.Select(arm => arm.Shards[index].WallTicks[warmFrames..].Sum() * 1e6 / Stopwatch.Frequency / + Math.Max(1, frames * arm.Shards[index].Jobs.Length))), + memoHitRate = Median(group.Select(arm => arm.Shards[index].Memo[warmFrames..].Sum(values => values[MemoHits]) / + Math.Max(1.0, (double)frames * arm.Shards[index].Graphics))), + memoWordsRate = Median(group.Select(arm => arm.Shards[index].Memo[warmFrames..].Sum(values => values[MemoWords]) / + Math.Max(1.0, (double)frames * arm.Shards[index].Graphics))), + memoNewRate = Median(group.Select(arm => arm.Shards[index].Memo[warmFrames..].Sum(values => values[MemoNew]) / + Math.Max(1.0, (double)frames * arm.Shards[index].Graphics))), + abandoned = group.Sum(arm => arm.Shards[index].Abandoned[warmFrames..].Sum()), + }).ToArray(); + return new + { + shards = group.Key, + arms = group.Count(), + jobsPerSecond = Median(group.Select(arm => arm.JobsPerSecond)), + jobsPerSecondByArm = group.Select(arm => Math.Round(arm.JobsPerSecond)).ToArray(), + wallMedianMsPerFrame = Median(group.Select(arm => arm.WallMedianMs)), + largestShardShare = group.First().Shards.Max(shard => shard.Jobs.Length) / (double)jobs.Length, + lockContention = group.Select(arm => arm.Contention).ToArray(), + bytesPerJob = Median(group.Select(arm => arm.BytesPerJob)), + gen0 = group.Sum(arm => arm.Gen0), + perShard = shardRows, + }; + }).ToArray(); + var single = byCount.FirstOrDefault(row => row.shards == 1)?.jobsPerSecond ?? double.NaN; + foreach (var row in byCount) + { + Output.WriteLine(( + $"summary N={row.shards}: {row.jobsPerSecond / 1000.0:F0}k jobs/s median of {row.arms} arms ({row.jobsPerSecond / single:F2}x N=1), " + + $"{row.wallMedianMsPerFrame:F2} ms/frame, largest shard {row.largestShardShare:P1}; per shard " + + string.Join(" ", row.perShard.Select(shard => + $"[{shard.shard}: {shard.jobs} jobs, cpu {shard.cpuMicrosecondsPerJob:F2} us/job (wall {shard.wallMicrosecondsPerJob:F2}), hit {shard.memoHitRate:P1} words {shard.memoWordsRate:P1} new {shard.memoNewRate:P1}]")))); + } + + return new + { + variation = $"{variation}/shards", + jobs = jobs.Length, + draws = graphicsJobs, + keyJobs, + frames, + warmFrames, + route = byIndex ? "index" : "pair", + byCount, + }; + } +} diff --git a/tests/SharpEmu.Gpu.Metal.Tests/Scenes/DsDrawCostBenchTests.cs b/tests/SharpEmu.Gpu.Metal.Tests/Scenes/DsDrawCostBenchTests.cs index 90179ad48..b5d35247a 100644 --- a/tests/SharpEmu.Gpu.Metal.Tests/Scenes/DsDrawCostBenchTests.cs +++ b/tests/SharpEmu.Gpu.Metal.Tests/Scenes/DsDrawCostBenchTests.cs @@ -22,7 +22,7 @@ namespace SharpEmu.Gpu.Metal.Tests.Scenes; /// load five sampled T#s, two storage T#s, two S#s and four V#s from a table of their own; each stores two images and /// a buffer of its own and samples what the dispatch sixteen before stored, a CS partial flush after every sixteenth. /// -public sealed class DsDrawCostBenchTests(ITestOutputHelper output) : SceneTestBase(output) +public sealed partial class DsDrawCostBenchTests(ITestOutputHelper output) : SceneTestBase(output) { private const uint Rgba8 = 56; private const uint Rgba32F = 77; @@ -249,14 +249,31 @@ public void MeasureDsShapedRecordingWhenRequested() { var path = Environment.GetEnvironmentVariable("SHARPEMU_DS_DRAW_BENCH_OUTPUT"); if (path is null) return; + Measure(path, shardBench: false); + } + + // SHARPEMU_DS_SHARD_BENCH_OUTPUT=: the resolver alone, as N independent shards on N threads (RunShardBench). + // Builds the game stream of _VARIATION (GameWords by default) with the SHARPEMU_DS_DRAW_BENCH_* settings, records + // _WARM rounds on the worker (20 by default here), captures the program resolutions the last of them takes, and + // replays those without the worker. + [Fact] + public void MeasureShardedResolutionWhenRequested() + { + var path = Environment.GetEnvironmentVariable("SHARPEMU_DS_SHARD_BENCH_OUTPUT"); + if (path is null) return; + Measure(path, shardBench: true); + } + + private void Measure(string path, bool shardBench) + { Environment.SetEnvironmentVariable("SHARPEMU_TEST_REQUIRE_DEVICE", "1"); int Setting(string name, int fallback) => int.TryParse(Environment.GetEnvironmentVariable($"SHARPEMU_DS_DRAW_BENCH_{name}"), out var value) && value > 0 ? value : fallback; var drawCount = Setting("DRAWS", 1024); var dispatchCount = Setting("DISPATCHES", 256); var rounds = Setting("ROUNDS", 40); - var warm = Setting("WARM", 150); - var only = Environment.GetEnvironmentVariable("SHARPEMU_DS_DRAW_BENCH_VARIATION"); + var warm = Setting("WARM", shardBench ? 20 : 150); + var only = Environment.GetEnvironmentVariable("SHARPEMU_DS_DRAW_BENCH_VARIATION") ?? (shardBench ? nameof(Variation.GameWords) : null); // _REBIND=n: every nth draw of a pass writes its targets and depth state again with the values they hold (no // flush), as a title's material binds do; 0 (the default) writes them only at a pass's first draw. var rebind = int.TryParse(Environment.GetEnvironmentVariable("SHARPEMU_DS_DRAW_BENCH_REBIND"), out var rebindEvery) && rebindEvery > 0 ? rebindEvery : 0; @@ -694,8 +711,54 @@ void ArmCopiedTables() long allAllocated = 0; long passes = 0; var collections = 0; + // The shard bench takes the resolutions of the worker's last warm round (its program takes, in order). + var translation = shardBench ? TranslationField.GetValue(rig.Host)! : null; + var liveExecutor = translation is not null ? (SharpEmu.Libs.Gpu.Rendering.RenderExecutor)TranslationExecutor.GetValue(translation)! : null; + var capture = liveExecutor is not null + ? new CapturingPrefetch(liveExecutor.Prefetch ?? throw new InvalidOperationException("The shard bench needs the parallel resolver.")) + : null; + if (capture is not null) liveExecutor!.Prefetch = capture; for (var round = 0; round < warm + rounds; round++) { + if (capture is not null) + { + if (round == warm) + { + liveExecutor!.Prefetch = capture.Inner; + Output.WriteLine($"captured round, worker resolver: {PrefetchCounters.Invoke(rig.Host, null)}"); + // SHARPEMU_DS_SHARD_BENCH_NEW_EVERY=n: one draw in n more takes per-frame pixel constants (a new key every + // frame), on top of the stream's every 32nd. + var newEvery = int.TryParse(Environment.GetEnvironmentVariable("SHARPEMU_DS_SHARD_BENCH_NEW_EVERY"), out var everyNew) && everyNew > 0 ? everyNew : 0; + var jobs = CapturedJobs(capture.Jobs!, Descriptors.Lo(pixelConstantCopies[(warm - 1) % PixelConstantCopies]), Descriptors.Lo(pixelConstants), newEvery); + results.Add(RunShardBench(rig, translation!, variation.ToString(), jobs, + frame => + { + // The replay resolves every job while the tables' copy is pending, so each read goes through to + // the copy's source: the churn is written there too (Demon's Souls' copy source changes per frame). + foreach (var (address, even, odd) in game.WordChurn ?? []) + { + rig.Memory.Write(address, frame % 2 == 0 ? even : odd); + if (copyWords != 0) rig.Memory.Write(copySource + (address - copyDestination), frame % 2 == 0 ? even : odd); + } + + foreach (var job in capture.Jobs!.Where(job => job.KeyWord >= 0)) + job.Banks.Shader.Pixel.UserScalars.Values[job.KeyWord] = Descriptors.Lo(pixelConstantCopies[frame % PixelConstantCopies]); + ArmCopiedTables(); + }, + () => + { + rig.Host.FlushCommandBuffer(); + rig.Drain(); + }, + firstFrame: warm)); + break; + } + + capture.Jobs = round == warm - 1 ? [] : null; + // The worker's own resolver counters over the captured round (the single-resolver mix in situ). + if (round == warm - 1) _ = PrefetchCounters.Invoke(rig.Host, null); + } + if (round == warm) { _ = SharpEmu.Libs.Gpu.Rendering.RenderRecorderStatistics.TakeInPlaceReport(); @@ -777,6 +840,7 @@ void ArmCopiedTables() } } + if (capture is not null) continue; var prefetch = (string)PrefetchCounters.Invoke(rig.Host, null)!; // The recorder's target reuse over the measured rounds, and the render passes of the last one. var inPlace = SharpEmu.Libs.Gpu.Rendering.RenderRecorderStatistics.TakeInPlaceReport(); From 91366b9e986b88b516c914431f4ae6fcec1ae2e1 Mon Sep 17 00:00:00 2001 From: kuba Date: Tue, 17 Nov 2026 03:50:48 +0000 Subject: [PATCH 163/178] [GPU] Resolve programs on N sharded resolver threads (SHARPEMU_RESOLVE_SHARDS, default 2) Each shard has its own queue, thread and resolve memo under its own gate; draws route by a hash of the memo-key fields (vertex address and user data, the pixel's when active), dispatches by compute address. The shared tier (program cache, vertex tables, translation, pipeline creation) stays under the pipeline cache's _resolveGate, taken only on a memo miss; cached-materialization revalidation takes it too. Ordering holds across shards: the finished count is the prefix over every shard's running or queued head, pause waits for all, caller and fallback resolutions run on the job's own shard. 1 restores the single resolver. Per-shard counts, resolve and CPU time and the shared-lock wait are in the prefetch counters' shards=(...) field. --- docs/macos/configuration.md | 1 + .../Gpu/Pipelines/GraphicsResolveMemo.cs | 4 +- .../Gpu/Pipelines/ShaderPipelineCache.cs | 228 ++++++++++++- .../Gpu/Pipelines/ShaderProgramCache.cs | 32 +- .../Gpu/Rendering/IShaderPipelineProvider.cs | 7 + .../Gpu/Rendering/ParallelProgramPrefetch.cs | 313 +++++++++++++----- .../Gpu/Rendering/RenderExecutor.Prefetch.cs | 8 + .../Gpu/Rendering/ResolveShards.cs | 113 +++++++ .../KeptStageInputsTests.ResolveShards.cs | 84 +++++ .../ParallelProgramPrefetchCallerTests.cs | 3 +- .../ParallelProgramPrefetchShardTests.cs | 267 +++++++++++++++ .../Rendering/RenderExecutorTestSupport.cs | 16 +- 12 files changed, 968 insertions(+), 108 deletions(-) create mode 100644 src/SharpEmu.Libs/Gpu/Rendering/ResolveShards.cs create mode 100644 tests/SharpEmu.Libs.Tests/Gpu/Pipelines/KeptStageInputsTests.ResolveShards.cs create mode 100644 tests/SharpEmu.Libs.Tests/Gpu/Rendering/ParallelProgramPrefetchShardTests.cs diff --git a/docs/macos/configuration.md b/docs/macos/configuration.md index a6f82ea6b..e4b952206 100644 --- a/docs/macos/configuration.md +++ b/docs/macos/configuration.md @@ -69,6 +69,7 @@ them for measurements or to isolate a problem. | `SHARPEMU_METAL_V2_BINARY_ARCHIVE_BUDGET_MB` | `8192` | Size bound of the archives on disk. | | `SHARPEMU_METAL_V2_ASYNC_PIPELINES` | on | `0` builds pipeline states on the GPU worker thread. | | `SHARPEMU_METAL_V2_ASYNC_LIBRARIES` | on | `0` compiles each shader library on the thread that needs it, not on the compile pool. | +| `SHARPEMU_RESOLVE_SHARDS` | `2` | Threads that resolve draw and dispatch programs ahead of the GPU worker, 1 to 8. Each has its own queue and its own part of the resolve memo; a draw always goes to the same one. `1` restores the single resolver. 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_METAL_V2_PIPELINE_LIMIT` | `8192` | Pipeline states kept before idle ones are released. `0` is unlimited. | | `SHARPEMU_METAL_V2_MODULE_LIMIT` | `2048` | The same for shader modules. | | `SHARPEMU_METAL_V2_SHADER_EVICTION` | on | `0` keeps every pipeline and module. | diff --git a/src/SharpEmu.Libs/Gpu/Pipelines/GraphicsResolveMemo.cs b/src/SharpEmu.Libs/Gpu/Pipelines/GraphicsResolveMemo.cs index bb11bdf45..fc1c1e9bb 100644 --- a/src/SharpEmu.Libs/Gpu/Pipelines/GraphicsResolveMemo.cs +++ b/src/SharpEmu.Libs/Gpu/Pipelines/GraphicsResolveMemo.cs @@ -83,8 +83,8 @@ internal enum ResolveMemoRebuildRefusal // The graphics programs of draws already resolved, keyed by everything their resolution reads from the registers and // the draw (ResolveKey), many per frame: a draw whose key matches an entry takes its programs once every guest read the -// full resolution makes still gives the same answer (ShaderPipelineCache.TryTakeResolveMemo). Used under the pipeline -// cache's _resolveGate only. +// full resolution makes still gives the same answer (ShaderPipelineCache.TryTakeResolveMemo). Used under its resolver +// shard's gate only (one memo per shard; with one shard that gate is the pipeline cache's _resolveGate). internal sealed class GraphicsResolveMemo { internal static readonly ResolveMemoMode DefaultMode = ParseMode(Environment.GetEnvironmentVariable("SHARPEMU_RESOLVE_MEMO")); diff --git a/src/SharpEmu.Libs/Gpu/Pipelines/ShaderPipelineCache.cs b/src/SharpEmu.Libs/Gpu/Pipelines/ShaderPipelineCache.cs index ced47c009..445048639 100644 --- a/src/SharpEmu.Libs/Gpu/Pipelines/ShaderPipelineCache.cs +++ b/src/SharpEmu.Libs/Gpu/Pipelines/ShaderPipelineCache.cs @@ -74,6 +74,7 @@ public ShaderPipelineCache(CpuContext context, IShaderPipelineHost host, IGuestG input.Stage = stage; return TryCreateComputePipeline(input, program, out _); }; + CreateShards(ResolveShards.Default); } public bool SupportsPrimitiveShaderMeshPipelines => _compiler.SupportsPrimitiveShaderMeshPipelines; @@ -289,8 +290,163 @@ private static ShaderSource SourceOf(ShaderHeaderEntry header, ulong hash, Shade // Program resolution runs on the render thread and on a thread resolving draws ahead of it; // the program, decode and materialization caches it updates are used under this lock only. // A pipeline lookup takes no lock, so it does not wait for a resolution. + // With resolver shards (ResolveShards), the shared tier only: what every shard's resolution shares (the program, + // decode and materialization caches, the vertex tables, the user data memos and last sources a full resolution + // fills, translation and links). A shard's memo hit or words rebuild does not take it; its miss does, inside the + // shard's own gate (lock order: shard gate, then this; never a shard gate while holding this). private readonly object _resolveGate = new(); + // One resolver shard: a part of the resolve memo's keys (ResolveShards.DrawRoute) and the lock its memo is used + // under. With one shard, its gate is _resolveGate itself and its memo _resolveMemo: everything as before. + private sealed class ResolveShard + { + public required object Gate; + public GraphicsResolveMemo? Memo; + } + + private ResolveShard[] _shards = []; + + private void CreateShards(int count) + { + var shards = new ResolveShard[count]; + shards[0] = new ResolveShard { Gate = count == 1 ? _resolveGate : new object(), Memo = _resolveMemo }; + for (var index = 1; index < count; index++) + { + shards[index] = new ResolveShard { Gate = new object(), Memo = NewMemoLike(_resolveMemo) }; + } + + _shards = shards; + // A memo hit's revalidation of a cached (not fast) materialization reads the materialization cache, which only + // the shared tier may use. + _programs.MaterializationGate = count == 1 ? null : _resolveGate; + } + + private static GraphicsResolveMemo? NewMemoLike(GraphicsResolveMemo? memo) => + memo is null ? null : new GraphicsResolveMemo(memo.Mode, GraphicsResolveMemo.DefaultCapacity) + { + Rebuild = memo.Rebuild, + HoldChurn = memo.HoldChurn, + AdmitSeen = memo.AdmitSeen, + }; + + // The resolver shards (IShaderPipelineProvider.ResolveShardCount), ResolveShards.Default unless a test or bench sets + // it before the first resolution. + public int ResolveShardCount + { + get => _shards.Length; + internal set + { + lock (_resolveGate) + { + CreateShards(Math.Clamp(value, 1, ResolveShards.Maximum)); + } + } + } + + public int ResolveShardOf(RegisterBanks banks, bool compute) => + _shards.Length == 1 ? 0 + : ResolveShards.ShardOf(compute ? ResolveShards.ComputeRoute(banks) : ResolveShards.DrawRoute(banks, RenderExecutor.PixelStageActive(banks)), + _shards.Length); + + // The sharded paths' use of the shared tier and of their own gates, for the prefetch line (TakeShardReport): shared + // gate takes and wait, shard gate wait (a shard's thread against the worker resolving a job of that shard), draws + // resolved through a shard's memo, and nested resolutions that went to the shared tier whole. + private static readonly ThreadCounter _sharedTakes = new(); + private static readonly ThreadCounter _sharedWaitTicks = new(); + private static readonly ThreadCounter _shardWaitTicks = new(); + private static readonly ThreadCounter _shardedDraws = new(); + private static readonly ThreadCounter _nestedShared = new(); + private static int _nestedReports; + + // Depth of sharded draw resolutions on this thread (any cache): a resolution inside one never waits for a shard gate. + [ThreadStatic] + private static int t_shardedDepth; + + public static string TakeShardReport() + { + static string Milliseconds(long ticks) => + (ticks * 1000.0 / System.Diagnostics.Stopwatch.Frequency).ToString("F1", System.Globalization.CultureInfo.InvariantCulture); + return FormattableString.Invariant($"shared_takes={_sharedTakes.Take()} shared_wait_ms={Milliseconds(_sharedWaitTicks.Take())} ") + + FormattableString.Invariant($"shard_wait_ms={Milliseconds(_shardWaitTicks.Take())} sharded_draws={_shardedDraws.Take()} ") + + FormattableString.Invariant($"nested_shared={_nestedShared.Take()} materialization_shared={ShaderProgramCache.TakeMaterializationGateTakes()}"); + } + + // The shared tier's gate; timed and counted with shards (with one shard, exactly the lock it always was). + private void EnterShared() + { + if (_shards.Length == 1) + { + Monitor.Enter(_resolveGate); + return; + } + + _sharedTakes.Increment(); + if (Monitor.TryEnter(_resolveGate)) + { + return; + } + + var started = System.Diagnostics.Stopwatch.GetTimestamp(); + Monitor.Enter(_resolveGate); + _sharedWaitTicks.Add(System.Diagnostics.Stopwatch.GetTimestamp() - started); + } + + // A full resolution under the shared tier (with one shard the caller already holds it: re-entered). + private GraphicsPrograms ResolveFullShared(RegisterBanks banks, ReadOnlySpan targetExportMapping, in KeptGraphicsFlags flags) + { + EnterShared(); + try + { + return ResolveFull(banks, targetExportMapping, flags); + } + finally + { + Monitor.Exit(_resolveGate); + } + } + + // A draw through its shard's memo, under the shard's gate; a miss takes the shared tier inside (ResolveThroughMemo). + private GraphicsPrograms GetGraphicsProgramsSharded(RegisterBanks banks, ReadOnlySpan targetExportMapping, in KeptGraphicsFlags flags) + { + var shard = _shards[ResolveShards.ShardOf(ResolveShards.DrawRoute(banks, flags.PixelActive), _shards.Length)]; + using var waitScope = RenderPhaseProfile.MeasureDetail(RenderPhaseProfile.Phase.GraphicsResolveLockWait); + if (!Monitor.TryEnter(shard.Gate)) + { + var started = System.Diagnostics.Stopwatch.GetTimestamp(); + Monitor.Enter(shard.Gate); + _shardWaitTicks.Add(System.Diagnostics.Stopwatch.GetTimestamp() - started); + } + + t_shardedDepth++; + try + { + using var workScope = RenderPhaseProfile.MeasureDetail(RenderPhaseProfile.Phase.ProgramPreparation); + _shardedDraws.Increment(); + return ResolveThroughMemo(shard.Memo!, banks, targetExportMapping, flags); + } + finally + { + t_shardedDepth--; + Monitor.Exit(shard.Gate); + } + } + + // A draw resolved inside another resolution on this thread (a guest read that runs deferred work), with shards: it + // must not wait for a shard gate while this thread holds the shared tier or another shard's gate, so it resolves in + // full under the shared tier and leaves every memo alone. Counted and named once; the programs are the same. + private GraphicsPrograms ResolveNestedShared(RegisterBanks banks, ReadOnlySpan targetExportMapping, in KeptGraphicsFlags flags) + { + _nestedShared.Increment(); + if (Interlocked.Increment(ref _nestedReports) == 1) + { + Console.Error.WriteLine("[GPU][PREFETCH] a draw resolved inside another resolution on one thread: resolved in full on the shared tier, " + + $"not through a resolver shard's memo (vs=0x{banks.Shader.Vertex.ExportAddress:X16} ps=0x{banks.Shader.Pixel.Address:X16}; counted as nested_shared)"); + } + + _graphicsResolved.Increment(); + return ResolveFullShared(banks, targetExportMapping, flags); + } + // The draw's programs (IShaderPipelineProvider). A draw whose registers, user data, targets and resolved // inputs are those of the last draw this thread resolved keeps its programs after their resources revalidate // (TryKeepGraphicsPrograms); anything else resolves them again. @@ -307,8 +463,17 @@ public GraphicsPrograms GetGraphicsPrograms( var vertex = banks.Shader.Vertex; var pixel = banks.Shader.Pixel; var context = banks.Context; + if (_shards.Length > 1 && _resolveMemo is { Mode: ResolveMemoMode.On or ResolveMemoMode.Verify }) + { + var shardedFlags = new KeptGraphicsFlags(pixelActive, depthBound, depthAspectBound, stencilAspectBound, triangleList, startInstanceUserData); + return t_shardedDepth != 0 || Monitor.IsEntered(_resolveGate) + ? ResolveNestedShared(banks, targetExportMapping, shardedFlags) + : GetGraphicsProgramsSharded(banks, targetExportMapping, shardedFlags); + } + using var waitScope = RenderPhaseProfile.MeasureDetail(RenderPhaseProfile.Phase.GraphicsResolveLockWait); - lock (_resolveGate) + EnterShared(); + try { using var workScope = RenderPhaseProfile.MeasureDetail(RenderPhaseProfile.Phase.ProgramPreparation); var flags = new KeptGraphicsFlags(pixelActive, depthBound, depthAspectBound, stencilAspectBound, triangleList, startInstanceUserData); @@ -340,6 +505,10 @@ public GraphicsPrograms GetGraphicsPrograms( if (shadowMiss) _resolveMemo!.Store(); return programs; } + finally + { + Monitor.Exit(_resolveGate); + } } // Shader header registrations are in the stamp too: a header registered at a code address changes what a lookup there @@ -365,6 +534,7 @@ internal ResolveMemoMode ResolveMemoMode lock (_resolveGate) { _resolveMemo = value == ResolveMemoMode.Off ? null : new GraphicsResolveMemo(value, GraphicsResolveMemo.DefaultCapacity); + CreateShards(_shards.Length); } } } @@ -378,6 +548,7 @@ internal bool ResolveMemoRebuild lock (_resolveGate) { if (_resolveMemo is { } memo) memo.Rebuild = value; + CreateShards(_shards.Length); } } } @@ -391,6 +562,7 @@ internal bool ResolveMemoHoldChurn lock (_resolveGate) { if (_resolveMemo is { } memo) memo.HoldChurn = value; + CreateShards(_shards.Length); } } } @@ -404,6 +576,7 @@ internal bool ResolveMemoAdmitSeen lock (_resolveGate) { if (_resolveMemo is { } memo) memo.AdmitSeen = value; + CreateShards(_shards.Length); } } } @@ -498,22 +671,32 @@ private GraphicsPrograms ResolveThroughMemo(GraphicsResolveMemo memo, RegisterBa } _graphicsResolved.Increment(); - var deviceDataGeneration = DeviceDataLoads.Generation; - var contentEpoch = _programs.ContentEpoch; - var linkedLookups = _programs.LinkedLookups; - var tablesGeneration = _vertexTables.Generation; - var programs = ResolveFull(banks, targetExportMapping, flags); - if (cacheable && memo.FillSerial != fillSerial) + // The miss: the full resolution and its store read and fill the shared tier (the last sources StoreResolveMemo + // reads are the ones this resolution's PrepareSource left), so both run under it (re-entered with one shard). + EnterShared(); + try { - // The memo holds another draw's key now: this result has no key to be stored under. - GraphicsResolveMemo.NoteUncacheable(ResolveMemoUncacheable.Changed); + var deviceDataGeneration = DeviceDataLoads.Generation; + var contentEpoch = _programs.ContentEpoch; + var linkedLookups = _programs.LinkedLookups; + var tablesGeneration = _vertexTables.Generation; + var programs = ResolveFull(banks, targetExportMapping, flags); + if (cacheable && memo.FillSerial != fillSerial) + { + // The memo holds another draw's key now: this result has no key to be stored under. + GraphicsResolveMemo.NoteUncacheable(ResolveMemoUncacheable.Changed); + } + else if (cacheable) + { + StoreResolveMemo(memo, banks, programs, flags.PixelActive, deviceDataGeneration, contentEpoch, linkedLookups, tablesGeneration); + } + + return programs; } - else if (cacheable) + finally { - StoreResolveMemo(memo, banks, programs, flags.PixelActive, deviceDataGeneration, contentEpoch, linkedLookups, tablesGeneration); + Monitor.Exit(_resolveGate); } - - return programs; } private GraphicsPrograms ResolveFull(RegisterBanks banks, ReadOnlySpan targetExportMapping, in KeptGraphicsFlags flags) => @@ -604,6 +787,14 @@ private GraphicsPrograms ResolveFull(RegisterBanks banks, ReadOnlySpan 1 && (entry.ContentEpoch != _programs.ContentEpoch || entry.TablesGeneration != _vertexTables.Generation)) + { + return ResolveMemoMiss.Epoch; + } + if (!stageRebuilt) { taken = programs; @@ -849,7 +1040,7 @@ private bool TryReadMemoTables(ShaderSource source, VertexInputInfo resolved, ou private GraphicsPrograms VerifyResolveMemo(GraphicsResolveMemo memo, GraphicsResolveMemo.Entry entry, GraphicsPrograms memoPrograms, ulong fingerprint, RegisterBanks banks, ReadOnlySpan targetExportMapping, in KeptGraphicsFlags flags) { - var full = ResolveFull(banks, targetExportMapping, flags); + var full = ResolveFullShared(banks, targetExportMapping, flags); GraphicsResolveMemo.NoteVerified(); var difference = GraphicsProgramsComparer.Difference(memoPrograms, full); if (difference is null) @@ -881,7 +1072,7 @@ private GraphicsPrograms VerifyResolveMemo(GraphicsResolveMemo memo, GraphicsRes return full; } - var again = ResolveFull(banks, targetExportMapping, flags); + var again = ResolveFullShared(banks, targetExportMapping, flags); if (GraphicsProgramsComparer.Difference(memoPrograms, again) is not { } againDifference) { GraphicsResolveMemo.NoteVerifyRaced(ResolveMemoVerifyRace.CameAndWent); @@ -2005,7 +2196,8 @@ public ComputeProgram GetComputeProgram(RegisterBanks banks, uint dispatchInitia refusal = ComputePrefetchRefusal.None; var compute = banks.Shader.Compute; using var waitScope = RenderPhaseProfile.MeasureDetail(RenderPhaseProfile.Phase.ComputeResolveLockWait); - lock (_resolveGate) + EnterShared(); + try { using var workScope = RenderPhaseProfile.MeasureDetail(RenderPhaseProfile.Phase.ProgramPreparation); if (retry is not null) @@ -2087,6 +2279,10 @@ public ComputeProgram GetComputeProgram(RegisterBanks banks, uint dispatchInitia ? Ahead(program, kept.Kernel, source, out refusal) : WithPrediction(program, kept.Kernel, source, systemRegisters, compute, dimensionX, dimensionY, dimensionZ, indirect); } + finally + { + Monitor.Exit(_resolveGate); + } } // A program resolved ahead stands for the dispatch's own only where the dispatch would take it unchanged: diff --git a/src/SharpEmu.Libs/Gpu/Pipelines/ShaderProgramCache.cs b/src/SharpEmu.Libs/Gpu/Pipelines/ShaderProgramCache.cs index e34a0aa97..bcfdf0e2d 100644 --- a/src/SharpEmu.Libs/Gpu/Pipelines/ShaderProgramCache.cs +++ b/src/SharpEmu.Libs/Gpu/Pipelines/ShaderProgramCache.cs @@ -353,6 +353,34 @@ private sealed record PendingTranslation(ProgramSourceEntry Entry, ResourceSpeci _spirvDumpEnabled || ReadLog is not null || Diagnostics.GpuReadTrace.Enabled || SharpEmu.Libs.Gpu.Images.ImageClearTrace.Enabled || RenderTrace.Enabled; + // With resolver shards (ShaderPipelineCache.ResolveShardCount above 1), the shared tier's gate: a memo hit revalidates + // outside it, and a snapshot of the materialization cache (not single-threaded: lookups fill and refresh its entries) + // is revalidated under it. Null with one shard, where every caller already holds that gate. + internal object? MaterializationGate { get; set; } + + private static long _materializationGateTakes; + + internal static long TakeMaterializationGateTakes() => Interlocked.Exchange(ref _materializationGateTakes, 0); + + private bool RevalidateMaterialization(ResourceSnapshot snapshot) + { + if (Materializations is not { } materializations) + { + return false; + } + + if (MaterializationGate is not { } gate) + { + return materializations.Revalidate(snapshot, _readResidentGuestBytes); + } + + Interlocked.Increment(ref _materializationGateTakes); + lock (gate) + { + return materializations.Revalidate(snapshot, _readResidentGuestBytes); + } + } + public bool Revalidate(in ShaderStageResources stage) { if (stage.Program is null) @@ -371,7 +399,7 @@ public bool Revalidate(in ShaderStageResources stage) throw GpuFatal.VerifyFailed(DescribeMismatch(mismatch)); } - var current = fast ?? (Materializations is { } materializations && materializations.Revalidate(stage.Resources, _readResidentGuestBytes)); + var current = fast ?? RevalidateMaterialization(stage.Resources); var outcome = current ? MaterializationTally.Outcome.KeptRevalidated : fast is not null && ResourceMaterializer.LastRevalidateRefused ? MaterializationTally.Outcome.RevalidateRefused : MaterializationTally.Outcome.KeptStale; @@ -419,7 +447,7 @@ public ResourceMaterializer.FastRevalidation RevalidateOrRebuild(in ShaderStageR if (fast == ResourceMaterializer.FastRevalidation.NotFast) { // A cached materialization: revalidated as before, never rebuilt here. - var current = Materializations is { } materializations && materializations.Revalidate(stage.Resources, _readResidentGuestBytes); + var current = RevalidateMaterialization(stage.Resources); MaterializationTally.Note(current ? MaterializationTally.Outcome.KeptRevalidated : MaterializationTally.Outcome.KeptStale, MaterializationTally.ElapsedTicks(started), stage.Resources); return current ? ResourceMaterializer.FastRevalidation.Current : ResourceMaterializer.FastRevalidation.NotFast; diff --git a/src/SharpEmu.Libs/Gpu/Rendering/IShaderPipelineProvider.cs b/src/SharpEmu.Libs/Gpu/Rendering/IShaderPipelineProvider.cs index 4670c791f..c8314dd0c 100644 --- a/src/SharpEmu.Libs/Gpu/Rendering/IShaderPipelineProvider.cs +++ b/src/SharpEmu.Libs/Gpu/Rendering/IShaderPipelineProvider.cs @@ -173,6 +173,13 @@ public interface IShaderPipelineProvider // under another stamp may hold the entry a lookup made now would not find (ParallelProgramPrefetch refuses it). ProgramStateStamp ProgramState => default; + // How many resolver shards the provider's resolution state is split into (ResolveShards): ParallelProgramPrefetch + // runs one resolving thread per shard. 1 resolves everything under one lock, as before. + int ResolveShardCount => 1; + + // The shard a draw's (or a dispatch's) resolution runs under: a stable function of the provider's per-shard key. + int ResolveShardOf(RegisterBanks banks, bool compute) => 0; + // Optional capture of rejected stage inputs; it never admits or executes the draw. void RecordUnsupportedGraphics(VertexStageRegisters vertex, ContextRegisters context) { } diff --git a/src/SharpEmu.Libs/Gpu/Rendering/ParallelProgramPrefetch.cs b/src/SharpEmu.Libs/Gpu/Rendering/ParallelProgramPrefetch.cs index 63d21100d..364133c66 100644 --- a/src/SharpEmu.Libs/Gpu/Rendering/ParallelProgramPrefetch.cs +++ b/src/SharpEmu.Libs/Gpu/Rendering/ParallelProgramPrefetch.cs @@ -8,9 +8,9 @@ namespace SharpEmu.Libs.Gpu.Rendering; -// Resolves the programs of deferred draws on a worker thread, in issue order, while the render -// thread interprets and records. The render thread takes a result for the draw it runs only when -// the resolution completed, used the inputs the draw derives and still matches the host's +// Resolves the programs of deferred draws on resolving threads (one per resolver shard, SHARPEMU_RESOLVE_SHARDS), each +// in issue order of its own jobs, while the render thread interprets and records. The render thread takes a result for +// the draw it runs only when the resolution completed, used the inputs the draw derives and still matches the host's // GPU-ownership state; otherwise it resolves the draw itself. public sealed class ParallelProgramPrefetch : IProgramPrefetch, IDisposable { @@ -31,6 +31,8 @@ public sealed class Job(RegisterBanks banks, long gate, bool indexed = false, in internal long ResolveTicks; // The jobs submitted before this one. internal long Index; + // The resolver shard whose queue holds it (ResolveShards): its resolution runs under that shard's state. + internal int Shard; // 0 queued, 1 resolved, 2 abandoned. internal volatile int State; // The resolving thread (or the caller) has taken it from the queue; it found its gate still closed when it got to it. @@ -246,19 +248,44 @@ public bool Matches(uint dispatchInitiator, uint groupsX, uint groupsY, uint gro DispatchInitiator == dispatchInitiator && GroupsX == groupsX && GroupsY == groupsY && GroupsZ == groupsZ && Indirect == indirect; } private readonly object _lock = new(); - private readonly Queue _queue = new(); - private readonly SharpEmu.HLE.Host.HostHelperThread _thread; + + // One resolving thread and its FIFO queue per resolver shard (ResolveShards, IShaderPipelineProvider.ResolveShardCount): + // a job goes to the queue of the shard its provider names (ResolveShardOf), and each shard resolves its own jobs in + // submission order, one at a time, its thread or the caller. Jobs of different shards finish out of order; _finished + // is the finished prefix over all of them (FinishedPrefix), so whatever waits for the jobs before an item waits for + // exactly those. Everything here is under _lock unless read with Volatile as a hint. With one shard, the single + // resolver as before. + private sealed class ResolverShard(int index) + { + public readonly int Index = index; + public readonly Queue Queue = new(); + public SharpEmu.HLE.Host.HostHelperThread? Thread; + // A resolution of this shard's head runs (its thread's or the caller's), and the job it resolves. + public bool Running; + public Job? Resolving; + // The shard's thread owns the head even while it releases the lock to wait for its gate. + public bool WorkerClaimed; + // The shard's thread waits for jobs or an active caller. + public bool IdleForJobs; + // Set while the shard's thread sleeps because of a pause. + public bool WaitingOnPause; + // The gate the shard's thread sleeps on; long.MaxValue while it does not. + public long SleepingOnGate = long.MaxValue; + // Its thread only: jobs taken (allocation sampling, resolver_jobs). + public long ResolverJobs; + // Since the last report: jobs its thread or the caller resolved, and its thread's resolving time (resolve_ms). + public long Resolved; + public long ResolveTicks; + public ulong ThreadId; + public long LastCpu = -1; + } + + private readonly ResolverShard[] _shards; private int _outstanding; + // The finished prefix: every job with a lower Index is finished (FinishedPrefix). private long _finished; private long _executedGate; - // The gate the worker sleeps on; long.MaxValue while it does not. - private long _sleepingOnGate = long.MaxValue; private bool _paused; - // Set while the worker sleeps because of a pause, under _lock. - private bool _waitingOnPause; - private bool _running; - // The worker owns the head even while it releases the lock to wait for its gate. - private bool _workerClaimed; private readonly bool _allowCallerResolution; // Long bursts give the resolver useful lead; racing it for each head adds handoffs. // Short queues are the query/barrier pattern where the renderer otherwise waits @@ -279,9 +306,81 @@ internal ParallelProgramPrefetch(RenderExecutor executor, IRenderHost host, ICon _fatal = host.Fatal; _concurrent = concurrent; _allowCallerResolution = allowCallerResolution; - // The worker waits on this thread per draw: it runs at the worker's class, with the - // worker's stack, since it resolves what the worker would resolve itself. - _thread = SharpEmu.HLE.Host.HostHelperThread.Start("SharpEmu program resolve", 16 * 1024 * 1024, Run); + var count = Math.Clamp(executor.ResolveShardCount, 1, ResolveShards.Maximum); + _shards = new ResolverShard[count]; + for (var index = 0; index < count; index++) + { + _shards[index] = new ResolverShard(index); + } + + ResolveShards.LogOnce(count); + // The worker waits on these threads per draw: they run at the worker's class, with the + // worker's stack, since they resolve what the worker would resolve itself. + foreach (var shard in _shards) + { + shard.Thread = SharpEmu.HLE.Host.HostHelperThread.Start(count == 1 ? "SharpEmu program resolve" : $"SharpEmu program resolve {shard.Index}", + 16 * 1024 * 1024, () => Run(shard)); + } + } + + internal int ShardCount => _shards.Length; + + // For tests: whether a shard's thread holds its head's claim (under _lock). + internal bool IsWorkerClaimed(int shard) + { + lock (_lock) + { + return _shards[shard].WorkerClaimed; + } + } + + private ResolverShard ShardFor(Job job) + { + if (_shards.Length == 1) + { + return _shards[0]; + } + + var index = _executor.ResolveShardOf(job.Banks, job.Compute is not null); + if ((uint)index >= (uint)_shards.Length) + { + throw _fatal($"The pipeline provider routed a job to resolver shard {index} of {_shards.Length}."); + } + + return _shards[index]; + } + + // Under _lock: the lowest Index not finished (a shard's running job, else its queue's head), or Submitted. + private long FinishedPrefix() + { + var prefix = Submitted; + foreach (var shard in _shards) + { + if (shard.Resolving is { } running) + { + prefix = Math.Min(prefix, running.Index); + } + else if (shard.Queue.TryPeek(out var head)) + { + prefix = Math.Min(prefix, head.Index); + } + } + + return prefix; + } + + // Under _lock. + private bool AnyRunning() + { + foreach (var shard in _shards) + { + if (shard.Running) + { + return true; + } + } + + return false; } // The job of the draw the render thread runs now; set around each deferred draw. @@ -289,9 +388,6 @@ internal ParallelProgramPrefetch(RenderExecutor executor, IRenderHost host, ICon public long Submitted { get; private set; } - // The worker waits for jobs or an active caller (read and written under _lock). - private bool _idleForJobs; - // What became of the jobs since the last TakeCounters: resolved, abandoned (the resolution threw), // taken by their draw, refused when taken (inputs or ownership changed), and the worker's wait. private long _resolvedCount; @@ -473,16 +569,18 @@ public Job SubmitDrawAhead(RegisterBanks banks, long gate, long fullGate, bool i private Job Enqueue(Job job) { + var shard = ShardFor(job); + job.Shard = shard.Index; lock (_lock) { job.Index = Submitted; - _queue.Enqueue(job); + shard.Queue.Enqueue(job); Submitted++; _outstanding++; - // Only the worker asleep on an empty queue waits for a job: the others on this lock wait - // for jobs to finish, which the worker signals. A pulse per draw was a wake for nothing - // while the worker was busy resolving the draws before. - if (_idleForJobs) + // Only the shard's thread asleep on an empty queue waits for this job: the others on this lock wait + // for jobs to finish, which the resolving threads signal. A pulse per draw was a wake for nothing + // while the thread was busy resolving the draws before. + if (shard.IdleForJobs) { Monitor.PulseAll(_lock); } @@ -525,19 +623,24 @@ public void WaitIdle() public void AdvanceGate(long executed) { Interlocked.Exchange(ref _executedGate, executed); - // Only a worker asleep on a gate this reaches needs a wake: one per item costs the render + // Only a resolving thread asleep on a gate this reaches needs a wake: one per item costs the render // thread a kernel call each. - if (Volatile.Read(ref _sleepingOnGate) <= executed) + foreach (var shard in _shards) { - lock (_lock) + if (Volatile.Read(ref shard.SleepingOnGate) <= executed) { - Monitor.PulseAll(_lock); + lock (_lock) + { + Monitor.PulseAll(_lock); + } + + return; } } } - // Returns once the worker finished the first count jobs it was given, so a non-draw item runs - // with no resolution of the draws before it still reading. + // Returns once the first count jobs submitted are finished, on whichever shard (the finished prefix), so a + // non-draw item runs with no resolution of the draws before it still reading. public void WaitFinished(long count) { if (Volatile.Read(ref _finished) >= count) @@ -564,7 +667,8 @@ public void Pause() lock (_lock) { _paused = true; - while (_running) + // Every shard's running resolution, its thread's or the caller's. + while (AnyRunning()) { _waiters++; Monitor.Wait(_lock); @@ -580,9 +684,13 @@ public void Resume() lock (_lock) { _paused = false; - if (_waitingOnPause) + foreach (var shard in _shards) { - Monitor.PulseAll(_lock); + if (shard.WaitingOnPause) + { + Monitor.PulseAll(_lock); + break; + } } } } @@ -606,7 +714,7 @@ public bool TryTakeGraphics(RegisterBanks banks, in GraphicsProgramInputs inputs // Caller work is reported separately, not disguised as a shorter resolver wait. // Keep long queues out of the claim routine's lock/finally frame. if (!_allowCallerResolution || - (Volatile.Read(ref _outstanding) > MaximumCallerOutstanding && !(ClaimSteal && Volatile.Read(ref _workerClaimed))) || + (Volatile.Read(ref _outstanding) > MaximumCallerOutstanding && !(ClaimSteal && Volatile.Read(ref _shards[job.Shard].WorkerClaimed))) || !TryResolveOnCaller(job)) { WaitFor(job); @@ -905,7 +1013,7 @@ public bool TryTakeCompute(RegisterBanks banks, uint dispatchInitiator, uint gro { var waitStarted = System.Diagnostics.Stopwatch.GetTimestamp(); if (!_allowCallerResolution || - (Volatile.Read(ref _outstanding) > MaximumCallerOutstanding && !(ClaimSteal && Volatile.Read(ref _workerClaimed))) || + (Volatile.Read(ref _outstanding) > MaximumCallerOutstanding && !(ClaimSteal && Volatile.Read(ref _shards[job.Shard].WorkerClaimed))) || !TryResolveOnCaller(job)) { WaitFor(job); @@ -1065,7 +1173,7 @@ private GateItemKind NoteUnresolvedTake(Job job, out bool behind) behind = Submitted > job.Index + 1; Interlocked.Increment(ref behind ? ref _unresolvedBehind : ref _unresolvedFrontier); if (job.Gate > Volatile.Read(ref _executedGate)) Interlocked.Increment(ref _unresolvedGated); - else if (Volatile.Read(ref _running)) Interlocked.Increment(ref _unresolvedBusy); + else if (Volatile.Read(ref _shards[job.Shard].Running)) Interlocked.Increment(ref _unresolvedBusy); else Interlocked.Increment(ref _unresolvedQueued); var kind = GateKindOf(job.Gate); Interlocked.Increment(ref _unresolvedByGate[(int)kind]); @@ -1084,16 +1192,15 @@ private GateItemKind NoteUnresolvedTake(Job job, out bool behind) // The resolving thread's idle time in its queue wait and its wakes from it, its time spinning and sleeping on job // gates, the bytes it allocated per job (sampled every AllocationSamplePeriod jobs), and its CPU time. - private long _idleTicks, _gateTicks, _idleWakes, _idleSpinTakes, _sampledBytes, _sampledJobs, _resolverJobs; + private long _idleTicks, _gateTicks, _idleWakes, _idleSpinTakes, _sampledBytes, _sampledJobs; // SHARPEMU_RESOLVER_IDLE_SPIN=0: the idle worker sleeps at once, as before. private static readonly bool IdleSpin = SharpEmu.ShaderCompiler.PerfSwitches.Enabled("SHARPEMU_RESOLVER_IDLE_SPIN"); private const int IdleSpins = 32; - private bool WorkReadyHint() => Volatile.Read(ref _stopping) || (_queue.Count != 0 && !Volatile.Read(ref _running)); + private bool WorkReadyHint(ResolverShard shard) => + Volatile.Read(ref _stopping) || (shard.Queue.Count != 0 && !Volatile.Read(ref shard.Running)); private const int AllocationSamplePeriod = 64; - private ulong _resolverThreadId; - private long _lastResolverCpu = -1; public string TakeResolverReport() { @@ -1101,9 +1208,19 @@ public string TakeResolverReport() static double Milliseconds(long ticks) => ticks * 1000.0 / System.Diagnostics.Stopwatch.Frequency; var sampledJobs = Interlocked.Exchange(ref _sampledJobs, 0); var sampledBytes = Interlocked.Exchange(ref _sampledBytes, 0); - var cpu = ResolverCpuNanoseconds(); - var lastCpu = Interlocked.Exchange(ref _lastResolverCpu, cpu); - var cpuMs = cpu < 0 || lastCpu < 0 ? -1.0 : (cpu - lastCpu) / 1e6; + // Per shard: its thread's CPU time since the last report, jobs resolved (its thread's and the caller's), and its + // thread's resolving time; resolver_cpu_ms is the sum (-1 when a thread's cannot be read). + var cpuMs = 0.0; + var resolverJobs = 0L; + var shardCpu = new double[_shards.Length]; + foreach (var shard in _shards) + { + var cpu = ResolverCpuNanoseconds(shard); + var lastCpu = Interlocked.Exchange(ref shard.LastCpu, cpu); + shardCpu[shard.Index] = cpu < 0 || lastCpu < 0 ? -1.0 : (cpu - lastCpu) / 1e6; + cpuMs = cpuMs < 0 || shardCpu[shard.Index] < 0 ? -1.0 : cpuMs + shardCpu[shard.Index]; + resolverJobs += Interlocked.Exchange(ref shard.ResolverJobs, 0); + } return $"takes_unresolved=(busy={Interlocked.Exchange(ref _unresolvedBusy, 0)},gated={Interlocked.Exchange(ref _unresolvedGated, 0)}," + $"queued={Interlocked.Exchange(ref _unresolvedQueued, 0)},started={Interlocked.Exchange(ref _unresolvedStarted, 0)}," + $"frontier={Interlocked.Exchange(ref _unresolvedFrontier, 0)},behind={Interlocked.Exchange(ref _unresolvedBehind, 0)}," + @@ -1111,19 +1228,38 @@ public string TakeResolverReport() $"behind_wait_ms={Milliseconds(Interlocked.Exchange(ref _unresolvedBehindWaitTicks, 0)).ToString("F1", culture)}) " + $"unresolved_by_gate=({FormatByKind(_unresolvedByGate)}) gate_bound_by_gate=({FormatByKind(_gateBoundByGate)}) " + $"unresolved_wait_ms_by_gate=({FormatByKind(_unresolvedWaitTicksByGate, ticks => Milliseconds(ticks).ToString("F1", culture))}) " + - $"draw_gate_raises=({FormatByKind(_drawGateRaises)}) {TakeDrawLookaheadReport()} resolver_jobs={Interlocked.Exchange(ref _resolverJobs, 0)} " + + $"draw_gate_raises=({FormatByKind(_drawGateRaises)}) {TakeDrawLookaheadReport()} resolver_jobs={resolverJobs} " + $"resolver_idle_ms={Milliseconds(Interlocked.Exchange(ref _idleTicks, 0)).ToString("F1", culture)} " + $"gate_sleep_ms={Milliseconds(Interlocked.Exchange(ref _gateTicks, 0)).ToString("F1", culture)} idle_wakes={Interlocked.Exchange(ref _idleWakes, 0)} " + $"idle_spin_takes={Interlocked.Exchange(ref _idleSpinTakes, 0)} " + $"alloc_b_per_job={(sampledJobs == 0 ? 0 : sampledBytes / (double)sampledJobs).ToString("F0", culture)} " + - $"resolver_cpu_ms={cpuMs.ToString("F1", culture)} " + + $"resolver_cpu_ms={cpuMs.ToString("F1", culture)} {TakeShardReport(shardCpu)} " + SharpEmu.Libs.Gpu.Pipelines.ShaderPipelineCache.TakeGraphicsResolveReport(); } - // The resolving thread's CPU time (user and system), or -1 where it cannot be read. - private long ResolverCpuNanoseconds() + // shards=(n=,resolved=a/b,resolve_ms=a/b,cpu_ms=a/b, then the pipeline cache's shared tier: its gate's takes and wait + // from the sharded paths, the shard gates' wait, draws resolved through a shard's memo, nested resolutions). + private string TakeShardReport(double[] shardCpu) + { + var culture = System.Globalization.CultureInfo.InvariantCulture; + var resolved = new string[_shards.Length]; + var resolveMs = new string[_shards.Length]; + var cpu = new string[_shards.Length]; + foreach (var shard in _shards) + { + resolved[shard.Index] = Interlocked.Exchange(ref shard.Resolved, 0).ToString(culture); + resolveMs[shard.Index] = (Interlocked.Exchange(ref shard.ResolveTicks, 0) * 1000.0 / System.Diagnostics.Stopwatch.Frequency).ToString("F1", culture); + cpu[shard.Index] = shardCpu[shard.Index].ToString("F1", culture); + } + + return $"shards=(n={_shards.Length},resolved={string.Join('/', resolved)},resolve_ms={string.Join('/', resolveMs)},cpu_ms={string.Join('/', cpu)}," + + $"{SharpEmu.Libs.Gpu.Pipelines.ShaderPipelineCache.TakeShardReport().Replace(' ', ',')})"; + } + + // A resolving thread's CPU time (user and system), or -1 where it cannot be read. + private static long ResolverCpuNanoseconds(ResolverShard shard) { - var thread = Volatile.Read(ref _resolverThreadId); + var thread = Volatile.Read(ref shard.ThreadId); if (thread == 0 || !OperatingSystem.IsMacOS()) return -1; Span info = stackalloc ulong[ThreadInfoBytes / sizeof(ulong)]; @@ -1191,17 +1327,19 @@ private void WaitFor(Job job) // the claim with the worker. internal bool TryResolveOnCaller(Job job) { - if (!_allowCallerResolution || job.State != 0 || Volatile.Read(ref _running)) + var shard = _shards[job.Shard]; + if (!_allowCallerResolution || job.State != 0 || Volatile.Read(ref shard.Running)) return false; lock (_lock) { - var claimed = _workerClaimed; - if (_stopping || _paused || _running || job.State != 0 || + var claimed = shard.WorkerClaimed; + if (_stopping || _paused || shard.Running || job.State != 0 || (claimed ? !ClaimSteal : _outstanding > MaximumCallerOutstanding) || - job.Gate > Volatile.Read(ref _executedGate) || !_queue.TryPeek(out var head) || !ReferenceEquals(head, job)) + job.Gate > Volatile.Read(ref _executedGate) || !shard.Queue.TryPeek(out var head) || !ReferenceEquals(head, job)) return false; - _queue.Dequeue(); - _running = true; + shard.Queue.Dequeue(); + shard.Running = true; + shard.Resolving = job; job.Started = true; if (claimed) { @@ -1221,7 +1359,7 @@ internal bool TryResolveOnCaller(Job job) GpuFatal.ThrowOnFatal = speculative; Interlocked.Add(ref _callerResolveTicks, System.Diagnostics.Stopwatch.GetTimestamp() - started); Interlocked.Increment(ref _callerResolves); - FinishJob(worker: false); + FinishJob(shard, worker: false); } return true; } @@ -1252,36 +1390,38 @@ public long TakeClaimSteals() // or pause (under _lock). FinishJob wakes only when one waits: a pulse per job was a kernel call per draw for nobody. private int _waiters; - private void FinishJob(bool worker) + private void FinishJob(ResolverShard shard, bool worker) { lock (_lock) { _outstanding--; - _finished++; - _running = false; - if (worker) _workerClaimed = false; - // The worker idle in Run waits for _running to fall after a caller's resolution as well as for jobs. - if (_waiters != 0 || _idleForJobs) + shard.Running = false; + shard.Resolving = null; + Volatile.Write(ref _finished, FinishedPrefix()); + if (worker) shard.WorkerClaimed = false; + // The shard's thread idle in Run waits for Running to fall after a caller's resolution as well as for jobs. + if (_waiters != 0 || shard.IdleForJobs) { Monitor.PulseAll(_lock); } } } - private void Run() + private void Run(ResolverShard shard) { GpuFatal.ThrowOnFatal = true; if (OperatingSystem.IsMacOS() && PthreadThreadId(0, out var threadId) == 0) { - Volatile.Write(ref _resolverThreadId, threadId); + Volatile.Write(ref shard.ThreadId, threadId); } + var queue = shard.Queue; while (true) { Job job; lock (_lock) { - if ((_queue.Count == 0 || _running) && !_stopping) + if ((queue.Count == 0 || shard.Running) && !_stopping) { var idleStarted = System.Diagnostics.Stopwatch.GetTimestamp(); if (IdleSpin) @@ -1292,7 +1432,7 @@ private void Run() try { var spinner = new SpinWait(); - for (var spin = 0; spin < IdleSpins && !WorkReadyHint(); spin++) + for (var spin = 0; spin < IdleSpins && !WorkReadyHint(shard); spin++) { spinner.SpinOnce(sleep1Threshold: -1); } @@ -1302,17 +1442,17 @@ private void Run() Monitor.Enter(_lock); } - if ((_queue.Count != 0 && !_running) || _stopping) + if ((queue.Count != 0 && !shard.Running) || _stopping) { _idleSpinTakes++; } } - while ((_queue.Count == 0 || _running) && !_stopping) + while ((queue.Count == 0 || shard.Running) && !_stopping) { - _idleForJobs = true; + shard.IdleForJobs = true; Monitor.Wait(_lock); - _idleForJobs = false; + shard.IdleForJobs = false; _idleWakes++; } @@ -1324,8 +1464,8 @@ private void Run() return; } - job = _queue.Peek(); - _workerClaimed = true; + job = queue.Peek(); + shard.WorkerClaimed = true; if (job.Gate > Volatile.Read(ref _executedGate)) { job.GateWaited = true; @@ -1352,20 +1492,20 @@ private void Run() while ((_paused || job.Gate > Volatile.Read(ref _executedGate)) && !_stopping) { - Interlocked.Exchange(ref _sleepingOnGate, _paused ? long.MaxValue : job.Gate); + Interlocked.Exchange(ref shard.SleepingOnGate, _paused ? long.MaxValue : job.Gate); if (!_paused && job.Gate <= Volatile.Read(ref _executedGate)) { break; } - _waitingOnPause = _paused; + shard.WaitingOnPause = _paused; _waiters++; Monitor.Wait(_lock, 50); _waiters--; - _waitingOnPause = false; + shard.WaitingOnPause = false; } - Volatile.Write(ref _sleepingOnGate, long.MaxValue); + Volatile.Write(ref shard.SleepingOnGate, long.MaxValue); if (gateStarted != 0) { Interlocked.Add(ref _gateTicks, System.Diagnostics.Stopwatch.GetTimestamp() - gateStarted); @@ -1377,22 +1517,23 @@ private void Run() } // The caller took the head while this thread waited for its gate (TryResolveOnCaller). - if (_running || !_queue.TryPeek(out var head) || !ReferenceEquals(head, job)) + if (shard.Running || !queue.TryPeek(out var head) || !ReferenceEquals(head, job)) { - _workerClaimed = false; + shard.WorkerClaimed = false; continue; } - _queue.Dequeue(); - _running = true; + queue.Dequeue(); + shard.Running = true; + shard.Resolving = job; job.Started = true; } - var sampled = (++_resolverJobs & (AllocationSamplePeriod - 1)) == 0; + var sampled = (Interlocked.Increment(ref shard.ResolverJobs) & (AllocationSamplePeriod - 1)) == 0; var allocatedBefore = sampled ? GC.GetAllocatedBytesForCurrentThread() : 0; try { - Resolve(job); + Resolve(job, shard); } finally { @@ -1402,18 +1543,18 @@ private void Run() Interlocked.Increment(ref _sampledJobs); } - FinishJob(worker: true); + FinishJob(shard, worker: true); } } } private long _resolveTicks; - // The resolving thread's busy time since the last call. + // The resolving threads' busy time since the last call (each shard's is in its own count too, TakeShardReport). public double TakeResolveMilliseconds() => Interlocked.Exchange(ref _resolveTicks, 0) * 1000.0 / System.Diagnostics.Stopwatch.Frequency; - private void Resolve(Job job) + private void Resolve(Job job, ResolverShard shard) { // resolve_ms only: sampled like the materialization timings (MaterializationTally.StartTiming). var started = SharpEmu.ShaderCompiler.Resources.MaterializationTally.StartTiming(); @@ -1425,7 +1566,9 @@ private void Resolve(Job job) { if (started != 0) { - Interlocked.Add(ref _resolveTicks, SharpEmu.ShaderCompiler.Resources.MaterializationTally.ElapsedTicks(started)); + var ticks = SharpEmu.ShaderCompiler.Resources.MaterializationTally.ElapsedTicks(started); + Interlocked.Add(ref _resolveTicks, ticks); + Interlocked.Add(ref shard.ResolveTicks, ticks); } } } @@ -1466,6 +1609,7 @@ private void ResolveCore(Job job) job.ResolveTicks = System.Diagnostics.Stopwatch.GetTimestamp() - started; Interlocked.Increment(ref _resolvedCount); + Interlocked.Increment(ref _shards[job.Shard].Resolved); job.State = 1; return; } @@ -1489,6 +1633,7 @@ private void ResolveCore(Job job) } Interlocked.Increment(ref _resolvedCount); + Interlocked.Increment(ref _shards[job.Shard].Resolved); job.State = 1; } catch (Exception exception) diff --git a/src/SharpEmu.Libs/Gpu/Rendering/RenderExecutor.Prefetch.cs b/src/SharpEmu.Libs/Gpu/Rendering/RenderExecutor.Prefetch.cs index 6d74eb5b6..bdae4b0c9 100644 --- a/src/SharpEmu.Libs/Gpu/Rendering/RenderExecutor.Prefetch.cs +++ b/src/SharpEmu.Libs/Gpu/Rendering/RenderExecutor.Prefetch.cs @@ -190,6 +190,14 @@ public static GraphicsProgramInputs ProgramInputsOf(RegisterBanks banks, IImageF public ProgramStateStamp ProgramState => _pipelines.ProgramState; + // The provider's resolver shards (IShaderPipelineProvider.ResolveShardCount) and a job's shard among them. + public int ResolveShardCount => _pipelines.ResolveShardCount; + + public int ResolveShardOf(RegisterBanks banks, bool compute) => _pipelines.ResolveShardOf(banks, compute); + + // As ProgramInputsOf decides it, for routing a draw before its inputs are derived. + public static bool PixelStageActive(RegisterBanks banks) => HasActivePixelShader(banks); + // The programs of a draw with these banks and inputs, as ResolveShaderPrograms resolves them. public GraphicsPrograms ResolveGraphicsPrograms(RegisterBanks banks, in GraphicsProgramInputs inputs) { diff --git a/src/SharpEmu.Libs/Gpu/Rendering/ResolveShards.cs b/src/SharpEmu.Libs/Gpu/Rendering/ResolveShards.cs new file mode 100644 index 000000000..a02c95ea1 --- /dev/null +++ b/src/SharpEmu.Libs/Gpu/Rendering/ResolveShards.cs @@ -0,0 +1,113 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using SharpEmu.Libs.Gpu.GpuCommands.Registers; + +namespace SharpEmu.Libs.Gpu.Rendering; + +/// +/// SHARPEMU_RESOLVE_SHARDS: how many resolver threads resolve draw and dispatch programs ahead of the GPU worker +/// (ParallelProgramPrefetch), each with its own queue and its own part of the pipeline cache's resolver state (resolve +/// memo, under a lock of its own); what all of them share (the program cache, translation, vertex tables) stays behind +/// one lock taken only on the miss path. 1 restores the single resolver. A job goes to the shard a stable hash of its +/// resolve memo key's fields names (KeyRoute), so a key always resolves on the same shard and keeps its memo entry. +/// +public static class ResolveShards +{ + public const int Maximum = 8; + private const int DefaultCount = 2; + + public static readonly int Default = Parse(Environment.GetEnvironmentVariable("SHARPEMU_RESOLVE_SHARDS"), out _); + + private static int _logged; + + // The value from the variable, clamped to 1..Maximum; unset or unreadable is the default (named in the log). + internal static int Parse(string? value, out string? problem) + { + problem = null; + if (string.IsNullOrWhiteSpace(value)) + { + return DefaultCount; + } + + if (!int.TryParse(value.Trim(), System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out var count)) + { + problem = $"unreadable value '{value}', using {DefaultCount}"; + return DefaultCount; + } + + if (count < 1 || count > Maximum) + { + var clamped = Math.Clamp(count, 1, Maximum); + problem = $"{count} is outside 1..{Maximum}, using {clamped}"; + return clamped; + } + + return count; + } + + // Once per process, when the first prefetch starts. + internal static void LogOnce(int count) + { + if (Interlocked.Exchange(ref _logged, 1) != 0) + { + return; + } + + Parse(Environment.GetEnvironmentVariable("SHARPEMU_RESOLVE_SHARDS"), out var problem); + Console.Error.WriteLine($"[GPU][PREFETCH] resolve shards={count} (SHARPEMU_RESOLVE_SHARDS{(problem is null ? string.Empty : ": " + problem)})"); + } + + private static ulong Mix(ulong value) + { + value ^= value >> 33; + value *= 0xFF51AFD7ED558CCDUL; + value ^= value >> 33; + value *= 0xC4CEB53FE85A87DUL; + value ^= value >> 33; + return value; + } + + // A draw's route: its vertex (export) program address and user data words, and with the pixel stage active its + // pixel program address and user data words. Every one of them is a field of the resolve memo's key + // (GraphicsResolveMemo.Fill: the addresses, and the user data as PutUserData counts them), so draws with one key + // always route alike; the user data spreads the draws of one program pair over the shards. + public static ulong DrawRoute(RegisterBanks banks, bool pixelActive) + { + var vertex = banks.Shader.Vertex; + var hash = Mix(vertex.ExportAddress ^ 0x9E3779B97F4A7C15UL); + hash = AddUserData(hash, vertex.GeometryUserScalars, vertex.GeometryResource2.UserScalarCount); + if (pixelActive) + { + var pixel = banks.Shader.Pixel; + hash = Mix(hash ^ pixel.Address); + hash = AddUserData(hash, pixel.UserScalars, pixel.Resource2.UserScalarCount); + } + + return Mix(hash); + } + + // A dispatch's route: its program address (a dispatch's resolution keeps no per-shard state). + public static ulong ComputeRoute(RegisterBanks banks) => Mix(banks.Shader.Compute.Address ^ 0x5A5A5A5A5A5A5A5AUL); + + // The words GraphicsResolveMemo.PutUserData puts in the key: the declared count, else the registers written; none + // when that is over the bank (the key is refused then, and the route keeps to the addresses). + private static ulong AddUserData(ulong hash, UserScalarRegisters registers, uint declared) + { + var count = declared != 0 ? declared : registers.Count; + if (count > UserScalarRegisters.Capacity) + { + return hash; + } + + hash = Mix(hash ^ count); + foreach (var word in registers.ValueSpan((int)count)) + { + hash = (hash ^ word) * 0x100000001B3UL; + } + + return hash; + } + + public static int ShardOf(ulong route, int shards) => shards <= 1 ? 0 : (int)(route % (ulong)shards); +} diff --git a/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/KeptStageInputsTests.ResolveShards.cs b/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/KeptStageInputsTests.ResolveShards.cs new file mode 100644 index 000000000..38e7bcc36 --- /dev/null +++ b/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/KeptStageInputsTests.ResolveShards.cs @@ -0,0 +1,84 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using SharpEmu.Libs.Gpu.GpuCommands.Registers; +using SharpEmu.Libs.Gpu.Pipelines; +using SharpEmu.Libs.Gpu.Rendering; +using Xunit; + +namespace SharpEmu.Libs.Tests.Gpu.Pipelines; + +// Resolver shards (ResolveShards): each shard's memo under its own gate, the shared tier under one lock taken on a miss. +public sealed partial class KeptStageInputsTests +{ + [Fact] + public void ResolveShards_TwoThreadsOnATwoShardCacheHandOutWhatOneThreadDoes() + { + var sharded = MemoCache(ResolveMemoMode.Verify); + sharded.ResolveShardCount = 2; + Assert.Equal(2, sharded.ResolveShardCount); + UseLoadingPixelProgram(Descriptor); + var draws = new List<(RegisterBanks Banks, bool Pixel)>(); + foreach (var descriptor in new[] { Descriptor, OtherDescriptor }) + { + PointPixelAt(descriptor); + draws.Add((_banks.Clone(), true)); + draws.Add((_banks.Clone(), false)); + } + + // One thread first (program handles belong to the cache that made them, so the reference is this cache's own). + var expected = draws.Select(draw => sharded.GetGraphicsPrograms(draw.Banks, [], draw.Pixel, depthBound: false)).ToArray(); + Assert.All(expected, programs => Assert.True(programs.Available)); + ShaderPipelineCache.TakeShardReport(); + Report(); + + const int Rounds = 200; + var failures = new System.Collections.Concurrent.ConcurrentQueue(); + var threads = Enumerable.Range(0, 2).Select(thread => new Thread(() => + { + try + { + for (var round = 0; round < Rounds; round++) + { + for (var index = 0; index < draws.Count; index++) + { + // The two threads walk the draws in opposite orders, so they meet on both shards. + var at = thread == 0 ? index : draws.Count - 1 - index; + var programs = sharded.GetGraphicsPrograms(draws[at].Banks, [], draws[at].Pixel, depthBound: false); + if (GraphicsProgramsComparer.Difference(expected[at], programs) is { } difference) + { + failures.Enqueue($"draw {at}: {difference}"); + } + } + } + } + catch (Exception exception) + { + failures.Enqueue(exception.ToString()); + } + })).ToArray(); + foreach (var thread in threads) thread.Start(); + foreach (var thread in threads) Assert.True(thread.Join(TimeSpan.FromSeconds(60))); + + Assert.Empty(failures); + var report = Report(); + Assert.Contains("verify_failed=0)", report); + var shards = ShaderPipelineCache.TakeShardReport(); + var shardedDraws = long.Parse(System.Text.RegularExpressions.Regex.Match(shards, @"sharded_draws=(\d+)").Groups[1].Value); + Assert.True(shardedDraws >= 2 * Rounds * draws.Count, shards); + Assert.Contains("nested_shared=0 ", shards); + Assert.NotNull(sharded.Programs.MaterializationGate); + } + + [Fact] + public void ResolveShards_OneShardKeepsTheSharedTierAsTheOnlyGate() + { + var cache = MemoCache(ResolveMemoMode.On); + cache.ResolveShardCount = 1; + UseLoadingPixelProgram(Descriptor); + Assert.Same(Programs(cache, pixelActive: true), Programs(cache, pixelActive: true)); + // No shard routing and no separate gate for the materialization cache: the one gate covers everything, as before. + Assert.Equal(0, cache.ResolveShardOf(_banks, compute: false)); + Assert.Null(cache.Programs.MaterializationGate); + } +} diff --git a/tests/SharpEmu.Libs.Tests/Gpu/Rendering/ParallelProgramPrefetchCallerTests.cs b/tests/SharpEmu.Libs.Tests/Gpu/Rendering/ParallelProgramPrefetchCallerTests.cs index 7f9b02c9f..e86d02a03 100644 --- a/tests/SharpEmu.Libs.Tests/Gpu/Rendering/ParallelProgramPrefetchCallerTests.cs +++ b/tests/SharpEmu.Libs.Tests/Gpu/Rendering/ParallelProgramPrefetchCallerTests.cs @@ -119,8 +119,7 @@ public void TheCallerTakesAHeadTheWorkerClaimedOnceItsGateOpens() var job = f.Prefetch.Submit(banks, gate: 1); var follower = Banks(); var next = f.Prefetch.Submit(follower, gate: 1); - var claim = typeof(ParallelProgramPrefetch).GetField("_workerClaimed", BindingFlags.Instance | BindingFlags.NonPublic)!; - Assert.True(SpinWait.SpinUntil(() => { lock (f.QueueLock) return (bool)claim.GetValue(f.Prefetch)!; }, TimeSpan.FromSeconds(10))); + Assert.True(SpinWait.SpinUntil(() => f.Prefetch.IsWorkerClaimed(0), TimeSpan.FromSeconds(10))); lock (f.QueueLock) { // Closed gate: still nobody's to resolve. diff --git a/tests/SharpEmu.Libs.Tests/Gpu/Rendering/ParallelProgramPrefetchShardTests.cs b/tests/SharpEmu.Libs.Tests/Gpu/Rendering/ParallelProgramPrefetchShardTests.cs new file mode 100644 index 000000000..ae64679f5 --- /dev/null +++ b/tests/SharpEmu.Libs.Tests/Gpu/Rendering/ParallelProgramPrefetchShardTests.cs @@ -0,0 +1,267 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using System.Reflection; +using SharpEmu.Libs.Gpu.GpuCommands.Registers; +using SharpEmu.Libs.Gpu.Rendering; +using SharpEmu.Libs.Tests.Gpu.Scheduling; +using Xunit; +using static SharpEmu.Libs.Tests.Gpu.Rendering.RenderExecutorFixtures; + +namespace SharpEmu.Libs.Tests.Gpu.Rendering; + +// Resolver shards (ResolveShards): one resolving thread and queue per shard, jobs finishing out of order between shards, +// and every wait for "the jobs before an item" still waiting for exactly those. +[Collection(SchedulingStateCollection.Name)] +public sealed class ParallelProgramPrefetchShardTests +{ + private const ulong ShardZeroShader = 0x0010_0000; + private const ulong ShardOneShader = 0x0020_0000; + private static readonly TimeSpan Long = TimeSpan.FromSeconds(10); + + private sealed class ConcurrentHost : IConcurrentResolveHost + { + internal int Active, MaximumActive, Begins; + public bool AllowsCallerResolution => true; + + public void BeginConcurrentResolve() + { + var active = Interlocked.Increment(ref Active); + int old; + do { old = Volatile.Read(ref MaximumActive); } + while (active > old && Interlocked.CompareExchange(ref MaximumActive, active, old) != old); + Interlocked.Increment(ref Begins); + } + + public object EndConcurrentResolve() + { + Interlocked.Decrement(ref Active); + return this; + } + + public bool IsStillCurrent(object assumptions) => true; + } + + // A resolution of a draw with this vertex address stops until released, and says when it got there. + private sealed class Hold + { + internal readonly ManualResetEventSlim Entered = new(false); + internal readonly ManualResetEventSlim Release = new(false); + } + + private sealed class Fixture : IDisposable + { + private readonly FatalScope _fatal = new(); + internal readonly RecordingRenderHost Host = new(); + internal readonly FakePipelineProvider Pipelines = new() + { + ResolveShardCount = 2, + ShardOf = (banks, _) => banks.Shader.Vertex.ExportAddress == ShardOneShader ? 1 : 0, + }; + internal readonly ConcurrentHost Concurrent = new(); + internal readonly ParallelProgramPrefetch Prefetch; + internal readonly object QueueLock; + private readonly System.Collections.Concurrent.ConcurrentDictionary _holds = new(); + + internal Fixture(bool callerResolution = false) + { + Pipelines.BeforeGraphicsResolve = vertex => + { + if (_holds.TryGetValue(vertex.ExportAddress, out var hold)) + { + hold.Entered.Set(); + Assert.True(hold.Release.Wait(Long), "A held resolution was never released."); + } + }; + Prefetch = new(new RenderExecutor(Host, Pipelines), Host, Concurrent, callerResolution); + QueueLock = typeof(ParallelProgramPrefetch).GetField("_lock", BindingFlags.Instance | BindingFlags.NonPublic)!.GetValue(Prefetch)!; + } + + internal Hold HoldResolutionsOf(ulong vertexAddress) => _holds.GetOrAdd(vertexAddress, _ => new Hold()); + + internal void Idle() => Assert.True(Task.Run(Prefetch.WaitIdle).Wait(Long), "The resolvers did not become idle."); + + public void Dispose() + { + foreach (var hold in _holds.Values) hold.Release.Set(); + Prefetch.Dispose(); + _fatal.Dispose(); + } + } + + private static RegisterBanks BanksAt(ulong vertexAddress) + { + var banks = Banks(); + banks.Shader.Vertex.ExportAddress = vertexAddress; + return banks; + } + + [Fact] + public void AWaiterForThePrefixDoesNotReturnWhileAnEarlierJobOnAnotherShardIsUnfinished() + { + using var f = new Fixture(); + Assert.Equal(2, f.Prefetch.ShardCount); + var hold = f.HoldResolutionsOf(ShardZeroShader); + var first = f.Prefetch.Submit(BanksAt(ShardZeroShader)); + var second = f.Prefetch.Submit(BanksAt(ShardOneShader)); + var third = f.Prefetch.Submit(BanksAt(ShardOneShader)); + Assert.Equal((0, 1, 1), (first.Shard, second.Shard, third.Shard)); + Assert.True(hold.Entered.Wait(Long)); + // The later jobs finish on their own shard while the first is still resolving: out of order. + Assert.True(SpinWait.SpinUntil(() => second.State == 1 && third.State == 1, Long)); + Assert.Equal(0, first.State); + + // Two jobs finished, but not the first: no prefix past it is finished. + var one = Task.Run(() => f.Prefetch.WaitFinished(1)); + var three = Task.Run(() => f.Prefetch.WaitFinished(3)); + Assert.False(one.Wait(TimeSpan.FromMilliseconds(250))); + Assert.False(three.IsCompleted); + f.Prefetch.WaitFinished(0); + + hold.Release.Set(); + Assert.True(one.Wait(Long) && three.Wait(Long)); + Assert.Equal(1, first.State); + f.Idle(); + Assert.Equal(3, f.Prefetch.TakeCounters().Resolved); + } + + [Fact] + public void ALaterJobOnTheSameShardWaitsBehindItsHeadWhileTheOtherShardRuns() + { + using var f = new Fixture(); + var hold = f.HoldResolutionsOf(ShardOneShader); + var held = f.Prefetch.Submit(BanksAt(ShardOneShader)); + Assert.True(hold.Entered.Wait(Long)); + var behindHeld = f.Prefetch.Submit(BanksAt(ShardOneShader)); + var otherShard = f.Prefetch.Submit(BanksAt(ShardZeroShader)); + Assert.True(SpinWait.SpinUntil(() => otherShard.State == 1, Long)); + // A shard resolves its own jobs in submission order: the one behind the held job has not begun. + Assert.Equal((0, 0, false), (held.State, behindHeld.State, behindHeld.Started)); + hold.Release.Set(); + f.Idle(); + f.Prefetch.WaitFinished(3); + Assert.Equal((1, 1), (held.State, behindHeld.State)); + } + + [Fact] + public void PauseWaitsForTheRunningResolutionOfEveryShardAndHoldsAllOfThem() + { + using var f = new Fixture(); + var hold = f.HoldResolutionsOf(ShardOneShader); + var running = f.Prefetch.Submit(BanksAt(ShardOneShader)); + Assert.True(hold.Entered.Wait(Long)); + var pause = Task.Run(f.Prefetch.Pause); + Assert.False(pause.Wait(TimeSpan.FromMilliseconds(250))); + hold.Release.Set(); + Assert.True(pause.Wait(Long)); + Assert.Equal(1, running.State); + + // Paused: jobs on both shards stay queued, none begins. + var begins = Volatile.Read(ref f.Concurrent.Begins); + var zero = f.Prefetch.Submit(BanksAt(ShardZeroShader)); + var one = f.Prefetch.Submit(BanksAt(ShardOneShader)); + Thread.Sleep(150); + Assert.Equal((0, 0, begins), (zero.State, one.State, Volatile.Read(ref f.Concurrent.Begins))); + + f.Prefetch.Resume(); + f.Idle(); + Assert.Equal((1, 1), (zero.State, one.State)); + f.Prefetch.WaitFinished(3); + } + + [Fact] + public void TheCallerResolvesItsShardsHeadWhileAnotherShardResolvesButNeverAJobAShardIsRunning() + { + using var f = new Fixture(callerResolution: true); + var hold = f.HoldResolutionsOf(ShardOneShader); + var onShardOne = f.Prefetch.Submit(BanksAt(ShardOneShader)); + Assert.True(hold.Entered.Wait(Long)); + ParallelProgramPrefetch.Job onShardZero; + lock (f.QueueLock) + { + // Shard zero's thread cannot take its job while the test holds the queue lock: the caller can. + onShardZero = f.Prefetch.Submit(BanksAt(ShardZeroShader)); + Assert.False(f.Prefetch.TryResolveOnCaller(onShardOne)); + Assert.True(f.Prefetch.TryResolveOnCaller(onShardZero)); + Assert.Equal((1, 0), (onShardZero.State, onShardOne.State)); + // Both resolutions ran at once: the caller's on shard zero beside shard one's thread. + Assert.Equal(2, f.Concurrent.MaximumActive); + } + + // The finished prefix still stops at the first job, which shard one's thread holds. + Assert.False(Task.Run(() => f.Prefetch.WaitFinished(1)).Wait(TimeSpan.FromMilliseconds(150))); + hold.Release.Set(); + f.Idle(); + f.Prefetch.WaitFinished(2); + Assert.Equal(1, onShardOne.State); + Assert.Equal(2, f.Concurrent.Begins); + Assert.Equal(1, f.Prefetch.TakeCallerResolveCounters().Count); + } + + [Fact] + public void AGatedJobOnOneShardDoesNotHoldAnOpenJobOnTheOther() + { + using var f = new Fixture(); + var gated = f.Prefetch.Submit(BanksAt(ShardZeroShader), gate: 1); + var open = f.Prefetch.Submit(BanksAt(ShardOneShader), gate: 0); + Assert.True(SpinWait.SpinUntil(() => open.State == 1, Long)); + Assert.Equal(0, gated.State); + Assert.False(Task.Run(() => f.Prefetch.WaitFinished(1)).Wait(TimeSpan.FromMilliseconds(150))); + f.Prefetch.AdvanceGate(1); + f.Idle(); + f.Prefetch.WaitFinished(2); + Assert.Equal(1, gated.State); + } + + [Fact] + public void ADrawRoutesByItsMemoKeyFieldsAlone() + { + static RegisterBanks Draw(uint word, uint beyond, bool pixel) + { + var banks = Banks(withPixel: pixel); + var vertex = banks.Shader.Vertex; + vertex.GeometryResource2.UserScalarCount = 2; + vertex.GeometryUserScalars.Set(0, 0x1234, UserScalarKind.Unknown); + vertex.GeometryUserScalars.Set(1, word, UserScalarKind.Unknown); + // Past the declared count: not part of the key. + vertex.GeometryUserScalars.Set(2, beyond, UserScalarKind.Unknown); + return banks; + } + + Assert.Equal(ResolveShards.DrawRoute(Draw(7, 1, true), true), ResolveShards.DrawRoute(Draw(7, 2, true), true)); + Assert.NotEqual(ResolveShards.DrawRoute(Draw(7, 1, true), true), ResolveShards.DrawRoute(Draw(8, 1, true), true)); + + // With the pixel stage off, nothing of the pixel stage is in the key, nor in the route. + var inactive = Draw(7, 1, true); + var other = Draw(7, 1, true); + other.Shader.Pixel.Address ^= 0x100; + other.Shader.Pixel.UserScalars.Set(0, 99, UserScalarKind.Unknown); + Assert.Equal(ResolveShards.DrawRoute(inactive, false), ResolveShards.DrawRoute(other, false)); + Assert.NotEqual(ResolveShards.DrawRoute(inactive, true), ResolveShards.DrawRoute(other, true)); + + // The same key routes alike every time; keys that differ in user data spread over the shards. + var counts = new int[3]; + for (var word = 0u; word < 3000; word++) + { + var shard = ResolveShards.ShardOf(ResolveShards.DrawRoute(Draw(word, 0, true), true), 3); + Assert.Equal(shard, ResolveShards.ShardOf(ResolveShards.DrawRoute(Draw(word, word, true), true), 3)); + counts[shard]++; + } + + Assert.All(counts, count => Assert.InRange(count, 850, 1150)); + Assert.Equal(0, ResolveShards.ShardOf(ResolveShards.DrawRoute(Draw(1, 0, true), true), 1)); + } + + [Theory] + [InlineData(null, 2, false)] + [InlineData("1", 1, false)] + [InlineData("3", 3, false)] + [InlineData("0", 1, true)] + [InlineData("64", ResolveShards.Maximum, true)] + [InlineData("two", 2, true)] + public void TheShardCountIsClampedAndNamesWhatItRefused(string? value, int count, bool problem) + { + Assert.Equal(count, ResolveShards.Parse(value, out var refused)); + Assert.Equal(problem, refused is not null); + } +} diff --git a/tests/SharpEmu.Libs.Tests/Gpu/Rendering/RenderExecutorTestSupport.cs b/tests/SharpEmu.Libs.Tests/Gpu/Rendering/RenderExecutorTestSupport.cs index 65d8a22a1..eb0c83825 100644 --- a/tests/SharpEmu.Libs.Tests/Gpu/Rendering/RenderExecutorTestSupport.cs +++ b/tests/SharpEmu.Libs.Tests/Gpu/Rendering/RenderExecutorTestSupport.cs @@ -653,6 +653,13 @@ public void RecordUnsupportedGraphics(VertexStageRegisters vertex, ContextRegist public List ExportMappings { get; } = new(); + // Resolver shards (IShaderPipelineProvider.ResolveShardCount); ShardOf routes a job (shard 0 without it). + public int ResolveShardCount { get; set; } = 1; + + internal Func? ShardOf { get; set; } + + public int ResolveShardOf(RegisterBanks banks, bool compute) => ShardOf?.Invoke(banks, compute) ?? 0; + public GraphicsPrograms GetGraphicsPrograms( RegisterBanks banks, ReadOnlySpan targetExportMapping, @@ -664,8 +671,13 @@ public GraphicsPrograms GetGraphicsPrograms( int startInstanceUserData) { BeforeGraphicsResolve?.Invoke(banks.Shader.Vertex); - Calls.Add($"get_graphics_programs pixelActive={pixelActive}"); - ExportMappings.Add(targetExportMapping.ToArray()); + // Resolver shards call in from several threads at once. + lock (Calls) + { + Calls.Add($"get_graphics_programs pixelActive={pixelActive}"); + ExportMappings.Add(targetExportMapping.ToArray()); + } + return !pixelActive && GraphicsWithoutPixel is { } withoutPixel ? withoutPixel : Graphics; } From 86be8b85149667b11eaba0f619703dbfb5ff63c9 Mon Sep 17 00:00:00 2001 From: kuba Date: Tue, 17 Nov 2026 03:50:48 +0000 Subject: [PATCH 164/178] [Tests] Bench the real resolver with N shards (SHARPEMU_DS_SHARD_BENCH_ENGINE=1) Replays the captured frame through ParallelProgramPrefetch on fresh pipeline caches per arm, fingerprints the programs every take hands out and counts program and pipeline creations; reports monitor contention, GC pauses and frame times inside the timed part. --- .../Scenes/DsDrawCostBenchTests.Engine.cs | 248 ++++++++++++++++++ .../Scenes/DsDrawCostBenchTests.Shards.cs | 6 + 2 files changed, 254 insertions(+) create mode 100644 tests/SharpEmu.Gpu.Metal.Tests/Scenes/DsDrawCostBenchTests.Engine.cs diff --git a/tests/SharpEmu.Gpu.Metal.Tests/Scenes/DsDrawCostBenchTests.Engine.cs b/tests/SharpEmu.Gpu.Metal.Tests/Scenes/DsDrawCostBenchTests.Engine.cs new file mode 100644 index 000000000..1212d46c2 --- /dev/null +++ b/tests/SharpEmu.Gpu.Metal.Tests/Scenes/DsDrawCostBenchTests.Engine.cs @@ -0,0 +1,248 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using System.Diagnostics; +using System.Reflection; +using SharpEmu.Gpu.Metal.V2; +using SharpEmu.HLE; +using SharpEmu.Libs.Gpu; +using SharpEmu.Libs.Gpu.Pipelines; +using SharpEmu.Libs.Gpu.Rendering; +using Xunit; + +namespace SharpEmu.Gpu.Metal.Tests.Scenes; + +/// +/// The shard bench on the real engine path (SHARPEMU_DS_SHARD_BENCH_ENGINE=1): per arm one pipeline cache split into N +/// resolver shards (ShaderPipelineCache.ResolveShardCount) and one ParallelProgramPrefetch over it with its N resolving +/// threads, fed the captured jobs of a frame as the command thread feeds it (every gate open) and drained (WaitIdle); +/// the wall time from the first submission to idle is the resolvers' throughput. The jobs are then taken as the worker +/// takes them (outside the time), which hands their assumptions back, and the taken programs are fingerprinted by +/// content (program hash, shader base, every snapshot word): equal between arms means N shards hand out what one does. +/// Creations are counted per arm (program entries made, graphics and compute pipelines): equal between arms means no +/// key was created twice because two shards missed at once. +/// +public sealed partial class DsDrawCostBenchTests +{ + // Looked up here, not from the other parts' statics: the order partial classes' static fields initialize in is not fixed. + private static readonly Type EngineCacheType = + typeof(GraphicsPrograms).Assembly.GetType("SharpEmu.Libs.Gpu.Pipelines.ShaderPipelineCache", throwOnError: true)!; + + private static readonly PropertyInfo CacheShardCount = + EngineCacheType.GetProperty("ResolveShardCount", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)!; + + private static readonly PropertyInfo CachePrograms = + EngineCacheType.GetProperty("Programs", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)!; + + private static readonly Type ProgramCacheType = + typeof(GraphicsPrograms).Assembly.GetType("SharpEmu.Libs.Gpu.Pipelines.ShaderProgramCache", throwOnError: true)!; + + private static readonly FieldInfo NextProgramId = ProgramCacheType.GetField("_nextProgramId", BindingFlags.Instance | BindingFlags.NonPublic)!; + + // A job's State (0 queued or resolving), read without the prefetch's lock: the drain below spins on it instead of + // sleeping in WaitIdle, where every finished job would pulse the waiting bench thread awake. + private static readonly System.Linq.Expressions.ParameterExpression JobParameter = + System.Linq.Expressions.Expression.Parameter(typeof(ParallelProgramPrefetch.Job), "job"); + + private static readonly Func JobState = System.Linq.Expressions.Expression.Lambda>( + System.Linq.Expressions.Expression.Field(JobParameter, "State"), JobParameter).Compile(); + + private static ulong FingerprintStage(ulong hash, in ShaderStageResources stage) + { + static ulong Mix(ulong hash, ulong value) => (hash ^ value) * 0x100000001B3UL; + static ulong MixWords(ulong hash, ReadOnlySpan words) + { + hash = Mix(hash, (ulong)words.Length); + foreach (var word in words) hash = Mix(hash, word); + return hash; + } + + hash = Mix(hash, stage.Program?.Hash ?? 0); + hash = Mix(hash, stage.ShaderBase); + if (stage.Program is null) return hash; + var snapshot = stage.Resources; + foreach (var words in snapshot.Buffers) hash = MixWords(hash, words); + foreach (var words in snapshot.Images) hash = MixWords(hash, words); + foreach (var words in snapshot.Samplers) hash = MixWords(hash, words); + hash = MixWords(hash, snapshot.FlattenedResourceTable); + return MixWords(hash, snapshot.UserData); + } + + private object RunEngineShardBench(SceneRig rig, object translation, string variation, CapturedJob[] jobs, Action prepareFrame, + Action finishFrame, int firstFrame) + { + int Setting(string name, int fallback) => + int.TryParse(Environment.GetEnvironmentVariable($"SHARPEMU_DS_SHARD_BENCH_{name}"), out var value) && value > 0 ? value : fallback; + var frames = Setting("FRAMES", 8); + var warmFrames = Setting("WARM_FRAMES", 4); + var arms = (Environment.GetEnvironmentVariable("SHARPEMU_DS_SHARD_BENCH_ARMS") ?? "1,2,2,1,1,2,2,1") + .Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries).Select(int.Parse).ToArray(); + var liveContext = (CpuContext)TranslationContext.GetValue(translation)!; + var renderHost = (IRenderHost)ExecutorHost.GetValue(TranslationExecutor.GetValue(translation))!; + var host = rig.Host; + var graphicsJobs = jobs.Count(job => job.Compute is null); + Output.WriteLine($"engine shard bench: {variation}, {jobs.Length} jobs a frame ({graphicsJobs} draws, {jobs.Length - graphicsJobs} dispatches), " + + $"{warmFrames} warm + {frames} measured frames per arm, arms {string.Join(",", arms)}, {Environment.ProcessorCount} cpus"); + + // =spin: the bench thread spins on each job's state instead of sleeping in WaitIdle (whose waiter makes every finish + // pulse the prefetch lock); the game's command thread never waits for the whole frame. + var spinDrain = Environment.GetEnvironmentVariable("SHARPEMU_DS_SHARD_BENCH_DRAIN") == "spin"; + var armResults = new List<(int Count, double JobsPerSecond, double WallMedianMs, string Report, ulong Fingerprint, string Creations, + long Taken, long Refused)>(); + foreach (var count in arms) + { + var context = new CpuContext(liveContext.Memory, liveContext.TargetGeneration); + var registry = CreateHeaderRegistry.Invoke(null, [context])!; + var cache = (IShaderPipelineProvider)Activator.CreateInstance(PipelineCacheType, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, + null, [context, (IShaderPipelineHost)host, GuestGpu.Current, registry], null)!; + CacheShardCount.SetValue(cache, count); + var executor = new RenderExecutor(renderHost, cache); + using var prefetch = new ParallelProgramPrefetch(executor, renderHost, (IConcurrentResolveHost)host); + Assert.Contains($"shards=(n={count},", prefetch.TakeResolverReport()); + var submitted = new ParallelProgramPrefetch.Job[jobs.Length]; + var total = warmFrames + frames; + var wall = new double[total]; + var fingerprint = 0xCBF29CE484222325UL; + // Every arm replays the same frames (the churn and the pixel-constant copies follow the frame number), so the + // fingerprints of all arms must match. + var frame = firstFrame; + long taken = 0, refused = 0, contentions = 0, collections = 0; + var paused = TimeSpan.Zero; + string report = string.Empty; + for (var index = 0; index < total; index++) + { + prepareFrame(frame++); + if (index == warmFrames) + { + _ = prefetch.TakeResolverReport(); + _ = prefetch.TakeCounters(); + _ = prefetch.TakeResolveMilliseconds(); + } + + var contended = Monitor.LockContentionCount; + var collected = GC.CollectionCount(0); + var pausedBefore = GC.GetTotalPauseDuration(); + var started = Stopwatch.GetTimestamp(); + for (var at = 0; at < jobs.Length; at++) + { + var job = jobs[at]; + submitted[at] = job.Compute is { } arguments + ? prefetch.SubmitCompute(job.Banks, 0, arguments.Initiator, arguments.GroupsX, arguments.GroupsY, arguments.GroupsZ, arguments.Indirect) + : prefetch.Submit(job.Banks, 0, job.Inputs.Indexed, job.Inputs.StartInstanceUserData); + } + + if (spinDrain) + { + foreach (var job in submitted) + { + while (JobState(job) == 0) Thread.SpinWait(8); + } + } + + prefetch.WaitIdle(); + wall[index] = (Stopwatch.GetTimestamp() - started) * 1000.0 / Stopwatch.Frequency; + // Monitor contentions in the process over the timed part (the prefetch lock, the shard and shared gates). + if (index >= warmFrames) + { + contentions += Monitor.LockContentionCount - contended; + // Collections and GC pause time inside the timed part: the resolvers allocate, a pause stops every shard. + collections += GC.CollectionCount(0) - collected; + paused += GC.GetTotalPauseDuration() - pausedBefore; + } + + // The worker's takes, untimed: they hand the assumptions back, and the measured frames' programs are fingerprinted. + for (var at = 0; at < jobs.Length; at++) + { + var job = jobs[at]; + prefetch.Current = submitted[at]; + bool took; + if (job.Compute is { } arguments) + { + took = prefetch.TryTakeCompute(job.Banks, arguments.Initiator, arguments.GroupsX, arguments.GroupsY, arguments.GroupsZ, + arguments.Indirect, out var program); + if (took && index >= warmFrames) fingerprint = FingerprintStage(fingerprint, program.Input.Stage); + } + else + { + var inputs = RenderExecutor.ProgramInputsOf(job.Banks, renderHost.FormatSupport, renderHost.Fatal, job.Inputs.Indexed, + job.Inputs.StartInstanceUserData); + took = prefetch.TryTakeGraphics(job.Banks, in inputs, out var programs); + if (took && index >= warmFrames) + { + fingerprint = FingerprintStage(fingerprint, programs.VertexInput.Stage); + if (inputs.PixelActive) fingerprint = FingerprintStage(fingerprint, programs.PixelInput.Stage); + } + } + + if (index >= warmFrames) + { + if (took) taken++; + else refused++; + } + } + + prefetch.Current = null; + finishFrame(); + if (index == total - 1) + { + report = prefetch.TakeResolverReport(); + } + } + + var programCache = CachePrograms.GetValue(cache)!; + var creations = $"program_ids={NextProgramId.GetValue(programCache)} program_entries={ProgramCacheType.GetProperty("ProgramCount")!.GetValue(programCache)} " + + $"graphics_pipelines={PipelineCacheType.GetProperty("GraphicsPipelineCount")!.GetValue(cache)} " + + $"compute_pipelines={PipelineCacheType.GetProperty("ComputePipelineCount")!.GetValue(cache)}"; + var measured = wall[warmFrames..]; + var sorted = measured.Order().ToArray(); + var jobsPerSecond = frames * jobs.Length / (measured.Sum() / 1000.0); + armResults.Add((count, jobsPerSecond, sorted[sorted.Length / 2], report, fingerprint, creations, taken, refused)); + var shards = System.Text.RegularExpressions.Regex.Match(report, @"shards=\([^)]*\)").Value; + Output.WriteLine($"engine N={count}: {jobsPerSecond / 1000.0:F0}k jobs/s, wall median {sorted[sorted.Length / 2]:F2} ms/frame (min {sorted[0]:F2}), " + + $"taken {taken} refused {refused}, fingerprint {fingerprint:X16}, {creations}, " + + $"monitor contentions {contentions / (double)(frames * jobs.Length):F3}/job, gc {collections} collections {paused.TotalMilliseconds:F1} ms paused, " + + $"frames ms [{string.Join(" ", measured.Select(ms => ms.ToString("F1")))}]; last frame {shards}"); + } + + var byCount = armResults.GroupBy(arm => arm.Count).OrderBy(group => group.Key).Select(group => + { + static double Median(IEnumerable values) + { + var sorted = values.Order().ToArray(); + return sorted.Length % 2 == 1 ? sorted[sorted.Length / 2] : (sorted[sorted.Length / 2 - 1] + sorted[sorted.Length / 2]) / 2; + } + + return new + { + shards = group.Key, + arms = group.Count(), + jobsPerSecond = Median(group.Select(arm => arm.JobsPerSecond)), + jobsPerSecondByArm = group.Select(arm => Math.Round(arm.JobsPerSecond)).ToArray(), + wallMedianMsPerFrame = Median(group.Select(arm => arm.WallMedianMs)), + fingerprints = group.Select(arm => $"{arm.Fingerprint:X16}").Distinct().ToArray(), + creations = group.Select(arm => arm.Creations).Distinct().ToArray(), + taken = group.Select(arm => arm.Taken).ToArray(), + refused = group.Select(arm => arm.Refused).ToArray(), + lastReports = group.Select(arm => System.Text.RegularExpressions.Regex.Match(arm.Report, @"shards=\([^)]*\)").Value).ToArray(), + }; + }).ToArray(); + var single = byCount.FirstOrDefault(row => row.shards == 1)?.jobsPerSecond ?? double.NaN; + foreach (var row in byCount) + { + Output.WriteLine($"engine summary N={row.shards}: {row.jobsPerSecond / 1000.0:F0}k jobs/s median of {row.arms} arms ({row.jobsPerSecond / single:F2}x N=1), " + + $"{row.wallMedianMsPerFrame:F2} ms/frame, fingerprints {string.Join("/", row.fingerprints)}, creations [{string.Join(" | ", row.creations)}]"); + } + + return new + { + variation = $"{variation}/engine-shards", + jobs = jobs.Length, + draws = graphicsJobs, + frames, + warmFrames, + byCount, + fingerprintsAgree = armResults.Select(arm => arm.Fingerprint).Distinct().Count() == 1, + creationsAgree = armResults.Select(arm => arm.Creations).Distinct().Count() == 1, + }; + } +} diff --git a/tests/SharpEmu.Gpu.Metal.Tests/Scenes/DsDrawCostBenchTests.Shards.cs b/tests/SharpEmu.Gpu.Metal.Tests/Scenes/DsDrawCostBenchTests.Shards.cs index 73d061884..7971e9bb9 100644 --- a/tests/SharpEmu.Gpu.Metal.Tests/Scenes/DsDrawCostBenchTests.Shards.cs +++ b/tests/SharpEmu.Gpu.Metal.Tests/Scenes/DsDrawCostBenchTests.Shards.cs @@ -224,6 +224,12 @@ private static void ResolveJob(MetalRenderHost host, IRenderHost renderHost, Ren private object RunShardBench(SceneRig rig, object translation, string variation, CapturedJob[] jobs, Action prepareFrame, Action finishFrame, int firstFrame) { + // SHARPEMU_DS_SHARD_BENCH_ENGINE=1: the real engine path instead (RunEngineShardBench). + if (Environment.GetEnvironmentVariable("SHARPEMU_DS_SHARD_BENCH_ENGINE") == "1") + { + return RunEngineShardBench(rig, translation, variation, jobs, prepareFrame, finishFrame, firstFrame); + } + int Setting(string name, int fallback) => int.TryParse(Environment.GetEnvironmentVariable($"SHARPEMU_DS_SHARD_BENCH_{name}"), out var value) && value > 0 ? value : fallback; var frames = Setting("FRAMES", 8); From 42dada621a3271720b853d14052339880090ffb3 Mon Sep 17 00:00:00 2001 From: kuba Date: Tue, 17 Nov 2026 04:10:56 +0000 Subject: [PATCH 165/178] [GPU] Default to one resolver shard: two gave no frame-time gain in Demon's Souls Same session, 1080p defaults: 80.8 ms median with one shard, 82.6 ms with two; the worker's wait on the resolver fell by about 2 ms per frame, resolver CPU rose about 45% and 8-9 ms per frame went to waiting on the shared lock. SHARPEMU_RESOLVE_SHARDS=2 still enables it. --- docs/macos/configuration.md | 2 +- src/SharpEmu.Libs/Gpu/Rendering/ResolveShards.cs | 4 +++- .../Gpu/Rendering/ParallelProgramPrefetchShardTests.cs | 5 +++-- 3 files changed, 7 insertions(+), 4 deletions(-) diff --git a/docs/macos/configuration.md b/docs/macos/configuration.md index e4b952206..b5c8ece7f 100644 --- a/docs/macos/configuration.md +++ b/docs/macos/configuration.md @@ -69,7 +69,7 @@ them for measurements or to isolate a problem. | `SHARPEMU_METAL_V2_BINARY_ARCHIVE_BUDGET_MB` | `8192` | Size bound of the archives on disk. | | `SHARPEMU_METAL_V2_ASYNC_PIPELINES` | on | `0` builds pipeline states on the GPU worker thread. | | `SHARPEMU_METAL_V2_ASYNC_LIBRARIES` | on | `0` compiles each shader library on the thread that needs it, not on the compile pool. | -| `SHARPEMU_RESOLVE_SHARDS` | `2` | Threads that resolve draw and dispatch programs ahead of the GPU worker, 1 to 8. Each has its own queue and its own part of the resolve memo; a draw always goes to the same one. `1` restores the single resolver. 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_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_METAL_V2_PIPELINE_LIMIT` | `8192` | Pipeline states kept before idle ones are released. `0` is unlimited. | | `SHARPEMU_METAL_V2_MODULE_LIMIT` | `2048` | The same for shader modules. | | `SHARPEMU_METAL_V2_SHADER_EVICTION` | on | `0` keeps every pipeline and module. | diff --git a/src/SharpEmu.Libs/Gpu/Rendering/ResolveShards.cs b/src/SharpEmu.Libs/Gpu/Rendering/ResolveShards.cs index a02c95ea1..5c01b7be4 100644 --- a/src/SharpEmu.Libs/Gpu/Rendering/ResolveShards.cs +++ b/src/SharpEmu.Libs/Gpu/Rendering/ResolveShards.cs @@ -15,7 +15,9 @@ namespace SharpEmu.Libs.Gpu.Rendering; public static class ResolveShards { public const int Maximum = 8; - private const int DefaultCount = 2; + // One by default: in Demon's Souls two shards took ~2 ms/frame off the worker's wait on the resolver but did not + // move the frame time, for ~45% more resolver CPU and 8-9 ms/frame spent waiting on the shared lock (2026-11-17). + private const int DefaultCount = 1; public static readonly int Default = Parse(Environment.GetEnvironmentVariable("SHARPEMU_RESOLVE_SHARDS"), out _); diff --git a/tests/SharpEmu.Libs.Tests/Gpu/Rendering/ParallelProgramPrefetchShardTests.cs b/tests/SharpEmu.Libs.Tests/Gpu/Rendering/ParallelProgramPrefetchShardTests.cs index ae64679f5..7a904151a 100644 --- a/tests/SharpEmu.Libs.Tests/Gpu/Rendering/ParallelProgramPrefetchShardTests.cs +++ b/tests/SharpEmu.Libs.Tests/Gpu/Rendering/ParallelProgramPrefetchShardTests.cs @@ -253,12 +253,13 @@ static RegisterBanks Draw(uint word, uint beyond, bool pixel) } [Theory] - [InlineData(null, 2, false)] + [InlineData(null, 1, false)] + [InlineData("2", 2, false)] [InlineData("1", 1, false)] [InlineData("3", 3, false)] [InlineData("0", 1, true)] [InlineData("64", ResolveShards.Maximum, true)] - [InlineData("two", 2, true)] + [InlineData("two", 1, true)] public void TheShardCountIsClampedAndNamesWhatItRefused(string? value, int count, bool problem) { Assert.Equal(count, ResolveShards.Parse(value, out var refused)); From d0cfeb21050f6510da0f0a609d1927ce579b7729 Mon Sep 17 00:00:00 2001 From: kuba Date: Tue, 17 Nov 2026 04:37:33 +0000 Subject: [PATCH 166/178] [Metal] Time blit, tiler and host compute encoders in the pass profile SHARPEMU_METAL_V2_PROFILE_PASSES=1 sampled only render passes and the shared compute encoder, so every transfer blit, tiler compute encoder, fill, copy, staged store and label copy landed in the next record's gap_us. Those encoders now open through their pass descriptors with start/end-of-encoder samples when the profile is on (the plain calls are kept when it is off), each with a record (k=blit, k=tiler-compute, k=host-compute) named for the transfer cause and the label the call site reports. An encoder the sample ring has no room for is recorded as us=? and counted. The sub line sums GPU time per kind (kind_us=), the gaps (gaps_us=) and unsampled records. --- docs/macos/configuration.md | 2 +- .../V2/MetalCommandStream.cs | 6 +- .../V2/MetalImageCache.Sparse.cs | 8 +- .../V2/MetalRenderHost.DeferredFills.cs | 4 +- .../V2/MetalRenderHost.FlipCopy.cs | 4 +- .../V2/MetalRenderHost.GdsTransfers.cs | 8 +- .../V2/MetalRenderHost.Images.cs | 4 +- .../V2/MetalRenderHost.KernelFills.cs | 4 +- .../V2/MetalRenderHost.LabelScatter.cs | 4 +- .../V2/MetalRenderHost.LodStatistics.cs | 4 +- .../V2/MetalRenderHost.MeshIndirect.cs | 4 +- .../V2/MetalRenderHost.Occlusion.cs | 9 +- .../V2/MetalRenderHost.PassProfile.cs | 178 ++++++++++++++++-- .../V2/MetalRenderHost.TargetDump.cs | 8 +- .../V2/MetalRenderHost.TextureStats.cs | 4 +- .../SharpEmu.Gpu.Metal/V2/MetalRenderHost.cs | 11 +- .../V2/MetalStagedStorage.cs | 9 +- .../SharpEmu.Gpu.Metal/V2/MetalTiler.cs | 29 ++- .../SharpEmu.Gpu.Metal/V2/MetalV2Contracts.cs | 24 +++ .../MetalPassProfileTests.cs | 118 ++++++++++++ 20 files changed, 406 insertions(+), 36 deletions(-) create mode 100644 tests/SharpEmu.Gpu.Metal.Tests/MetalPassProfileTests.cs diff --git a/docs/macos/configuration.md b/docs/macos/configuration.md index b5c8ece7f..bf6ab48e1 100644 --- a/docs/macos/configuration.md +++ b/docs/macos/configuration.md @@ -120,7 +120,7 @@ undoes an optimization to isolate a miscompile: | `SHARPEMU_METAL_V2_WAIT_TRACE=1` (or `SHARPEMU_METAL_V2_EOP_TRACE=1`) | Names, on each `[METAL-V2][SLOW-WAIT]` line, the shader whose resources were being prepared. | | `SHARPEMU_METAL_V2_PROFILE_SHADERS=1` | Gives every draw and dispatch its own command buffer and prints GPU time per shader hash (`[METAL-V2][SHADER-PROF]`). It serializes the GPU, so only ratios are meaningful. | | `SHARPEMU_METAL_V2_PROFILE_TOP=` | Entries per profile report. Default 8. | -| `SHARPEMU_METAL_V2_PROFILE_PASSES=1` | Per-encoder GPU time (`[METAL-V2][PASS-PROF]`). | +| `SHARPEMU_METAL_V2_PROFILE_PASSES=1` | Per-encoder GPU time (`[METAL-V2][PASS-PROF]`). Blit encoders (`k=blit`), the tiler's compute encoders (`k=tiler-compute`) and the host's other compute encoders (`k=host-compute`) are recorded too, named for the transfer that opened them, so `gap_us` is time no encoder ran; the `sub` line sums GPU time per kind (`kind_us=`). | | `SHARPEMU_PROFILE_RENDER=1` | Per-phase timing of the draw translation path on the GPU worker, reported at each flip. | | `SHARPEMU_METAL_V2_DUMP_TARGETS=` | Writes each render pass's color target and each presented frame as PNG. Waits for the GPU after each dump. `1` writes to `metal-targets` under the logs folder. | | `SHARPEMU_METAL_V2_DUMP_MAX=` | Maximum dumps. Default 240. | diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalCommandStream.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalCommandStream.cs index 45aa93e8d..0acb8b6e0 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalCommandStream.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalCommandStream.cs @@ -2308,7 +2308,9 @@ private void EncodeLabelCopies(nint commandBuffer, ReadOnlySpan _ppUnlabelled = new(); + // The cause of the transfer being encoded (BeginTransfer), the name of the encoders it opens. + private string? _ppEncoderCause; + private static readonly string[] PassProfileCauseNames = Enum.GetNames(); + // Encoders recorded with no samples because the ring had wrapped onto unread ones. + private long _ppUnsampled; + + /// Device tests: receives what the profile prints for each completed submission. + internal Action? PassProfileOutputForTest { get; set; } + + /// Device tests: shared compute encoders opened, each of which the profile records as k=compute. + internal long ComputeEncodersOpenedForTest => Interlocked.Read(ref _computeEncodersOpened); private bool PassProfileReady() { @@ -111,6 +130,17 @@ private bool PassProfileReady() return false; } + // MTLCounterSamplingPoint: stage 0, draw 1, dispatch 2, tile dispatch 3, blit 4. Every + // encoder is sampled at its stage boundaries, through its pass descriptor's sample + // buffer attachments, which needs only the first. + var supportsSelector = MetalNative.Selector("supportsCounterSampling:"); + Console.Error.WriteLine( + "[METAL-V2][PASS-PROF] counter sampling: stage=1 " + + $"draw={(MetalNative.SendBool(_device, supportsSelector, 1) ? 1 : 0)} " + + $"dispatch={(MetalNative.SendBool(_device, supportsSelector, 2) ? 1 : 0)} " + + $"tile_dispatch={(MetalNative.SendBool(_device, supportsSelector, 3) ? 1 : 0)} " + + $"blit={(MetalNative.SendBool(_device, supportsSelector, 4) ? 1 : 0)}"); + var sets = MetalNative.Send(_device, MetalNative.Selector("counterSets")); var count = sets == 0 ? 0 : MetalV2Native.SendValue(sets, MetalNative.Selector("count")); for (nuint index = 0; index < count; index++) @@ -186,8 +216,10 @@ private nint PassProfileTakeBuffer() return buffer; } - // Reserves sample indices for one encoder of the submission being recorded. - private PassRecord? PassProfileReserve(string kind, int samples) + // Reserves sample indices for one encoder of the submission being recorded. With + // keepUnsampled an encoder the ring has no samples for is still recorded, with none, + // so it is named and placed in the submission (us=?). + private PassRecord? PassProfileReserve(string kind, int samples, bool keepUnsampled = false) { if (!PassProfileReady()) { @@ -214,7 +246,25 @@ private nint PassProfileTakeBuffer() { // The ring has wrapped onto samples not yet read: this encoder goes unsampled. _ppSkipped++; - return null; + if (!keepUnsampled) + { + return null; + } + + _ppUnsampled++; + MetalV2Diagnostics.WarnOnce("pass-profile-unsampled", + "[METAL-V2][PASS-PROF] the counter sample ring has wrapped onto unread samples: encoders are " + + "recorded with us=? and counted as unsampled= on the sub line."); + var unsampled = new PassRecord + { + Frame = _ppFrame, + Index = submission.Records.Count, + Kind = kind, + Buffer = -1, + }; + PassProfileTakeLeading(submission); + submission.Records.Add(unsampled); + return unsampled; } _ppCursorBuffer = next; @@ -232,20 +282,89 @@ private nint PassProfileTakeBuffer() }; _ppNextSample += samples; _ppOutstanding[_ppCursorBuffer]++; + PassProfileTakeLeading(submission); + submission.Records.Add(record); + return record; + } + + private void PassProfileTakeLeading(PassSubmission submission) + { if (_ppLeading is not null && submission.Records.Count == 0) { submission.Leading = string.Join(',', _ppLeading); _ppLeading = null; } + } - submission.Records.Add(record); - return record; + /// + /// Opens an encoder of the open command buffer with timestamps at its start and end and a + /// record of its own, named for site, or for the transfer being encoded when site is null. + /// Called only with the profile on, in place of the plain call. An encoder of another + /// command buffer (a prelude, a private one) is opened plain and not recorded: its records + /// would be resolved with a submission it is not part of. One the ring has no samples for + /// is opened plain and recorded unsampled. + /// + private nint PassProfileOpenEncoder(nint commandBuffer, MetalProfiledEncoder kind, string? site, bool concurrent = false) + { + var name = kind switch + { + MetalProfiledEncoder.Blit => "blit", + MetalProfiledEncoder.TilerCompute => "tiler-compute", + _ => "host-compute", + }; + var record = commandBuffer == _commandBuffer && commandBuffer != 0 + ? PassProfileReserve(name, 2, keepUnsampled: true) + : null; + if (record is not null) + { + if (site is not null) + { + // Its own operation: the encoders before it are done waiting for a label. + _ppUnlabelled.Clear(); + } + + record.Shape = site ?? _ppEncoderCause ?? "transfer"; + record.End = "end"; + _ppUnlabelled.Add(record); + _ppLast = record; + } + + if (record is null || record.Buffer < 0) + { + return kind == MetalProfiledEncoder.Blit + ? MetalNative.Send(commandBuffer, SelBlitEncoder) + : concurrent + ? MetalNative.Send(commandBuffer, SelComputeEncoderWithDispatchType, DispatchTypeConcurrent) + : MetalNative.Send(commandBuffer, SelComputeEncoder); + } + + var descriptor = kind == MetalProfiledEncoder.Blit + ? MetalNative.Send(MetalNative.Class("MTLBlitPassDescriptor"), MetalNative.Selector("blitPassDescriptor")) + : MetalNative.Send(MetalNative.Class("MTLComputePassDescriptor"), MetalNative.Selector("computePassDescriptor")); + var attachments = MetalNative.Send(descriptor, SelSampleBufferAttachments); + var slot = MetalNative.SendAtIndex(attachments, SelObjectAtIndex, 0); + MetalNative.SendVoid(slot, SelSetSampleBuffer, _ppBuffers[record.Buffer]); + MetalV2Native.SendVoidValue(slot, SelSetStartOfEncoderSampleIndex, (nuint)record.FirstSample); + MetalV2Native.SendVoidValue(slot, SelSetEndOfEncoderSampleIndex, (nuint)record.FirstSample + 1); + if (kind == MetalProfiledEncoder.Blit) + { + return MetalNative.Send(commandBuffer, SelBlitEncoderWithDescriptor, descriptor); + } + + // MTLDispatchType: serial 0, concurrent 1, as the plain call would have opened it. + MetalV2Native.SendVoidValue(descriptor, SelSetDispatchType, concurrent ? (nuint)DispatchTypeConcurrent : 0); + return MetalNative.Send(commandBuffer, SelComputeEncoderWithDescriptor, descriptor); } + nint IMetalSubmissionContext.OpenProfiledEncoder( + nint commandBuffer, MetalProfiledEncoder kind, string? site, bool concurrent) => + PassProfileOpenEncoder(commandBuffer, kind, site, concurrent); + /// Attaches stage-boundary timestamps to a render pass about to be encoded. private void PassProfileAttachRender(nint descriptor) { _ppOpen = null; + _ppUnlabelled.Clear(); var record = PassProfileReserve("render", 4); if (record is null) { @@ -318,6 +437,7 @@ private void PassProfileDescribe(in RenderingState state, long loadBytes, long s /// Opens a sampled compute encoder, or returns 0 to let the caller open a plain one. private nint PassProfileComputeEncoder(nint commandBuffer) { + _ppUnlabelled.Clear(); var record = PassProfileReserve("compute", 2); if (record is null) { @@ -473,6 +593,19 @@ private void PassProfileNoteBetween(string what) return; } + if (_ppUnlabelled.Count > 0) + { + // The transfer, clear or copy that opened them: what they did and on how much. + foreach (var record in _ppUnlabelled) + { + record.Shape = $"{record.Shape} {what}"; + } + + _ppUnlabelled.Clear(); + _ppEncoderCause = null; + return; + } + if (_ppLast is not null && _ppCurrent is not null && _ppCurrent.Records.Contains(_ppLast)) { (_ppLast.After ??= new List()).Add(what); @@ -492,6 +625,8 @@ private void PassProfileCommit(ulong serial, bool present) } _ppOpen = null; + _ppUnlabelled.Clear(); + _ppEncoderCause = null; if (_ppCurrent is not null) { _ppInFlight[serial] = _ppCurrent; @@ -543,9 +678,24 @@ private void PassProfileResolve(ulong serial, bool completed, double gpuSeconds) ulong lastEnd = 0; ulong firstStart = ulong.MaxValue; var lines = new System.Text.StringBuilder(); + var kindMicroseconds = new SortedDictionary(StringComparer.Ordinal); + var gaps = 0.0; + var unsampled = 0; foreach (var record in submission.Records) { Array.Clear(values); + if (record.Buffer < 0) + { + // Recorded with no samples (the ring had wrapped): named and placed, not timed. + unsampled++; + lines.Append(string.Create( + culture, + $"[METAL-V2][PASS-PROF] f={submission.Frame} s={serial} i={record.Index} k={record.Kind} " + + $"us=? gap_us=? draws={record.Draws} tg=0 ld_mb=0.0 st_mb=0.0 end={record.End} " + + $"a=[{record.Shape}] sh=[-] after=[-] n_after={record.After?.Count ?? 0} joins=0")).Append('\n'); + continue; + } + var data = MetalV2Native.SendRange( _ppBuffers[record.Buffer], SelResolveCounterRange, (nuint)record.FirstSample, (nuint)record.SampleCount); _ppOutstanding[record.Buffer]--; @@ -591,6 +741,8 @@ private void PassProfileResolve(ulong serial, bool completed, double gpuSeconds) } sum += microseconds; + gaps += Math.Max(gap, 0.0); + kindMicroseconds[record.Kind] = kindMicroseconds.GetValueOrDefault(record.Kind) + microseconds; var shaders = record.Shaders is null ? "-" : string.Join(';', record.Shaders.OrderByDescending(pair => pair.Value).Take(6) @@ -613,7 +765,11 @@ private void PassProfileResolve(ulong serial, bool completed, double gpuSeconds) culture, $"[METAL-V2][PASS-PROF] sub f={submission.Frame} s={serial} encoders={submission.Records.Count} " + $"enc_ms={sum / 1000.0:F2} span_ms={span / 1000.0:F2} gpu_ms={gpuSeconds * 1000.0:F2} " + - $"skipped={_ppSkipped} leading=[{submission.Leading}]")); - Console.Error.WriteLine(lines.ToString()); + $"skipped={_ppSkipped} leading=[{submission.Leading}] " + + $"kind_us=[{string.Join(',', kindMicroseconds.Select(pair => string.Create(culture, $"{pair.Key}:{pair.Value:F0}")))}] " + + $"gaps_us={gaps:F0} unsampled={unsampled} unsampled_total={_ppUnsampled}")); + var text = lines.ToString(); + Console.Error.WriteLine(text); + PassProfileOutputForTest?.Invoke(text); } } diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.TargetDump.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.TargetDump.cs index 45f1db43e..e5a208d9e 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.TargetDump.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.TargetDump.cs @@ -397,7 +397,9 @@ private bool TrySnapshotTexture(nint texture, string label) } var readback = _guestMemory.CreateReportBuffer(total * depth, "SharpEmu TargetSnapshot", out var contents, out _); - var blit = MetalNative.Send(EnsureCommandBuffer(), SelBlitEncoder); + var blit = PassProfileEnabled + ? PassProfileOpenEncoder(EnsureCommandBuffer(), MetalProfiledEncoder.Blit, "target-snapshot") + : MetalNative.Send(EnsureCommandBuffer(), SelBlitEncoder); MetalMemoryTelemetry.BlitEncoders.Add(); if (blit == 0) { @@ -748,7 +750,9 @@ private bool TryReadTextureRgba( try { EndEncoders(PassEndCause.Other); - var blit = MetalNative.Send(EnsureCommandBuffer(), SelBlitEncoder); + var blit = PassProfileEnabled + ? PassProfileOpenEncoder(EnsureCommandBuffer(), MetalProfiledEncoder.Blit, "target-dump") + : MetalNative.Send(EnsureCommandBuffer(), SelBlitEncoder); MetalMemoryTelemetry.BlitEncoders.Add(); if (blit == 0) { diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.TextureStats.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.TextureStats.cs index 5d0dd2759..36a0004c4 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.TextureStats.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.TextureStats.cs @@ -87,7 +87,9 @@ private unsafe void DumpTextureStats(nint texture, string label) try { EndEncoders(PassEndCause.Other); - var encoder = MetalNative.Send(EnsureCommandBuffer(), SelLodStatsComputeEncoder); + var encoder = PassProfileEnabled + ? PassProfileOpenEncoder(EnsureCommandBuffer(), MetalProfiledEncoder.HostCompute, "texture-stats") + : MetalNative.Send(EnsureCommandBuffer(), SelLodStatsComputeEncoder); if (encoder == 0) { return; diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.cs index a6edfba87..6860f2b5d 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.cs @@ -416,6 +416,9 @@ private IMetalSubmissionContext BeginTransferTouching(MetalTransferCause cause, if (PassProfileEnabled) { _ppTransferCause = $"transfer:{cause}"; + // A new transfer: the encoders it opens are named for its cause until it labels them. + _ppUnlabelled.Clear(); + _ppEncoderCause = PassProfileCauseNames[(int)cause]; } if (_preparation is null) @@ -1700,7 +1703,9 @@ public void FillGuestMemory(ulong address, ulong size, uint value, bool allowHos } var context = ((IMetalImageCacheOwner)this).BeginTransfer(MetalTransferCause.GuestFill); - var encoder = MetalNative.Send(context.CommandBuffer, SelBlitEncoder); + var encoder = PassProfileEnabled + ? PassProfileOpenEncoder(context.CommandBuffer, MetalProfiledEncoder.Blit, "GuestFill") + : MetalNative.Send(context.CommandBuffer, SelBlitEncoder); MetalMemoryTelemetry.BlitEncoders.Add(); if (encoder == 0) { @@ -1876,7 +1881,9 @@ public void CopyGuestMemory(ulong destination, ulong source, ulong size, bool al } var context = ((IMetalImageCacheOwner)this).BeginTransfer(MetalTransferCause.GuestCopy); - var encoder = MetalNative.Send(context.CommandBuffer, SelBlitEncoder); + var encoder = PassProfileEnabled + ? PassProfileOpenEncoder(context.CommandBuffer, MetalProfiledEncoder.Blit, "GuestCopy") + : MetalNative.Send(context.CommandBuffer, SelBlitEncoder); MetalMemoryTelemetry.BlitEncoders.Add(); if (encoder == 0) { diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalStagedStorage.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalStagedStorage.cs index 0e3bdaa14..0cd3e704d 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalStagedStorage.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalStagedStorage.cs @@ -369,7 +369,10 @@ public void EndSubmission() if (encoder == 0) { - encoder = MetalNative.Send(commandBuffer, SelComputeEncoder); + encoder = MetalRenderHost.PassProfileEnabled + ? MetalTiler.ProfiledEncoder( + ordering, commandBuffer, MetalProfiledEncoder.HostCompute, "staged-store-writeback", false) + : MetalNative.Send(commandBuffer, SelComputeEncoder); MetalMemoryTelemetry.ComputeEncoders.Add(); if (encoder == 0) { @@ -541,7 +544,9 @@ public bool TryEncodeWholeGather(nint commandBuffer, ulong address, in MetalGues private static nint BlitEncoder(nint commandBuffer, IMetalSubmissionContext? ordering) { - var encoder = MetalNative.Send(commandBuffer, SelBlitEncoder); + var encoder = MetalRenderHost.PassProfileEnabled + ? MetalTiler.ProfiledEncoder(ordering, commandBuffer, MetalProfiledEncoder.Blit, "staged-storage", false) + : MetalNative.Send(commandBuffer, SelBlitEncoder); MetalMemoryTelemetry.BlitEncoders.Add(); if (encoder == 0) { diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalTiler.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalTiler.cs index 7b630e2a6..e476c1fd9 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalTiler.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalTiler.cs @@ -222,7 +222,9 @@ public MetalBufferSpan Acquire(IMetalSubmissionContext context, ulong size) => public nint BeginCompute(IMetalSubmissionContext context, bool concurrent = false) { context.ReleaseSharedEncoder(); - var encoder = concurrent && ConcurrentDispatch + var encoder = MetalRenderHost.PassProfileEnabled + ? ProfiledEncoder(context, context.CommandBuffer, MetalProfiledEncoder.TilerCompute, null, concurrent && ConcurrentDispatch) + : concurrent && ConcurrentDispatch ? MetalNative.Send(context.CommandBuffer, SelComputeEncoderWithDispatchType, DispatchTypeConcurrent) : MetalNative.Send(context.CommandBuffer, SelComputeEncoder); MetalMemoryTelemetry.ComputeEncoders.Add(); @@ -251,7 +253,9 @@ public static void Barrier(nint encoder) public nint BeginBlit(IMetalSubmissionContext context) { context.ReleaseSharedEncoder(); - var encoder = MetalNative.Send(context.CommandBuffer, SelBlitEncoder); + var encoder = MetalRenderHost.PassProfileEnabled + ? ProfiledEncoder(context, context.CommandBuffer, MetalProfiledEncoder.Blit, null, concurrent: false) + : MetalNative.Send(context.CommandBuffer, SelBlitEncoder); MetalMemoryTelemetry.BlitEncoders.Add(); if (encoder == 0) { @@ -262,6 +266,27 @@ public nint BeginBlit(IMetalSubmissionContext context) return encoder; } + /// + /// Under SHARPEMU_METAL_V2_PROFILE_PASSES=1, in place of the plain call: the encoder the + /// context opens timed (named site, or the transfer's cause when null), or the plain one + /// for a context that records no profile (a prelude buffer, a test harness). + /// + internal static nint ProfiledEncoder( + IMetalSubmissionContext? context, nint commandBuffer, MetalProfiledEncoder kind, string? site, bool concurrent) + { + var encoder = context?.OpenProfiledEncoder(commandBuffer, kind, site, concurrent) ?? 0; + if (encoder != 0) + { + return encoder; + } + + return kind == MetalProfiledEncoder.Blit + ? MetalNative.Send(commandBuffer, SelBlitEncoder) + : concurrent + ? MetalNative.Send(commandBuffer, SelComputeEncoderWithDispatchType, DispatchTypeConcurrent) + : MetalNative.Send(commandBuffer, SelComputeEncoder); + } + // Ends an encoder outside any ordering (tests that drive the tiler on their own). public static void EndEncoding(nint encoder) => MetalNative.SendVoid(encoder, SelEndEncoding); diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalV2Contracts.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalV2Contracts.cs index 25cf69ae1..779a62fc6 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalV2Contracts.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalV2Contracts.cs @@ -80,6 +80,30 @@ void EncoderEnding(nint encoder, bool render) _ = encoder; _ = render; } + + // Profiling only, called only under SHARPEMU_METAL_V2_PROFILE_PASSES=1 in place of the + // plain blitCommandEncoder / computeCommandEncoder call: opens that encoder on + // commandBuffer through its pass descriptor with GPU timestamps at its start and end, and + // records it under site (or under the transfer being encoded when site is null). Zero + // tells the caller to open the plain encoder itself: a context that records no profile. + nint OpenProfiledEncoder(nint commandBuffer, MetalProfiledEncoder kind, string? site, bool concurrent) + { + _ = commandBuffer; + _ = kind; + _ = site; + _ = concurrent; + return 0; + } +} + +// The encoders the pass profile times besides render passes and the shared compute encoder. +internal enum MetalProfiledEncoder +{ + Blit, + // A compute encoder the tiler opens for a transfer of its own. + TilerCompute, + // A compute encoder the host opens outside the shared one (occlusion, labels, stores). + HostCompute, } // Moves image contents between guest memory and Metal textures entirely on the GPU. diff --git a/tests/SharpEmu.Gpu.Metal.Tests/MetalPassProfileTests.cs b/tests/SharpEmu.Gpu.Metal.Tests/MetalPassProfileTests.cs new file mode 100644 index 000000000..aaa0a8426 --- /dev/null +++ b/tests/SharpEmu.Gpu.Metal.Tests/MetalPassProfileTests.cs @@ -0,0 +1,118 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using System.Globalization; +using System.Text.RegularExpressions; +using SharpEmu.Gpu.Metal.V2; +using SharpEmu.Libs.Gpu.Abstractions; +using Xunit; +using Xunit.Abstractions; + +namespace SharpEmu.Gpu.Metal.Tests; + +/// +/// SHARPEMU_METAL_V2_PROFILE_PASSES=1 times every encoder the host opens on the command buffer +/// it records, not only render passes and the shared compute encoder: an upload, a guest fill +/// and a writeback made through the host's own paths each come out as a blit or tiler-compute +/// record of their own, timed and named, while render and compute records stay one per encoder. +/// Device work is behind the exclusive device gate. +/// +public sealed partial class MetalPassProfileTests(ITestOutputHelper output) +{ + private const uint Width = 64; + private const uint Height = 8; + private const ulong TargetAddress = MetalPassRig.GuestBase + 0x10000; + private const ulong FillAddress = MetalPassRig.GuestBase + 0x40000; + private const ulong FillBytes = 0xC000; + + [GeneratedRegex(@"\[METAL-V2\]\[PASS-PROF\] f=\d+ s=\d+ i=\d+ k=(\S+) us=(\S+) .* a=\[(.*?)\] sh=")] + private static partial Regex RecordLine(); + + private sealed record Record(string Kind, string Microseconds, string Label); + + [Fact] + public void UploadsFillsAndWritebacksGetTimedRecordsOfTheirOwn() + { + if (!RequireDevice()) return; + var saved = MetalRenderHost.PassProfileEnabled; + MetalRenderHost.PassProfileEnabled = true; + try + { + using var rig = new MetalPassRig(Device.Value, 1024 * 1024); + var host = rig.Host; + var printed = new List(); + host.PassProfileOutputForTest = printed.Add; + host.DeferPassFills = false; + host.FillsShareCompute = false; + var formats = new[] { GpuFormat.R8G8B8A8Unorm }; + // The left half: the right half keeps what the target held, so the pass loads it. + var red = rig.Pipeline(formats, ["1.0f, 0.0f, 0.0f, 1.0f"], -1f, 0f); + // What the guest left in the target: its first use uploads it. + rig.WriteRaw(TargetAddress, Enumerable.Repeat((byte)0x40, (int)(Width * Height * 4)).ToArray()); + var passes = host.RenderPassSerial; + var computes = host.ComputeEncodersOpenedForTest; + var target = rig.MakeTarget(TargetAddress, GpuFormat.R8G8B8A8Unorm, Width, Height); + using (host.BeginPreparation()) + { + rig.Draw(red, [target]); + host.EndRendering(); + } + + host.FillGuestMemory(FillAddress, FillBytes, 0xA1B2C3D4u, allowHost: false); + // The CPU reads what the draw wrote: the target is written back. + var pixels = rig.Read(TargetAddress, Width * Height * 4); + _ = host.TakeGpuBusySecondsWhenIdle(); + passes = host.RenderPassSerial - passes; + computes = host.ComputeEncodersOpenedForTest - computes; + + foreach (var line in printed) + { + output.WriteLine(line); + } + + Assert.Equal(0xFF, pixels[0]); + Assert.Equal(0x40, pixels[(Width - 1) * 4]); + Assert.Equal(0xA1B2C3D4u, BitConverter.ToUInt32(rig.Read(FillAddress, 4))); + var records = printed.SelectMany(text => text.Split('\n')) + .Select(line => RecordLine().Match(line)) + .Where(match => match.Success) + .Select(match => new Record(match.Groups[1].Value, match.Groups[2].Value, match.Groups[3].Value)) + .ToList(); + Assert.Equal(passes, records.Count(record => record.Kind == "render")); + Assert.Equal(computes, records.Count(record => record.Kind == "compute")); + AssertTimed(records, "Upload"); + AssertTimed(records, "GuestFill fill bytes=0xC000"); + AssertTimed(records, "Writeback"); + } + finally + { + MetalRenderHost.PassProfileEnabled = saved; + } + } + + private static void AssertTimed(List records, string label) + { + var record = records.FirstOrDefault(record => + record.Kind is "blit" or "tiler-compute" && record.Label.StartsWith(label, StringComparison.Ordinal)); + Assert.True(record is not null, $"no blit or tiler-compute record labelled '{label}'"); + Assert.True( + double.TryParse(record.Microseconds, NumberStyles.Float, CultureInfo.InvariantCulture, out var microseconds) && + microseconds > 0, + $"record '{record.Label}' has us={record.Microseconds}"); + } + + private bool RequireDevice() + { + if (Environment.GetEnvironmentVariable("SHARPEMU_TEST_REQUIRE_DEVICE") != "1") + { + output.WriteLine("The pass profile samples the device only behind the exclusive device gate."); + return false; + } + + Assert.True(OperatingSystem.IsMacOS()); + Assert.NotEqual(0, Device.Value); + return true; + } + + private static readonly Lazy Device = new(MetalNative.MTLCreateSystemDefaultDevice); +} From 82d5e5213cf268184bcc0acae57a152edf7a6057 Mon Sep 17 00:00:00 2001 From: kuba Date: Tue, 17 Nov 2026 05:00:31 +0000 Subject: [PATCH 167/178] [GPU] Diagnostic: drop every draw after a set time to measure the frame floor SHARPEMU_DIAG_SKIP_ALL_DRAWS_AFTER_S= drops draws at translation, before they are resolved or recorded; dispatches, labels and flips go on. Demon's Souls at the 540p scene cap: 23.5 ms per frame with it against 65-76 ms without, in the same run. --- docs/macos/configuration.md | 1 + .../Agc/AgcExports.CommandStream.cs | 40 +++++++++++++++++++ 2 files changed, 41 insertions(+) diff --git a/docs/macos/configuration.md b/docs/macos/configuration.md index bf6ab48e1..cce94de7a 100644 --- a/docs/macos/configuration.md +++ b/docs/macos/configuration.md @@ -121,6 +121,7 @@ undoes an optimization to isolate a miscompile: | `SHARPEMU_METAL_V2_PROFILE_SHADERS=1` | Gives every draw and dispatch its own command buffer and prints GPU time per shader hash (`[METAL-V2][SHADER-PROF]`). It serializes the GPU, so only ratios are meaningful. | | `SHARPEMU_METAL_V2_PROFILE_TOP=` | Entries per profile report. Default 8. | | `SHARPEMU_METAL_V2_PROFILE_PASSES=1` | Per-encoder GPU time (`[METAL-V2][PASS-PROF]`). Blit encoders (`k=blit`), the tiler's compute encoders (`k=tiler-compute`) and the host's other compute encoders (`k=host-compute`) are recorded too, named for the transfer that opened them, so `gap_us` is time no encoder ran; the `sub` line sums GPU time per kind (`kind_us=`). | +| `SHARPEMU_DIAG_SKIP_ALL_DRAWS_AFTER_S=` | Diagnostic. From that many seconds after the GPU process translated its first draw, every draw is dropped before it is resolved or recorded; dispatches, labels and flips go on. Shows the frame time a draw path of no cost would leave. The picture is wrong by design; logged once when it starts. | | `SHARPEMU_PROFILE_RENDER=1` | Per-phase timing of the draw translation path on the GPU worker, reported at each flip. | | `SHARPEMU_METAL_V2_DUMP_TARGETS=` | Writes each render pass's color target and each presented frame as PNG. Waits for the GPU after each dump. `1` writes to `metal-targets` under the logs folder. | | `SHARPEMU_METAL_V2_DUMP_MAX=` | Maximum dumps. Default 240. | diff --git a/src/SharpEmu.Libs/Agc/AgcExports.CommandStream.cs b/src/SharpEmu.Libs/Agc/AgcExports.CommandStream.cs index 0d04bcd0e..e212bbba1 100644 --- a/src/SharpEmu.Libs/Agc/AgcExports.CommandStream.cs +++ b/src/SharpEmu.Libs/Agc/AgcExports.CommandStream.cs @@ -681,6 +681,38 @@ internal void CompleteDeferred(DeferredWork work) } } + // SHARPEMU_DIAG_SKIP_ALL_DRAWS_AFTER_S=: from that many seconds after this process started, every draw + // is dropped at translation, before its program is resolved or anything is recorded. Dispatches, labels and + // flips go on. It measures the frame time a draw path of no cost would leave; the picture is wrong by design. + private static class DrawFloorProbe + { + private static readonly long Started = Environment.TickCount64; + private static readonly long AfterMilliseconds = + double.TryParse(Environment.GetEnvironmentVariable("SHARPEMU_DIAG_SKIP_ALL_DRAWS_AFTER_S"), + System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture, out var seconds) && seconds >= 0 + ? (long)(seconds * 1000) + : -1; + private static int _announced; + + public static bool Active + { + get + { + if (AfterMilliseconds < 0 || Environment.TickCount64 - Started < AfterMilliseconds) + { + return false; + } + + if (Interlocked.Exchange(ref _announced, 1) == 0) + { + Console.Error.WriteLine("[GPU][DIAG] SHARPEMU_DIAG_SKIP_ALL_DRAWS_AFTER_S: every draw is dropped from now on; the picture is wrong by design."); + } + + return true; + } + } + } + private bool TryRunExecutorDraw(ulong submitId, SubmittedDcbState state, bool indexed, in DrawIndexedArguments indexedArguments, in DrawAutoArguments autoArguments) { Diagnostics.DispatchRunTally.NoteDraw(); @@ -699,6 +731,14 @@ private bool TryRunExecutorDraw(ulong submitId, SubmittedDcbState state, bool in state.FrameDrawCount++; state.SawIndexedDraw |= indexed; + if (DrawFloorProbe.Active) + { + // Diagnostic floor: the draw is dropped before it is resolved or recorded (the picture is wrong). + state.CurrentIndexSnapshot = null; + state.CurrentVertexSnapshot = null; + return true; + } + if (_defersWholeWork && (_parallel is not null || producing)) { var snapshot = banks.Snapshot(); From e18e31a206c0e9bab33a3875045ed1dfac49caf7 Mon Sep 17 00:00:00 2001 From: kuba Date: Tue, 17 Nov 2026 05:28:33 +0000 Subject: [PATCH 168/178] [GPU] Answer kept and rebound dispatches off the shared resolve lock with shards 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, completes on its own thread (this thread's kept programs, runtime inputs, user data memo and lookup options) without the shared tier; anything else (a replan, shader calls, traces, a cached materialization, a new permutation, the identity recheck) still takes it. SHARPEMU_RESOLVE_UNSHARED_COMPUTE=0 sends every dispatch through the shared lock. One shard is unchanged. The shared lock's takes and wait are split by reason in the prefetch counters (shared_by=, shared_wait_by=), with the dispatches answered off it (unshared_compute=) and why a rebinding still took it (rebind_shared_by=); the resolvers' sampled allocation is split by path and step (alloc_by_path=, alloc_by_step=). A retry's read log is bound to the thread that set it, so another resolver's guest reads are never logged into it. --- docs/macos/configuration.md | 1 + .../Gpu/Pipelines/ShaderPipelineCache.cs | 252 ++++++++++++++++-- .../Gpu/Pipelines/ShaderProgramCache.cs | 152 ++++++++++- .../Gpu/Rendering/ParallelProgramPrefetch.cs | 78 +++++- .../ComputeProgramReuseTests.Shards.cs | 90 +++++++ .../Gpu/Pipelines/ComputeProgramReuseTests.cs | 2 +- 6 files changed, 553 insertions(+), 22 deletions(-) create mode 100644 tests/SharpEmu.Libs.Tests/Gpu/Pipelines/ComputeProgramReuseTests.Shards.cs diff --git a/docs/macos/configuration.md b/docs/macos/configuration.md index cce94de7a..b7910a9c5 100644 --- a/docs/macos/configuration.md +++ b/docs/macos/configuration.md @@ -70,6 +70,7 @@ them for measurements or to isolate a problem. | `SHARPEMU_METAL_V2_ASYNC_PIPELINES` | on | `0` builds pipeline states on the GPU worker thread. | | `SHARPEMU_METAL_V2_ASYNC_LIBRARIES` | on | `0` compiles each shader library on the thread that needs it, not on the compile pool. | | `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_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=`). | | `SHARPEMU_METAL_V2_PIPELINE_LIMIT` | `8192` | Pipeline states kept before idle ones are released. `0` is unlimited. | | `SHARPEMU_METAL_V2_MODULE_LIMIT` | `2048` | The same for shader modules. | | `SHARPEMU_METAL_V2_SHADER_EVICTION` | on | `0` keeps every pipeline and module. | diff --git a/src/SharpEmu.Libs/Gpu/Pipelines/ShaderPipelineCache.cs b/src/SharpEmu.Libs/Gpu/Pipelines/ShaderPipelineCache.cs index 445048639..2d7096afe 100644 --- a/src/SharpEmu.Libs/Gpu/Pipelines/ShaderPipelineCache.cs +++ b/src/SharpEmu.Libs/Gpu/Pipelines/ShaderPipelineCache.cs @@ -362,17 +362,80 @@ public int ResolveShardOf(RegisterBanks banks, bool compute) => [ThreadStatic] private static int t_shardedDepth; + // How this thread's last resolution was answered, for the prefetch's allocation sample by path (alloc_by_path=). + internal enum ResolvePath : byte + { + Other, // refused, abandoned, or a path not named here + DrawHit, // the shard memo's entry, revalidated + DrawRebuilt, // the entry rebuilt from its words revalidation + DrawFull, // a full graphics resolution (memo miss) + ComputeKept, // the kept compute program + ComputeRebound, // the kept program rebound to new user data + ComputeResolve, // a full compute resolution + Count, + } + + internal static readonly string[] ResolvePathNames = ["other", "draw_hit", "draw_rebuilt", "draw_full", "compute_kept", "compute_rebound", "compute_resolve"]; + + [ThreadStatic] + internal static ResolvePath t_resolvePath; + + // Why a resolution took the shared tier (shared_by= and shared_wait_by= in TakeShardReport). + internal enum SharedReason + { + DrawNew, // a draw whose key the shard's memo does not hold + DrawMiss, // a draw whose memo entry missed for another reason, or that cannot be kept (uncacheable) + DrawUnsharded, // a draw resolved without a shard's memo (memo off) + Nested, // a draw resolved inside another resolution on one thread (ResolveNestedShared) + Verify, // RESOLVE_MEMO=verify's full resolutions + ComputeResolve, // a dispatch with no kept program of its shape: resolved in full + ComputeRebind, // a kept program's rebinding that the shared tier has to make (rebind_shared_by=) + ComputeWorker, // a dispatch resolved where the kernel may be predicted (the worker with predictions on) + ComputeRetry, // a dispatch that may suspend on its pipeline (ComputeProgramRetry) + Other, // tessellation, mesh and register-form resolutions, frontend fallback compiles + Count, + } + + private static readonly string[] SharedReasonNames = + ["draw_new", "draw_miss", "draw_unsharded", "nested", "verify", "compute_resolve", "compute_rebind", "compute_worker", "compute_retry", "other"]; + + private static readonly ThreadCounter[] _sharedTakesBy = Enumerable.Range(0, (int)SharedReason.Count).Select(_ => new ThreadCounter()).ToArray(); + private static readonly ThreadCounter[] _sharedWaitTicksBy = Enumerable.Range(0, (int)SharedReason.Count).Select(_ => new ThreadCounter()).ToArray(); + + // Dispatches answered off the shared tier with shards (kept, rebound), and the rebindings it had to make, by why. + private static readonly ThreadCounter _unsharedComputeKept = new(); + private static readonly ThreadCounter _unsharedComputeRebound = new(); + private static readonly ThreadCounter[] _rebindSharedBy = + Enumerable.Range(0, (int)ShaderProgramCache.UnsharedRefusal.Count).Select(_ => new ThreadCounter()).ToArray(); + public static string TakeShardReport() { static string Milliseconds(long ticks) => (ticks * 1000.0 / System.Diagnostics.Stopwatch.Frequency).ToString("F1", System.Globalization.CultureInfo.InvariantCulture); + var by = new System.Text.StringBuilder(); + var waitBy = new System.Text.StringBuilder(); + for (var index = 0; index < (int)SharedReason.Count; index++) + { + var separator = index == 0 ? "" : ","; + by.Append(separator).Append(SharedReasonNames[index]).Append('=').Append(_sharedTakesBy[index].Take()); + waitBy.Append(separator).Append(SharedReasonNames[index]).Append('=').Append(Milliseconds(_sharedWaitTicksBy[index].Take())); + } + + var rebind = new System.Text.StringBuilder(); + for (var index = 0; index < (int)ShaderProgramCache.UnsharedRefusal.Count; index++) + { + rebind.Append(index == 0 ? "" : ",").Append(ShaderProgramCache.UnsharedRefusalNames[index]).Append('=').Append(_rebindSharedBy[index].Take()); + } + return FormattableString.Invariant($"shared_takes={_sharedTakes.Take()} shared_wait_ms={Milliseconds(_sharedWaitTicks.Take())} ") + FormattableString.Invariant($"shard_wait_ms={Milliseconds(_shardWaitTicks.Take())} sharded_draws={_shardedDraws.Take()} ") + - FormattableString.Invariant($"nested_shared={_nestedShared.Take()} materialization_shared={ShaderProgramCache.TakeMaterializationGateTakes()}"); + FormattableString.Invariant($"nested_shared={_nestedShared.Take()} materialization_shared={ShaderProgramCache.TakeMaterializationGateTakes()} ") + + FormattableString.Invariant($"shared_by=({by}) shared_wait_by=({waitBy}) ") + + FormattableString.Invariant($"unshared_compute=(kept={_unsharedComputeKept.Take()},rebound={_unsharedComputeRebound.Take()}) rebind_shared_by=({rebind})"); } - // The shared tier's gate; timed and counted with shards (with one shard, exactly the lock it always was). - private void EnterShared() + // The shared tier's gate; timed and counted by reason with shards (with one shard, exactly the lock it always was). + private void EnterShared(SharedReason reason) { if (_shards.Length == 1) { @@ -381,6 +444,7 @@ private void EnterShared() } _sharedTakes.Increment(); + _sharedTakesBy[(int)reason].Increment(); if (Monitor.TryEnter(_resolveGate)) { return; @@ -388,13 +452,28 @@ private void EnterShared() var started = System.Diagnostics.Stopwatch.GetTimestamp(); Monitor.Enter(_resolveGate); - _sharedWaitTicks.Add(System.Diagnostics.Stopwatch.GetTimestamp() - started); + var waited = System.Diagnostics.Stopwatch.GetTimestamp() - started; + _sharedWaitTicks.Add(waited); + _sharedWaitTicksBy[(int)reason].Add(waited); + } + + // EnterShared for a block (using): the forms that held the gate with a lock statement. + private SharedScope EnterSharedScope(SharedReason reason) + { + EnterShared(reason); + return new SharedScope(_resolveGate); + } + + private readonly ref struct SharedScope(object gate) + { + public void Dispose() => Monitor.Exit(gate); } // A full resolution under the shared tier (with one shard the caller already holds it: re-entered). - private GraphicsPrograms ResolveFullShared(RegisterBanks banks, ReadOnlySpan targetExportMapping, in KeptGraphicsFlags flags) + private GraphicsPrograms ResolveFullShared(RegisterBanks banks, ReadOnlySpan targetExportMapping, in KeptGraphicsFlags flags, + SharedReason reason) { - EnterShared(); + EnterShared(reason); try { return ResolveFull(banks, targetExportMapping, flags); @@ -444,7 +523,7 @@ private GraphicsPrograms ResolveNestedShared(RegisterBanks banks, ReadOnlySpan targetExportMapping, in KeptGraphicsFlags flags) { - var full = ResolveFullShared(banks, targetExportMapping, flags); + var full = ResolveFullShared(banks, targetExportMapping, flags, SharedReason.Verify); GraphicsResolveMemo.NoteVerified(); var difference = GraphicsProgramsComparer.Difference(memoPrograms, full); if (difference is null) @@ -1072,7 +1156,7 @@ private GraphicsPrograms VerifyResolveMemo(GraphicsResolveMemo memo, GraphicsRes return full; } - var again = ResolveFullShared(banks, targetExportMapping, flags); + var again = ResolveFullShared(banks, targetExportMapping, flags, SharedReason.Verify); if (GraphicsProgramsComparer.Difference(memoPrograms, again) is not { } againDifference) { GraphicsResolveMemo.NoteVerifyRaced(ResolveMemoVerifyRace.CameAndWent); @@ -1392,7 +1476,7 @@ public static uint TessellationMaxFactor(uint maxLevelBits) TessellationMaxFactor(shaderInterface.MaxTessellationLevel), quad); using var waitScope = RenderPhaseProfile.MeasureDetail(RenderPhaseProfile.Phase.GraphicsResolveLockWait); - lock (_resolveGate) + using (EnterSharedScope(SharedReason.Other)) { using var workScope = RenderPhaseProfile.MeasureDetail(RenderPhaseProfile.Phase.ProgramPreparation); var started = TraceTessellationPrograms ? System.Diagnostics.Stopwatch.GetTimestamp() : 0; @@ -1533,7 +1617,7 @@ private GraphicsPrograms GetGraphicsProgramsCore( MeshDrawConfiguration? mesh) { using var waitScope = RenderPhaseProfile.MeasureDetail(RenderPhaseProfile.Phase.GraphicsResolveLockWait); - lock (_resolveGate) + using (EnterSharedScope(SharedReason.Other)) { using var workScope = RenderPhaseProfile.MeasureDetail(RenderPhaseProfile.Phase.ProgramPreparation); return ResolveGraphicsProgramsCore(vertex, pixel, shaderInterface, context, targetExportMapping, pixelActive, depthBound, @@ -2195,8 +2279,24 @@ public ComputeProgram GetComputeProgram(RegisterBanks banks, uint dispatchInitia { refusal = ComputePrefetchRefusal.None; var compute = banks.Shader.Compute; + var sharedReason = retry is not null ? SharedReason.ComputeRetry : SharedReason.ComputeResolve; + // With shards, a dispatch whose kept program holds or rebinds off the shared tier never takes it (the kept programs + // are this thread's own); the worker's form only where it predicts nothing (WithPrediction returns the program). + if (_shards.Length > 1 && UnsharedCompute && retry is null && !Monitor.IsEntered(_resolveGate)) + { + if (!ahead && PredictsKernels) + { + sharedReason = SharedReason.ComputeWorker; + } + else if (TryGetComputeProgramUnshared(compute, dispatchInitiator, dimensionX, dimensionY, dimensionZ, indirect, ahead, + out var unshared, out refusal, ref sharedReason)) + { + return unshared; + } + } + using var waitScope = RenderPhaseProfile.MeasureDetail(RenderPhaseProfile.Phase.ComputeResolveLockWait); - EnterShared(); + EnterShared(sharedReason); try { using var workScope = RenderPhaseProfile.MeasureDetail(RenderPhaseProfile.Phase.ProgramPreparation); @@ -2237,6 +2337,7 @@ public ComputeProgram GetComputeProgram(RegisterBanks banks, uint dispatchInitia SameUserScalars(previousRegisters.UserScalars, compute.UserScalars, compute.UserScalarCount) && _programs.Revalidate(previous.Input.Stage)) { _computeKept.Increment(); + t_resolvePath = ResolvePath.ComputeKept; return ahead ? Ahead(previous, kept.Kernel, kept.Source, out refusal) : WithPrediction(previous, kept.Kernel, kept.Source, kept.SystemRegisters, compute, dimensionX, dimensionY, dimensionZ, indirect); @@ -2245,6 +2346,7 @@ public ComputeProgram GetComputeProgram(RegisterBanks banks, uint dispatchInitia if (kept.Entry is { } entry && ++kept.Rebinds % IdentityRecheckPeriod != 0) { _computeRebound.Increment(); + t_resolvePath = ResolvePath.ComputeRebound; var rebound = RebindComputeProgram(kept, entry, compute, dispatchInitiator, dimensionX, dimensionY, dimensionZ); KeepComputeProgram(kept, rebound, compute, dimensionX, dimensionY, dimensionZ); return ahead @@ -2254,6 +2356,7 @@ public ComputeProgram GetComputeProgram(RegisterBanks banks, uint dispatchInitia } _computeResolved.Increment(); + t_resolvePath = ResolvePath.ComputeResolve; var program = GetComputeProgramCore(compute, dispatchInitiator, dimensionX, dimensionY, dimensionZ, retry: null, out var source, out var systemRegisters, out var decoded, ahead); if (program.ImageCopy is not null) @@ -2285,6 +2388,119 @@ public ComputeProgram GetComputeProgram(RegisterBanks banks, uint dispatchInitia } } + // GetComputeProgramKept's kept and rebound answers without the shared tier (shards only): true with the answer, false + // with why the shared tier must make it (reason), having changed nothing the shared path reads differently. + private bool TryGetComputeProgramUnshared(ComputeStageRegisters compute, uint dispatchInitiator, uint dimensionX, uint dimensionY, uint dimensionZ, + bool indirect, bool ahead, out ComputeProgram? result, out ComputePrefetchRefusal refusal, ref SharedReason reason) + { + result = null; + refusal = ComputePrefetchRefusal.None; + if (ahead && _registry.HasFrontend) + { + refusal = ComputePrefetchRefusal.Frontend; + return true; + } + + if (DrawReuseDisabled || _registry.HasFrontend) + { + return false; + } + + var registrations = ShaderHeaderRegistry.Registrations; + ClaimKeptPrograms(); + if (_keptComputes is not { } all || !all.TryGetValue(compute.Address, out var keptList)) + { + return false; + } + + KeptComputeProgram? kept = null; + foreach (var candidate in keptList) + { + if (candidate.Registrations == registrations && candidate.DispatchInitiator == dispatchInitiator && SameComputeShape(candidate.Registers, compute)) + { + kept = candidate; + break; + } + } + + if (kept is null) + { + return false; + } + + if (kept.Program is { } previous && kept.Registers is { } previousRegisters && kept.DimensionX == dimensionX && + kept.DimensionY == dimensionY && kept.DimensionZ == dimensionZ && + SameUserScalars(previousRegisters.UserScalars, compute.UserScalars, compute.UserScalarCount) && _programs.Revalidate(previous.Input.Stage)) + { + _computeKept.Increment(); + t_resolvePath = ResolvePath.ComputeKept; + _unsharedComputeKept.Increment(); + result = ahead + ? Ahead(previous, kept.Kernel, kept.Source, out refusal) + : WithPrediction(previous, kept.Kernel, kept.Source, kept.SystemRegisters, compute, dimensionX, dimensionY, dimensionZ, indirect); + return true; + } + + if (kept.Entry is not { } entry) + { + return false; + } + + reason = SharedReason.ComputeRebind; + if ((kept.Rebinds + 1) % IdentityRecheckPeriod == 0) + { + _rebindSharedBy[(int)ShaderProgramCache.UnsharedRefusal.Recheck].Increment(); + return false; + } + + var userData = UserData(compute.UserScalars, compute.UserScalarCount, probeWrittenRegisters: false, compute.Address, "compute", ref t_computeUserData); + var source = kept.Source! with { UserData = userData }; + var input = ComputeStageInputResolver.Resolve(compute, source.Registered, dispatchInitiator, !_host.ComputeWave64Supported, dimensionX, dimensionY, dimensionZ); + var options = t_computeOptions ??= StageCompileOptions.CreateReusable(); + options.ComputeInfo = input; + options.ComputeSystemRegisters = kept.SystemRegisters; + options.Tessellation = null; + var pushDataCursor = 0u; + bool completed; + ShaderProgram handle; + ShaderStageResources stage; + ShaderProgramCache.UnsharedRefusal refused; + using (RenderPhaseProfile.MeasureDetail(RenderPhaseProfile.Phase.ProgramPreparation)) + { + completed = _programs.TryCompleteProgramUnshared(entry, source, options, ref pushDataCursor, out handle, out stage, out refused); + } + + options.ComputeInfo = null; + if (!completed) + { + _rebindSharedBy[(int)refused].Increment(); + return false; + } + + // What GetComputeProgramKept's rebinding leaves behind, with the same program. + kept.Rebinds++; + kept.Source = source; + input.Stage = stage; + var rebound = new ComputeProgram { Program = handle, Input = input }; + _computeRebound.Increment(); + t_resolvePath = ResolvePath.ComputeRebound; + _unsharedComputeRebound.Increment(); + KeepComputeProgram(kept, rebound, compute, dimensionX, dimensionY, dimensionZ); + result = ahead + ? Ahead(rebound, kept.Kernel, kept.Source, out refusal) + : WithPrediction(rebound, kept.Kernel, kept.Source, kept.SystemRegisters, compute, dimensionX, dimensionY, dimensionZ, indirect); + return true; + } + + // SHARPEMU_RESOLVE_UNSHARED_COMPUTE=0: with shards, every dispatch takes the shared tier as with one resolver. + internal static bool UnsharedCompute { get; set; } = Environment.GetEnvironmentVariable("SHARPEMU_RESOLVE_UNSHARED_COMPUTE") != "0"; + + // This thread's user data memo and lookup options for unshared rebindings (the cache's own are the shared tier's). + [ThreadStatic] + private static uint[]? t_computeUserData; + [ThreadStatic] + private static StageCompileOptions? t_computeOptions; + // A program resolved ahead stands for the dispatch's own only where the dispatch would take it unchanged: // WithPrediction returns it as it is, and no frontend or consumption had a say. private ComputeProgram? Ahead(ComputeProgram program, KernelDemand? kernel, ShaderSource? source, out ComputePrefetchRefusal refusal) @@ -2362,7 +2578,7 @@ kept is not null && // A frontend image copy's fallback program, compiled when the executor cannot copy: outside any resolution. private ComputeProgram CompileComputeProgram(ShaderSource source, ComputeInputInfo input, Gen5ComputeSystemRegisters systemRegisters) { - lock (_resolveGate) + using (EnterSharedScope(SharedReason.Other)) { using var profileScope = RenderPhaseProfile.MeasureDetail(RenderPhaseProfile.Phase.ProgramPreparation); ShaderProgram handle; @@ -2395,7 +2611,7 @@ public ComputeProgram GetComputeProgram( uint dimensionZ) { using var waitScope = RenderPhaseProfile.MeasureDetail(RenderPhaseProfile.Phase.ComputeResolveLockWait); - lock (_resolveGate) + using (EnterSharedScope(SharedReason.Other)) { using var workScope = RenderPhaseProfile.MeasureDetail(RenderPhaseProfile.Phase.ProgramPreparation); // Predicted on the CPU like the bank form (upstream's register form does the same). @@ -2418,7 +2634,7 @@ public ComputeProgram PrepareComputeProgramAhead( uint dimensionZ) { using var waitScope = RenderPhaseProfile.MeasureDetail(RenderPhaseProfile.Phase.ComputeResolveLockWait); - lock (_resolveGate) + using (EnterSharedScope(SharedReason.Other)) { using var workScope = RenderPhaseProfile.MeasureDetail(RenderPhaseProfile.Phase.ProgramPreparation); return GetComputeProgramCore(compute, dispatchInitiator, dimensionX, dimensionY, dimensionZ, retry: null, out _, out _, out _, ahead: true); @@ -2438,7 +2654,7 @@ public ComputeProgram GetComputeProgram( ComputeProgramRetry retry) { using var waitScope = RenderPhaseProfile.MeasureDetail(RenderPhaseProfile.Phase.ComputeResolveLockWait); - lock (_resolveGate) + using (EnterSharedScope(SharedReason.ComputeRetry)) { using var workScope = RenderPhaseProfile.MeasureDetail(RenderPhaseProfile.Phase.ProgramPreparation); return GetComputeProgramCore(compute, dispatchInitiator, dimensionX, dimensionY, dimensionZ, retry, out _, out _, out _); diff --git a/src/SharpEmu.Libs/Gpu/Pipelines/ShaderProgramCache.cs b/src/SharpEmu.Libs/Gpu/Pipelines/ShaderProgramCache.cs index bcfdf0e2d..a8f3468df 100644 --- a/src/SharpEmu.Libs/Gpu/Pipelines/ShaderProgramCache.cs +++ b/src/SharpEmu.Libs/Gpu/Pipelines/ShaderProgramCache.cs @@ -516,7 +516,21 @@ public ShaderProgramCache(CpuContext context, IGuestGpuBackend compiler, IShader // Where the preparation running now logs what it reads of guest memory, for a dispatch // that may run again without preparing again (ComputeProgramRetry); null logs nothing. - internal GuestReadLog? ReadLog { get; set; } + // Bound to the thread that set it: with resolver shards, other threads read guest words through this cache's readers + // (a memo hit's revalidation, an unshared rebinding) while the worker logs a retry's reads, and those are not the + // retry's. With one thread, the log as it always was. + internal GuestReadLog? ReadLog + { + get => _readLog is { } log && _readLogThread == Environment.CurrentManagedThreadId ? log : null; + set + { + _readLogThread = value is null ? 0 : Environment.CurrentManagedThreadId; + _readLog = value; + } + } + + private GuestReadLog? _readLog; + private int _readLogThread; private bool ReadGuestWord(ulong address, out uint word) { @@ -752,6 +766,140 @@ private sealed class ShaderProgramPendingException() : Exception("The linked pro internal static ProgramSourceEntry? LastEntry => _lastEntry; + // Why a cached entry's program for new user data had to be made under the shared tier (TryCompleteProgramUnshared). + internal enum UnsharedRefusal + { + DeviceData, // a device data load since the plan was made: it is planned again (CompleteProgram) + Linked, // shader calls or run-time call records: linking reads and fills the call caches + Traced, // the lookup logs or traces its reads (TracesLookups) + NotFast, // the plan materializes through the materialization cache, which only the shared tier uses + Failed, // the fast materialization failed: the shared tier reports it + Permutation, // no permutation of this specialization yet: translation + Recheck, // the periodic identity recheck of a rebound program (ShaderPipelineCache.IdentityRecheckPeriod) + Count, + } + + internal static readonly string[] UnsharedRefusalNames = ["device_data", "linked", "traced", "not_fast", "failed", "permutation", "recheck"]; + + // This thread's runtime inputs for unshared lookups, with the cache whose readers they hold. A fast snapshot keeps the + // inputs object and copies the draw values it was evaluated with (ResourceMaterializer.FastOrigin), as for _inputs. + [ThreadStatic] + private static ShaderProgramCache? t_unsharedInputsOwner; + [ThreadStatic] + private static ResourceRuntimeInputs? t_unsharedInputs; + + // CompleteProgram for a cached entry, off the shared tier: only where it reads nothing that tier owns and fills + // nothing in it, that is a fast plan with no shader calls, nothing traced, no replan pending and a permutation of + // the specialization already made. Anything else is refused (refusal), and the caller makes the lookup under the + // shared tier, where CompleteProgram does all of it as before. The same inputs, readers, tally and permutation choice + // as CompleteProgram; the inputs object is this thread's own instead of the shared one. + internal bool TryCompleteProgramUnshared(ProgramSourceEntry entry, ShaderSource source, StageCompileOptions options, ref uint pushDataCursor, + out ShaderProgram program, out ShaderStageResources stage, out UnsharedRefusal refusal) + { + program = default; + stage = default; + refusal = UnsharedRefusal.Count; + if (_dataWritePending is not null && entry.DeviceDataGeneration != DeviceDataLoads.Generation) + { + refusal = UnsharedRefusal.DeviceData; + return false; + } + + if ((entry.HasShaderCalls && _compiler.LinkedShaderCallsSupported) || entry.RuntimeCallRecords) + { + refusal = UnsharedRefusal.Linked; + return false; + } + + if (TracesLookups) + { + refusal = UnsharedRefusal.Traced; + return false; + } + + if (!ResourceMaterializer.CanMaterializeFast(entry.Plan)) + { + refusal = UnsharedRefusal.NotFast; + return false; + } + + if (!ReferenceEquals(t_unsharedInputsOwner, this) || t_unsharedInputs is null) + { + t_unsharedInputsOwner = this; + t_unsharedInputs = new ResourceRuntimeInputs + { + ReadMemory = _readGuestWord, + ReadCleanMemory = _readCleanGuestWord, + TraceImageCandidate = null, + ReadResidentMemory = _prefetchResidentGuestBytes, + CompareResidentMemory = _compareResidentGuestBytes, + CompareGuestWords = _compareGuestWords, + ReadsSuperseded = _readsSuperseded, + DataWritePending = _dataWritePending, + NullsOffClassLoopRecords = NullsOffClassLoopRecords, + }; + } + + var inputs = t_unsharedInputs; + inputs.UserData = source.UserData; + inputs.ShaderBase = source.Address; + inputs.ComputeState = source.Stage == ShaderStage.Compute && options.ComputeInfo is { } computeState + ? new ComputeSelectorState(computeState.WaveSize, Math.Max(computeState.ThreadsX, 1), + Math.Max(computeState.ThreadsY, 1), Math.Max(computeState.ThreadsZ, 1), computeState.DispatchThreadDimensions, + computeState.LocalDataShareDwords, computeState.ThreadIdCount) + : null; + ResourceSnapshot snapshot = null!; + ResourceSpecialization specialization = null!; + MaterializingShader.Hash = source.Hash; + bool materialized; + MaterializationTally.Outcome outcome; + long started; + using (RenderPhaseProfile.MeasureDetail(RenderPhaseProfile.Phase.ResourceMaterialization)) + { + started = MaterializationTally.StartTiming(); + _host.BeginGuestWordReads(); + try + { + materialized = ResourceMaterializer.MaterializeFast(entry.Plan, inputs, ref snapshot, ref specialization, out _); + outcome = ResourceMaterializer.LastFastOutcome; + } + finally + { + _host.EndGuestWordReads(); + MaterializingShader.Hash = 0; + } + } + + if (!materialized) + { + refusal = UnsharedRefusal.Failed; + return false; + } + + snapshot = snapshot.WithUserData(source.UserData); + var permutation = Volatile.Read(ref entry.LastPermutation) is { } last && ReferenceEquals(last.Specialization, specialization) && + last.Bindings.PushDataStartDword == PushDataStart(last.Bindings, pushDataCursor) + ? last + : FindPermutation(entry, specialization, pushDataCursor); + if (permutation is null) + { + refusal = UnsharedRefusal.Permutation; + return false; + } + + MaterializationTally.Note(outcome, MaterializationTally.ElapsedTicks(started), snapshot); + _lastEntry = entry; + if (ReferenceEquals(permutation.Specialization, specialization)) + { + Volatile.Write(ref entry.LastPermutation, permutation); + } + + stage = CreateStageResources(permutation.Program, snapshot, source, options, [], [], null, null); + permutation.Bindings.AdvancePushData(ref pushDataCursor); + program = permutation.Handle; + return true; + } + internal bool TryGetProgramForEntry(ProgramSourceEntry entry, ShaderSource source, StageCompileOptions options, bool strictShaders, ref uint pushDataCursor, out ShaderProgram program, out ShaderStageResources stage, out string rejection) { @@ -896,7 +1044,7 @@ private ShaderProgram CompleteProgram(ProgramSourceEntry entry, bool sourceWasCa // One inputs object refilled per lookup: the materialization reads it during the call // and keeps nothing of it (a miss copies what its entry needs). Lookups run one at a time - // (ShaderPipelineCache._resolveGate). + // (ShaderPipelineCache._resolveGate); an unshared lookup uses its thread's own (TryCompleteProgramUnshared). var inputs = _inputs ??= new ResourceRuntimeInputs { ReadMemory = _readGuestWord, diff --git a/src/SharpEmu.Libs/Gpu/Rendering/ParallelProgramPrefetch.cs b/src/SharpEmu.Libs/Gpu/Rendering/ParallelProgramPrefetch.cs index 364133c66..65476678d 100644 --- a/src/SharpEmu.Libs/Gpu/Rendering/ParallelProgramPrefetch.cs +++ b/src/SharpEmu.Libs/Gpu/Rendering/ParallelProgramPrefetch.cs @@ -1194,6 +1194,64 @@ private GateItemKind NoteUnresolvedTake(Job job, out bool behind) // gates, the bytes it allocated per job (sampled every AllocationSamplePeriod jobs), and its CPU time. private long _idleTicks, _gateTicks, _idleWakes, _idleSpinTakes, _sampledBytes, _sampledJobs; + // The sampled jobs' allocation by how their resolution was answered (ShaderPipelineCache.ResolvePath): + // name=bytes per job/sampled jobs. + private readonly long[] _sampledBytesByPath = new long[(int)SharpEmu.Libs.Gpu.Pipelines.ShaderPipelineCache.ResolvePath.Count]; + private readonly long[] _sampledJobsByPath = new long[(int)SharpEmu.Libs.Gpu.Pipelines.ShaderPipelineCache.ResolvePath.Count]; + + // The sampled jobs' allocation by step of ResolveCore (alloc_by_step=, bytes per sampled job). + private enum AllocationStep { Begin, Inputs, Programs, Assumptions, Bindings, Count } + + private static readonly string[] AllocationStepNames = ["begin", "inputs", "programs", "assumptions", "bindings"]; + private readonly long[] _sampledBytesByStep = new long[(int)AllocationStep.Count]; + + [ThreadStatic] + private static bool t_allocationSampled; + + // The thread's allocated bytes now, adding what was allocated since mark to step (sampled jobs only). + private long MarkAllocation(AllocationStep step, long mark) + { + if (!t_allocationSampled) + { + return 0; + } + + var now = GC.GetAllocatedBytesForCurrentThread(); + if (step != AllocationStep.Begin) + { + Interlocked.Add(ref _sampledBytesByStep[(int)step], now - mark); + } + + return now; + } + + private string TakeAllocationByStep(long sampledJobs) + { + var text = new System.Text.StringBuilder(); + for (var step = 1; step < (int)AllocationStep.Count; step++) + { + var bytes = Interlocked.Exchange(ref _sampledBytesByStep[step], 0); + text.Append(step == 1 ? "" : ",").Append(AllocationStepNames[step]).Append('=') + .Append((sampledJobs == 0 ? 0 : bytes / (double)sampledJobs).ToString("F0", System.Globalization.CultureInfo.InvariantCulture)); + } + + return text.ToString(); + } + + private string TakeAllocationByPath() + { + var text = new System.Text.StringBuilder(); + for (var path = 0; path < _sampledBytesByPath.Length; path++) + { + var bytes = Interlocked.Exchange(ref _sampledBytesByPath[path], 0); + var jobs = Interlocked.Exchange(ref _sampledJobsByPath[path], 0); + text.Append(path == 0 ? "" : ",").Append(SharpEmu.Libs.Gpu.Pipelines.ShaderPipelineCache.ResolvePathNames[path]).Append('=') + .Append(jobs == 0 ? "0" : (bytes / (double)jobs).ToString("F0", System.Globalization.CultureInfo.InvariantCulture)).Append('/').Append(jobs); + } + + return text.ToString(); + } + // SHARPEMU_RESOLVER_IDLE_SPIN=0: the idle worker sleeps at once, as before. private static readonly bool IdleSpin = SharpEmu.ShaderCompiler.PerfSwitches.Enabled("SHARPEMU_RESOLVER_IDLE_SPIN"); private const int IdleSpins = 32; @@ -1233,6 +1291,7 @@ public string TakeResolverReport() $"gate_sleep_ms={Milliseconds(Interlocked.Exchange(ref _gateTicks, 0)).ToString("F1", culture)} idle_wakes={Interlocked.Exchange(ref _idleWakes, 0)} " + $"idle_spin_takes={Interlocked.Exchange(ref _idleSpinTakes, 0)} " + $"alloc_b_per_job={(sampledJobs == 0 ? 0 : sampledBytes / (double)sampledJobs).ToString("F0", culture)} " + + $"alloc_by_path=({TakeAllocationByPath()}) alloc_by_step=({TakeAllocationByStep(sampledJobs)}) " + $"resolver_cpu_ms={cpuMs.ToString("F1", culture)} {TakeShardReport(shardCpu)} " + SharpEmu.Libs.Gpu.Pipelines.ShaderPipelineCache.TakeGraphicsResolveReport(); } @@ -1531,6 +1590,8 @@ private void Run(ResolverShard shard) var sampled = (Interlocked.Increment(ref shard.ResolverJobs) & (AllocationSamplePeriod - 1)) == 0; var allocatedBefore = sampled ? GC.GetAllocatedBytesForCurrentThread() : 0; + if (sampled) SharpEmu.Libs.Gpu.Pipelines.ShaderPipelineCache.t_resolvePath = default; + t_allocationSampled = sampled; try { Resolve(job, shard); @@ -1539,8 +1600,12 @@ private void Run(ResolverShard shard) { if (sampled) { - Interlocked.Add(ref _sampledBytes, GC.GetAllocatedBytesForCurrentThread() - allocatedBefore); + var bytes = GC.GetAllocatedBytesForCurrentThread() - allocatedBefore; + Interlocked.Add(ref _sampledBytes, bytes); Interlocked.Increment(ref _sampledJobs); + var path = (int)SharpEmu.Libs.Gpu.Pipelines.ShaderPipelineCache.t_resolvePath; + Interlocked.Add(ref _sampledBytesByPath[path], bytes); + Interlocked.Increment(ref _sampledJobsByPath[path]); } FinishJob(shard, worker: true); @@ -1593,20 +1658,25 @@ private void ResolveCore(Job job) var started = System.Diagnostics.Stopwatch.GetTimestamp(); // Before the lookup, as for a draw: a take under another stamp is refused (ComputeRefusal.Replanned). job.ProgramState = _executor.ProgramState; + var mark = MarkAllocation(AllocationStep.Begin, 0); job.ComputeResult = _executor.ResolveComputeProgramAhead(job.Banks, compute.DispatchInitiator, compute.GroupsX, compute.GroupsY, compute.GroupsZ, compute.Indirect, out job.ComputeRefusal); + mark = MarkAllocation(AllocationStep.Programs, mark); if (RecordsForVerify) { job.ResolveState = _executor.DescribeProgramState(); } job.Assumptions = _concurrent.EndConcurrentResolve(); + mark = MarkAllocation(AllocationStep.Assumptions, mark); // The dispatch's binding decode joins its resolution (IConcurrentResolveHost.PrepareBindingsAhead). if (job.ComputeResult is { Available: true, Consumed: false, ImageCopy: null } resolved) { _concurrent.PrepareBindingsAhead(resolved.Input.Stage, dispatch: true); } + MarkAllocation(AllocationStep.Bindings, mark); + job.ResolveTicks = System.Diagnostics.Stopwatch.GetTimestamp() - started; Interlocked.Increment(ref _resolvedCount); Interlocked.Increment(ref _shards[job.Shard].Resolved); @@ -1614,10 +1684,13 @@ private void ResolveCore(Job job) return; } + var drawMark = MarkAllocation(AllocationStep.Begin, 0); job.Inputs = RenderExecutor.ProgramInputsOf(job.Banks, _host.FormatSupport, WorkerScratch.Enabled ? _fatal : _host.Fatal, job.Indexed, job.StartInstanceUserData); + drawMark = MarkAllocation(AllocationStep.Inputs, drawMark); job.ProgramState = _executor.ProgramState; job.Programs = _executor.ResolveGraphicsPrograms(job.Banks, in job.Inputs); + drawMark = MarkAllocation(AllocationStep.Programs, drawMark); if (RecordsForVerify) { job.ResolveState = _executor.DescribeProgramState(); @@ -1627,11 +1700,14 @@ private void ResolveCore(Job job) } job.Assumptions = _concurrent.EndConcurrentResolve(); + drawMark = MarkAllocation(AllocationStep.Assumptions, drawMark); if (job.Programs is { Available: true } programs) { PrepareGraphicsBindingsAhead(programs, job.Inputs.PixelActive); } + MarkAllocation(AllocationStep.Bindings, drawMark); + Interlocked.Increment(ref _resolvedCount); Interlocked.Increment(ref _shards[job.Shard].Resolved); job.State = 1; diff --git a/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/ComputeProgramReuseTests.Shards.cs b/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/ComputeProgramReuseTests.Shards.cs new file mode 100644 index 000000000..84d280d5e --- /dev/null +++ b/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/ComputeProgramReuseTests.Shards.cs @@ -0,0 +1,90 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using System.Text.RegularExpressions; +using SharpEmu.Libs.Gpu.GpuCommands.Registers; +using SharpEmu.Libs.Gpu.Pipelines; +using SharpEmu.Libs.Gpu.Rendering; +using SharpEmu.Libs.Tests.Gpu.Scheduling; +using Xunit; + +namespace SharpEmu.Libs.Tests.Gpu.Pipelines; + +// Dispatches with resolver shards: a kept program holds or rebinds off the shared tier where it can, and every take of +// that tier is counted by reason (ShaderPipelineCache.TakeShardReport). +public sealed partial class ComputeProgramReuseTests +{ + [Fact] + public void WithShardsADispatchHandsOutWhatOneResolverDoesAndCountsEverySharedTakeByReason() + { + using var fatal = new FatalScope(); + var (single, _) = CreateCache(); + single.ResolveShardCount = 1; + var (sharded, _) = CreateCache(); + sharded.ResolveShardCount = 2; + ShaderPipelineCache.TakeShardReport(); + + var userData = new uint[] { 0, 0x1234, 0x1234, 0x5678 }; + var expected = new List(); + var banks = Banks(); + foreach (var word in userData) + { + banks.Shader.Compute.UserScalars.Set(0, word, UserScalarKind.Unknown); + expected.Add(single.GetComputeProgram(banks, 0x8001, 1, 1, 1)); + } + + Assert.Contains("shared_takes=0 ", ShaderPipelineCache.TakeShardReport()); + banks = Banks(); + for (var index = 0; index < userData.Length; index++) + { + banks.Shader.Compute.UserScalars.Set(0, userData[index], UserScalarKind.Unknown); + var program = sharded.ResolveComputeProgramAhead(banks, 0x8001, 1, 1, 1, indirect: false, out var refusal); + Assert.Equal(ComputePrefetchRefusal.None, refusal); + Assert.NotNull(program); + Assert.Equal(expected[index].Available, program!.Available); + Assert.Equal(expected[index].Input.Stage.Resources.UserData.ToArray(), program.Input.Stage.Resources.UserData.ToArray()); + Assert.Equal(expected[index].Input.ThreadsX, program.Input.ThreadsX); + } + + // The first resolves in full on the shared tier; the repeat is kept off it; each change of user data is a rebinding, + // off the tier or counted there with its reason. Nothing else takes the shared tier. + var report = ShaderPipelineCache.TakeShardReport(); + long Field(string pattern) => long.Parse(Regex.Match(report, pattern).Groups[1].Value); + Assert.Equal(1, Field(@"compute_resolve=(\d+)")); + Assert.Equal(1, Field(@"unshared_compute=\(kept=(\d+)")); + var rebound = Field(@"rebound=(\d+)\)"); + var rebindShared = Field(@"shared_by=\([^)]*compute_rebind=(\d+)"); + Assert.Equal(2, rebound + rebindShared); + var refusals = Regex.Match(report, @"rebind_shared_by=\(([^)]*)\)").Groups[1].Value.Split(',').Sum(field => long.Parse(field.Split('=')[1])); + Assert.Equal(rebindShared, refusals); + Assert.Equal(1 + rebindShared, Field(@"shared_takes=(\d+)")); + } + + [Fact] + public void AReadLogIsTheSettingThreadsOnly() + { + var (cache, _) = CreateCache(); + var log = new GuestReadLog(); + cache.Programs.ReadLog = log; + try + { + Assert.Same(log, cache.Programs.ReadLog); + Assert.True(cache.Programs.TracesLookups); + GuestReadLog? seen = log; + var traces = true; + var other = new Thread(() => + { + seen = cache.Programs.ReadLog; + traces = cache.Programs.TracesLookups; + }); + other.Start(); + other.Join(); + Assert.Null(seen); + Assert.False(traces); + } + finally + { + cache.Programs.ReadLog = null; + } + } +} diff --git a/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/ComputeProgramReuseTests.cs b/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/ComputeProgramReuseTests.cs index 1f067c52c..7a76e0e0c 100644 --- a/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/ComputeProgramReuseTests.cs +++ b/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/ComputeProgramReuseTests.cs @@ -9,7 +9,7 @@ namespace SharpEmu.Libs.Tests.Gpu.Pipelines; [Collection(SchedulingStateCollection.Name)] -public sealed class ComputeProgramReuseTests +public sealed partial class ComputeProgramReuseTests { private const ulong CodeAddress = PipelineTestGuest.MemoryBase + 0x1000; private const ulong HeaderAddress = PipelineTestGuest.MemoryBase + 0x8000; From f202b2e9ed614f141fc14e1bd7d8947e326f2afb Mon Sep 17 00:00:00 2001 From: kuba Date: Tue, 17 Nov 2026 05:28:33 +0000 Subject: [PATCH 169/178] [Tests] Bench the shard resolver with the game's dispatch share and a pipelined worker SHARPEMU_DS_DRAW_BENCH_DISPATCH_REBIND=1 runs each compute program over the four tables in turn, so dispatches rebind as in Demon's Souls; SHARPEMU_DS_SHARD_BENCH_DRAIN=pipeline takes each job on a worker thread inside the timed part with the submitter at most _WINDOW (64) jobs ahead, so the resolvers draw assumptions from the host's pool as in game. The arm line reports the shared-lock split, allocation by path and step, and the resolvers' idle time. --- .../Scenes/DsDrawCostBenchTests.Engine.cs | 99 ++++++++++++++----- .../Scenes/DsDrawCostBenchTests.cs | 7 +- 2 files changed, 82 insertions(+), 24 deletions(-) diff --git a/tests/SharpEmu.Gpu.Metal.Tests/Scenes/DsDrawCostBenchTests.Engine.cs b/tests/SharpEmu.Gpu.Metal.Tests/Scenes/DsDrawCostBenchTests.Engine.cs index 1212d46c2..51a34a6a9 100644 --- a/tests/SharpEmu.Gpu.Metal.Tests/Scenes/DsDrawCostBenchTests.Engine.cs +++ b/tests/SharpEmu.Gpu.Metal.Tests/Scenes/DsDrawCostBenchTests.Engine.cs @@ -87,6 +87,11 @@ int Setting(string name, int fallback) => // =spin: the bench thread spins on each job's state instead of sleeping in WaitIdle (whose waiter makes every finish // pulse the prefetch lock); the game's command thread never waits for the whole frame. var spinDrain = Environment.GetEnvironmentVariable("SHARPEMU_DS_SHARD_BENCH_DRAIN") == "spin"; + // =pipeline: as in the game, a taker thread (the worker) takes each job in order once it is resolved, inside the + // timed part, and the submitter (the command thread) stays at most _WINDOW (64) jobs ahead of it; the takes hand + // the assumptions back, so the resolvers draw from the host's pool as in game instead of allocating a frame's worth. + var pipeline = Environment.GetEnvironmentVariable("SHARPEMU_DS_SHARD_BENCH_DRAIN") == "pipeline"; + var window = int.TryParse(Environment.GetEnvironmentVariable("SHARPEMU_DS_SHARD_BENCH_WINDOW"), out var parsedWindow) && parsedWindow > 0 ? parsedWindow : 64; var armResults = new List<(int Count, double JobsPerSecond, double WallMedianMs, string Report, ulong Fingerprint, string Creations, long Taken, long Refused)>(); foreach (var count in arms) @@ -102,6 +107,33 @@ int Setting(string name, int fallback) => var submitted = new ParallelProgramPrefetch.Job[jobs.Length]; var total = warmFrames + frames; var wall = new double[total]; + var took = new bool[jobs.Length]; + var takenStages = new (ShaderStageResources First, ShaderStageResources? Second)[jobs.Length]; + + // The worker's take of job at; the stages it handed out are fingerprinted afterwards, untimed. + bool Take(int at, int frameIndex) + { + var job = jobs[at]; + prefetch.Current = submitted[at]; + bool result; + if (job.Compute is { } arguments) + { + result = prefetch.TryTakeCompute(job.Banks, arguments.Initiator, arguments.GroupsX, arguments.GroupsY, arguments.GroupsZ, + arguments.Indirect, out var program); + takenStages[at] = result ? (program.Input.Stage, null) : default; + } + else + { + var inputs = RenderExecutor.ProgramInputsOf(job.Banks, renderHost.FormatSupport, renderHost.Fatal, job.Inputs.Indexed, + job.Inputs.StartInstanceUserData); + result = prefetch.TryTakeGraphics(job.Banks, in inputs, out var programs); + takenStages[at] = result ? (programs.VertexInput.Stage, inputs.PixelActive ? programs.PixelInput.Stage : null) : default; + } + + prefetch.Current = null; + return result; + } + var fingerprint = 0xCBF29CE484222325UL; // Every arm replays the same frames (the churn and the pixel-constant copies follow the frame number), so the // fingerprints of all arms must match. @@ -122,15 +154,42 @@ int Setting(string name, int fallback) => var contended = Monitor.LockContentionCount; var collected = GC.CollectionCount(0); var pausedBefore = GC.GetTotalPauseDuration(); + var frameIndex = index; + var submittedCount = 0; + var takenCount = 0; + Thread? taker = null; + if (pipeline) + { + taker = new Thread(() => + { + for (var at = 0; at < jobs.Length; at++) + { + while (Volatile.Read(ref submittedCount) <= at) Thread.SpinWait(8); + while (JobState(submitted[at]) == 0) Thread.SpinWait(8); + took[at] = Take(at, frameIndex); + Volatile.Write(ref takenCount, at + 1); + } + }); + taker.Start(); + } + var started = Stopwatch.GetTimestamp(); for (var at = 0; at < jobs.Length; at++) { + if (pipeline) + { + while (at - Volatile.Read(ref takenCount) >= window) Thread.SpinWait(8); + } + var job = jobs[at]; submitted[at] = job.Compute is { } arguments ? prefetch.SubmitCompute(job.Banks, 0, arguments.Initiator, arguments.GroupsX, arguments.GroupsY, arguments.GroupsZ, arguments.Indirect) : prefetch.Submit(job.Banks, 0, job.Inputs.Indexed, job.Inputs.StartInstanceUserData); + Volatile.Write(ref submittedCount, at + 1); } + taker?.Join(); + if (spinDrain) { foreach (var job in submitted) @@ -150,34 +209,25 @@ int Setting(string name, int fallback) => paused += GC.GetTotalPauseDuration() - pausedBefore; } - // The worker's takes, untimed: they hand the assumptions back, and the measured frames' programs are fingerprinted. + // Without pipeline, the worker's takes, untimed: they hand the assumptions back. The measured frames' programs + // are fingerprinted untimed either way, in stream order. for (var at = 0; at < jobs.Length; at++) { - var job = jobs[at]; - prefetch.Current = submitted[at]; - bool took; - if (job.Compute is { } arguments) - { - took = prefetch.TryTakeCompute(job.Banks, arguments.Initiator, arguments.GroupsX, arguments.GroupsY, arguments.GroupsZ, - arguments.Indirect, out var program); - if (took && index >= warmFrames) fingerprint = FingerprintStage(fingerprint, program.Input.Stage); - } - else + if (!pipeline) took[at] = Take(at, index); + if (index >= warmFrames) { - var inputs = RenderExecutor.ProgramInputsOf(job.Banks, renderHost.FormatSupport, renderHost.Fatal, job.Inputs.Indexed, - job.Inputs.StartInstanceUserData); - took = prefetch.TryTakeGraphics(job.Banks, in inputs, out var programs); - if (took && index >= warmFrames) - { - fingerprint = FingerprintStage(fingerprint, programs.VertexInput.Stage); - if (inputs.PixelActive) fingerprint = FingerprintStage(fingerprint, programs.PixelInput.Stage); - } + if (took[at]) taken++; + else refused++; } + } - if (index >= warmFrames) + if (index >= warmFrames) + { + for (var at = 0; at < jobs.Length; at++) { - if (took) taken++; - else refused++; + if (!took[at]) continue; + fingerprint = FingerprintStage(fingerprint, takenStages[at].First); + if (takenStages[at].Second is { } second) fingerprint = FingerprintStage(fingerprint, second); } } @@ -197,7 +247,10 @@ int Setting(string name, int fallback) => var sorted = measured.Order().ToArray(); var jobsPerSecond = frames * jobs.Length / (measured.Sum() / 1000.0); armResults.Add((count, jobsPerSecond, sorted[sorted.Length / 2], report, fingerprint, creations, taken, refused)); - var shards = System.Text.RegularExpressions.Regex.Match(report, @"shards=\([^)]*\)").Value; + var shards = System.Text.RegularExpressions.Regex.Match(report, @"shards=\(.*?rebind_shared_by=\([^)]*\)\)").Value; + // The resolvers' allocation per job, sampled, and by how each job was answered. + shards += " " + System.Text.RegularExpressions.Regex.Match(report, @"alloc_b_per_job=\d+ alloc_by_path=\([^)]*\) alloc_by_step=\([^)]*\)").Value; + shards += " " + System.Text.RegularExpressions.Regex.Match(report, @"resolver_idle_ms=\S+ gate_sleep_ms=\S+ idle_wakes=\d+ idle_spin_takes=\d+").Value; Output.WriteLine($"engine N={count}: {jobsPerSecond / 1000.0:F0}k jobs/s, wall median {sorted[sorted.Length / 2]:F2} ms/frame (min {sorted[0]:F2}), " + $"taken {taken} refused {refused}, fingerprint {fingerprint:X16}, {creations}, " + $"monitor contentions {contentions / (double)(frames * jobs.Length):F3}/job, gc {collections} collections {paused.TotalMilliseconds:F1} ms paused, " + diff --git a/tests/SharpEmu.Gpu.Metal.Tests/Scenes/DsDrawCostBenchTests.cs b/tests/SharpEmu.Gpu.Metal.Tests/Scenes/DsDrawCostBenchTests.cs index b5d35247a..5194e98aa 100644 --- a/tests/SharpEmu.Gpu.Metal.Tests/Scenes/DsDrawCostBenchTests.cs +++ b/tests/SharpEmu.Gpu.Metal.Tests/Scenes/DsDrawCostBenchTests.cs @@ -548,6 +548,10 @@ ulong DispatchTable(int dispatch, ulong writeBuffer) // at _GAME_DRAWS and _CHURN_EVERY=1, every draw has a mesh of its own whose table changes every round. var meshRepeat = Setting("MESH_REPEAT", 2); var dispatchEvery = int.TryParse(Environment.GetEnvironmentVariable("SHARPEMU_DS_DRAW_BENCH_DISPATCH_EVERY"), out var every) && every > 0 ? every : 0; + // SHARPEMU_DS_DRAW_BENCH_DISPATCH_REBIND=1: those dispatches run each program over the four tables in turn, so a + // dispatch's user data differs from the last of its program and its kept program is rebound (Demon's Souls: ~95% + // of dispatches rebound, ~2% kept, ~2.5% resolved); without it each program keeps one table and is kept. + var dispatchRebind = Environment.GetEnvironmentVariable("SHARPEMU_DS_DRAW_BENCH_DISPATCH_REBIND") == "1"; // SHARPEMU_DS_DRAW_BENCH_BURST=1: a round's game streams are all submitted before the worker records any, as // Demon's Souls submits ~13 command buffers at once, so the collector call after each submission lies between // draws (and is looked ahead of with SHARPEMU_PREFETCH_DRAW_LOOKAHEAD); one commit and one copy arming a round, @@ -653,10 +657,11 @@ void ArmCopiedTables() if (dispatchEvery != 0 && draw % dispatchEvery == dispatchEvery - 1) { var dispatch = draw / dispatchEvery % dispatchTables.Length; + var program = dispatchRebind ? draw / dispatchEvery / dispatchTables.Length % computePrograms.Length : dispatch % computePrograms.Length; var compute = new SceneState(1, 1); compute.Context.Clear(); compute.Uconfig.Clear(); - compute.ComputeShader(computePrograms[dispatch % computePrograms.Length], 8, 8, 1, + compute.ComputeShader(computePrograms[program], 8, 8, 1, [Descriptors.Lo(dispatchTables[dispatch]), Descriptors.Hi(dispatchTables[dispatch])], true, true, false, 1, 0); compute.Emit(pm4!); pm4!.DispatchDirect(StorageEdge / 8, StorageEdge / 8, 1); From a2b6912103076f97192bb3adf29bfd81867339d6 Mon Sep 17 00:00:00 2001 From: kuba Date: Tue, 17 Nov 2026 06:21:40 +0000 Subject: [PATCH 170/178] [GPU] Refuse a dispatch job across a logged kernel fill or copy only when the write covers its reads A dispatch the recorder consumes as a kernel fill or copy (TryClearImageFromKernelFill, TryCopyWordsOnHost) on Metal either does a storage store's bookkeeping and logs the write over its destination (NoteGuestMemoryWrite), or writes nothing (identical elision). The dispatch take already refuses a job whose reads a write logged since its resolution began covers (IsStillCurrentAcrossDispatches), so those two kinds no longer refuse every job resolved ahead of them. Every other effect kind, and every effect for a draw's take, keeps the blunt refusal. Counters: dispatch_effects=(kind=n,...) and exact_effects=(mode,refused,taken) in the prefetch line. SHARPEMU_PREFETCH_EXACT_EFFECTS=0 restores the blunt rule. Not game-verified. --- docs/macos/configuration.md | 1 + .../Gpu/Rendering/ParallelProgramPrefetch.cs | 70 +++++++++++++++-- .../Gpu/Rendering/RenderExecutor.Compute.cs | 4 +- .../Gpu/Rendering/RenderExecutor.Prefetch.cs | 37 +++++++++ .../Gpu/Rendering/RenderRecorder.Compute.cs | 23 ++++-- .../V2/MetalRenderHost.ConcurrentResolve.cs | 7 ++ ...MetalClearFoldingTests.DispatchPrefetch.cs | 33 ++++++++ .../ParallelProgramPrefetchComputeTests.cs | 77 +++++++++++++++++++ ...rallelProgramPrefetchDrawLookaheadTests.cs | 17 ++++ 9 files changed, 256 insertions(+), 13 deletions(-) diff --git a/docs/macos/configuration.md b/docs/macos/configuration.md index b7910a9c5..ec68b8f54 100644 --- a/docs/macos/configuration.md +++ b/docs/macos/configuration.md @@ -70,6 +70,7 @@ them for measurements or to isolate a problem. | `SHARPEMU_METAL_V2_ASYNC_PIPELINES` | on | `0` builds pipeline states on the GPU worker thread. | | `SHARPEMU_METAL_V2_ASYNC_LIBRARIES` | on | `0` compiles each shader library on the thread that needs it, not on the compile pool. | | `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 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 resolved ahead of them; a draw's take still refuses on all of them. The prefetch counters report `dispatch_effects=(...)` by kind and `exact_effects=(mode,refused,taken)`, the jobs the old rule would have refused that the check refused or took. `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=`). | | `SHARPEMU_METAL_V2_PIPELINE_LIMIT` | `8192` | Pipeline states kept before idle ones are released. `0` is unlimited. | | `SHARPEMU_METAL_V2_MODULE_LIMIT` | `2048` | The same for shader modules. | diff --git a/src/SharpEmu.Libs/Gpu/Rendering/ParallelProgramPrefetch.cs b/src/SharpEmu.Libs/Gpu/Rendering/ParallelProgramPrefetch.cs index 65476678d..d10621df4 100644 --- a/src/SharpEmu.Libs/Gpu/Rendering/ParallelProgramPrefetch.cs +++ b/src/SharpEmu.Libs/Gpu/Rendering/ParallelProgramPrefetch.cs @@ -411,8 +411,9 @@ public enum ComputeRefusal Inputs, // The ownership answers it read under changed (IConcurrentResolveHost.IsStillCurrentAcrossDispatches). Ownership, - // A dispatch it was resolved ahead of did more than encode GPU work (NoteDispatchEffect), or a collector call it - // was resolved ahead of noted an effect (NoteCollect). + // A dispatch it was resolved ahead of did more than encode GPU work (NoteDispatchEffect; a kernel fill or copy + // the host logs is left to Ownership, ExactEffects), or a collector call it was resolved ahead of noted an + // effect (NoteCollect). Effects, // The program cache stamp moved since the resolution began (Job.ProgramState), as DrawLookaheadRefusal.Replanned. Replanned, @@ -462,7 +463,38 @@ public long[] TakeProviderRefusals() // refused, since what that dispatch did may not show in the ownership answers. -1 while none did. private long _lastDispatchEffect = -1; - public void NoteDispatchEffect() => Volatile.Write(ref _lastDispatchEffect, Volatile.Read(ref _executedGate)); + public void NoteDispatchEffect() => NoteDispatchEffect(DispatchEffectKind.Unknown); + + // Kernel fills and copies (DispatchEffectKind.KernelFill, KernelCopy) on a host that logs them as GPU writes + // (IConcurrentResolveHost.KernelFillWritesLogged) are noted apart (_lastExactDispatchEffect): a dispatch job resolved + // ahead of one is not refused for it, since the take's IsStillCurrentAcrossDispatches already refuses a job whose + // reads a write logged since its resolution began covers, the fill's or copy's as any dispatch's store. Every + // other kind keeps the blunt refusal. A draw's take still refuses on either (TryTakeGraphics). + public void NoteDispatchEffect(DispatchEffectKind kind) + { + Interlocked.Increment(ref _dispatchEffects[(int)kind]); + Volatile.Write(ref IsExactEffect(kind) ? ref _lastExactDispatchEffect : ref _lastDispatchEffect, Volatile.Read(ref _executedGate)); + } + + private bool IsExactEffect(DispatchEffectKind kind) => + ExactEffects && kind is DispatchEffectKind.KernelFill or DispatchEffectKind.KernelCopy && _concurrent.KernelFillWritesLogged; + + private static readonly bool ExactEffectsDefault = + Environment.GetEnvironmentVariable("SHARPEMU_PREFETCH_EXACT_EFFECTS") != "0"; + + // SHARPEMU_PREFETCH_EXACT_EFFECTS=0 refuses dispatch jobs for every effect kind again. Tests set it on one instance. + internal bool ExactEffects { get; set; } = ExactEffectsDefault; + + // The last kernel fill or copy noted exactly (NoteDispatchEffect), as _lastDispatchEffect; -1 while none was. + private long _lastExactDispatchEffect = -1; + + // Effects noted by kind, and the dispatch jobs an exact effect stood in the window of (the blunt rule would have + // refused them) that the take refused anyway (ownership or write log) or took. + private readonly long[] _dispatchEffects = new long[(int)DispatchEffectKind.Count]; + private long _exactEffectRefused, _exactEffectTaken; + + private static readonly string[] DispatchEffectNames = + ["unknown", "consumed", "image_copy", "known_write", "metadata_clear", "constant_fill", "dcc_fill", "kernel_fill", "kernel_copy", "image_clear"]; // =verify: the compute program hash of each dispatch by the gate number it brings the count to (the worker runs item // _executedGate + 1), so a fatal names the dispatches a draw looked over. Written and read on the worker only. @@ -759,7 +791,9 @@ public bool TryTakeGraphics(RegisterBanks banks, in GraphicsProgramInputs inputs : !lookedAhead ? (_concurrent.IsStillCurrent(job.Assumptions!) ? DrawLookaheadRefusal.Count : DrawLookaheadRefusal.Ownership) // A collector call or a dispatch that ran after the resolution began (gate above ExecutedAtStart) noted an effect. : Volatile.Read(ref _lastCollectEffect) >= job.ExecutedAtStart ? DrawLookaheadRefusal.CollectEffects - : Volatile.Read(ref _lastDispatchEffect) >= job.ExecutedAtStart ? DrawLookaheadRefusal.Effects + // Exact effects too: the draw's take keeps the blunt rule (NoteDispatchEffect). + : Math.Max(Volatile.Read(ref _lastDispatchEffect), Volatile.Read(ref _lastExactDispatchEffect)) >= job.ExecutedAtStart + ? DrawLookaheadRefusal.Effects : !_concurrent.IsStillCurrentAcrossDispatches(job.Assumptions!) ? DrawLookaheadRefusal.Ownership : DrawLookaheadRefusal.Count; // =verify keeps a taken look-ahead's assumptions to its comparison (VerifyLookahead): a difference whose answers @@ -1029,6 +1063,13 @@ public bool TryTakeCompute(RegisterBanks banks, uint dispatchInitiator, uint gro : HasComputeEffects(job) ? ComputeRefusal.Effects : !_concurrent.IsStillCurrentAcrossDispatches(job.Assumptions!) ? ComputeRefusal.Ownership : ComputeRefusal.Count; + // A kernel fill or copy the blunt rule would have refused it for: the ownership check above decided instead. + if (refusal is ComputeRefusal.Count or ComputeRefusal.Ownership && + Volatile.Read(ref _lastExactDispatchEffect) >= (ComputeEffectsFromStart ? job.ExecutedAtStart : job.Gate)) + { + Interlocked.Increment(ref refusal == ComputeRefusal.Count ? ref _exactEffectTaken : ref _exactEffectRefused); + } + if (refusal == ComputeRefusal.Count && job.ExecutedAtStart < Volatile.Read(ref _executedGate)) { Interlocked.Increment(ref _computeTakenOver); @@ -1104,7 +1145,8 @@ public bool TryTakeCompute(RegisterBanks banks, uint dispatchInitiator, uint gro $"(job {job.Index}, gate {job.Gate}, executed at start {job.ExecutedAtStart}, executed now {executed}). " + (resolved is null ? string.Empty : $"{SharpEmu.Libs.Gpu.Pipelines.GraphicsProgramsComparer.DescribeCompute(job.ComputeResult!, resolved)} ") + $"looked_over=[{DescribeLookedOver(job.ExecutedAtStart, executed)}] " + - $"last_dispatch_effect={Volatile.Read(ref _lastDispatchEffect)} last_collect_effect={Volatile.Read(ref _lastCollectEffect)} " + + $"last_dispatch_effect={Volatile.Read(ref _lastDispatchEffect)} last_exact_effect={Volatile.Read(ref _lastExactDispatchEffect)} " + + $"last_collect_effect={Volatile.Read(ref _lastCollectEffect)} " + $"stamp_ahead={job.ProgramState} stamp_now={_executor.ProgramState} " + $"state_ahead=[{job.ResolveState}] state_now=[{_executor.DescribeProgramState()}]."); } @@ -1154,9 +1196,27 @@ public string TakeComputeReport() var verify = TakeComputeVerifyCounters(); return $"effects_window=(mode={(ComputeEffectsFromStart ? "started" : "gate")},gate={Interlocked.Exchange(ref _computeEffectsByGate, 0)}," + $"started={Interlocked.Exchange(ref _computeEffectsByStart, 0)},taken_over={Interlocked.Exchange(ref _computeTakenOver, 0)}) " + + $"{TakeDispatchEffectReport()} " + $"dispatch_verify=(verified={verify.Verified},raced={verify.Raced},failed={verify.Failed})"; } + // dispatch_effects=(kind=noted,...) and exact_effects=(mode, refused, taken): the effects noted by kind, and the + // dispatch jobs a kernel fill or copy stood in the effects window of that the ownership check refused or took + // (the blunt rule would have refused both). Resets them. + private string TakeDispatchEffectReport() + { + var builder = new System.Text.StringBuilder("dispatch_effects=("); + for (var index = 0; index < _dispatchEffects.Length; index++) + { + builder.Append(index == 0 ? string.Empty : ",").Append(DispatchEffectNames[index]).Append('=') + .Append(Interlocked.Exchange(ref _dispatchEffects[index], 0)); + } + + return builder.Append(") exact_effects=(mode=").Append(ExactEffects && _concurrent.KernelFillWritesLogged ? "on" : "off") + .Append(",refused=").Append(Interlocked.Exchange(ref _exactEffectRefused, 0)) + .Append(",taken=").Append(Interlocked.Exchange(ref _exactEffectTaken, 0)).Append(')').ToString(); + } + // Why a draw's job was not resolved when its draw took it: still gated on the work before it, the resolving // thread busy with another job, or queued behind others with its gate open (takes_unresolved). private long _unresolvedGated, _unresolvedBusy, _unresolvedQueued; diff --git a/src/SharpEmu.Libs/Gpu/Rendering/RenderExecutor.Compute.cs b/src/SharpEmu.Libs/Gpu/Rendering/RenderExecutor.Compute.cs index beab162bf..86a80dcd9 100644 --- a/src/SharpEmu.Libs/Gpu/Rendering/RenderExecutor.Compute.cs +++ b/src/SharpEmu.Libs/Gpu/Rendering/RenderExecutor.Compute.cs @@ -147,7 +147,9 @@ public void Dispatch(ulong submitId, RegisterBanks banks, uint groupsX, uint gro if (computeProgram.Consumed || computeProgram.ImageCopy is not null || computeProgram.KnownWrite is not null) { // What this dispatch does may not show in the ownership answers of a dispatch resolved ahead of it. - Prefetch?.NoteDispatchEffect(); + Prefetch?.NoteDispatchEffect(computeProgram.Consumed ? DispatchEffectKind.Consumed + : computeProgram.ImageCopy is not null ? DispatchEffectKind.ImageCopy + : DispatchEffectKind.KnownWrite); } var retried = retry?.Reused == true; diff --git a/src/SharpEmu.Libs/Gpu/Rendering/RenderExecutor.Prefetch.cs b/src/SharpEmu.Libs/Gpu/Rendering/RenderExecutor.Prefetch.cs index bdae4b0c9..d121a2303 100644 --- a/src/SharpEmu.Libs/Gpu/Rendering/RenderExecutor.Prefetch.cs +++ b/src/SharpEmu.Libs/Gpu/Rendering/RenderExecutor.Prefetch.cs @@ -100,6 +100,13 @@ public interface IConcurrentResolveHost // its take checked with IsStillCurrentAcrossDispatches; only a host whose check covers what those dispatches write. bool PrefetchedDrawsCrossDispatches => false; + // A dispatch the recorder consumed as a kernel fill or copy (DispatchEffectKind.KernelFill, KernelCopy: the host's + // TryClearImageFromKernelFill, TryCopyWordsOnHost) changed what a resolution reads only as a recorded GPU write + // over its destination does, and logged that write where IsStillCurrentAcrossDispatches finds it, or wrote + // nothing. A dispatch job resolved ahead of such a dispatch is then checked as across any other dispatch, instead + // of refused for the effect (ParallelProgramPrefetch.ExactEffects). False keeps the blunt refusal. + bool KernelFillWritesLogged => false; + // On the render thread, for a dispatch's resolution that may have read guest memory before the dispatches ahead of // it ran: the answers hold, and none of the GPU writes those dispatches recorded covers what it read. bool IsStillCurrentAcrossDispatches(object assumptions) => IsStillCurrent(assumptions); @@ -118,6 +125,32 @@ void PrepareBindingsAhead(in ShaderStageResources stage, bool dispatch) } } +// What a dispatch did beyond encoding GPU work (IProgramPrefetch.NoteDispatchEffect). +public enum DispatchEffectKind : byte +{ + // A caller that names no kind. + Unknown, + // RenderExecutor.Dispatch: the provider ran the kernel itself (a CPU prediction consumed, a masked dword copy). + Consumed, + // RenderExecutor.Dispatch: a frontend image copy. + ImageCopy, + // RenderExecutor.Dispatch: CPU-predicted writes. + KnownWrite, + // RenderRecorder.TryConsume: a metadata clear. + MetadataClear, + // RenderRecorder.TryConsume: a constant fill as an image clear or an absorbed DCC fill. + ConstantFill, + // RenderRecorder.TryConsume: a bounded uniform fill of DCC metadata (TryFillDccMetadata). + DccFill, + // RenderRecorder.TryConsume: a bounded fill as a kernel fill (TryClearImageFromKernelFill). + KernelFill, + // RenderRecorder.TryConsume: a bounded copy (TryCopyWordsOnHost). + KernelCopy, + // RenderRecorder.TryConsume: a compute image clear. + ImageClear, + Count, +} + // Program resolutions computed ahead of their draws. A draw takes one only when it was resolved // from the same register banks with the same inputs; otherwise it resolves its programs itself. public interface IProgramPrefetch @@ -137,6 +170,10 @@ void NoteDispatchEffect() { } + // As NoteDispatchEffect, naming what the dispatch did (ParallelProgramPrefetch counts each kind and refuses some + // exactly rather than bluntly). + void NoteDispatchEffect(DispatchEffectKind kind) => NoteDispatchEffect(); + // The dispatch running now resolved this program (the look-ahead verify names the dispatches a draw looked over). void NoteDispatchProgram(ComputeProgram program) { diff --git a/src/SharpEmu.Libs/Gpu/Rendering/RenderRecorder.Compute.cs b/src/SharpEmu.Libs/Gpu/Rendering/RenderRecorder.Compute.cs index 4713711ef..ea78d2da6 100644 --- a/src/SharpEmu.Libs/Gpu/Rendering/RenderRecorder.Compute.cs +++ b/src/SharpEmu.Libs/Gpu/Rendering/RenderRecorder.Compute.cs @@ -87,8 +87,8 @@ internal sealed partial class RenderRecorder // Each program and HTILE surface NoteHtileStores reported, once. private readonly HashSet<(ulong Hash, ulong Address)> _loggedHtileStores = new(); - // Told when a dispatch is consumed by a host fill or copy (ParallelProgramPrefetch.NoteDispatchEffect). - public Action? DispatchEffect { get; set; } + // Told when a dispatch is consumed by a host fill or copy, and which (ParallelProgramPrefetch.NoteDispatchEffect). + public Action? DispatchEffect { get; set; } public void Record(ResolvedDispatch record) { @@ -147,9 +147,10 @@ private void RecordDispatch(ResolvedDispatch record) if (record.IndirectArgumentsAddress == 0 && !record.Retried) { bool consumed; + DispatchEffectKind effect; using (RenderPhaseProfile.MeasureDetail(RenderPhaseProfile.Phase.DispatchConsume)) { - consumed = TryConsume(record, program, out var disposition); + consumed = TryConsume(record, program, out var disposition, out effect); if (consumed) { RenderExecutor.TraceFrameDispatch(_host, disposition!, shader, program.Hash, record.GroupsX, record.GroupsY, record.GroupsZ, 0); @@ -166,7 +167,7 @@ private void RecordDispatch(ResolvedDispatch record) if (consumed) { // A host fill or copy in its place: a dispatch resolved ahead of it does not stand (ParallelProgramPrefetch). - DispatchEffect?.Invoke(); + DispatchEffect?.Invoke(effect); _host.ResetBindings(); return; } @@ -319,13 +320,15 @@ private void RecordDispatch(ResolvedDispatch record) // The host consumers, in the order the dispatch is offered to them. disposition names the one // that took it, for the frame trace. - private bool TryConsume(ResolvedDispatch record, ShaderProgramInfo program, out string? disposition) + private bool TryConsume(ResolvedDispatch record, ShaderProgramInfo program, out string? disposition, out DispatchEffectKind effect) { disposition = null; + effect = DispatchEffectKind.Unknown; if (record.MetadataClearCount != 0 && TryClearMetadata(record.MetadataClear, program, program.Frontend is not null && program.StoresUniformValues)) { disposition = "metadata-clear"; + effect = DispatchEffectKind.MetadataClear; return true; } @@ -341,6 +344,7 @@ private bool TryConsume(ResolvedDispatch record, ShaderProgramInfo program, out if (consumed) { disposition = "constant-fill"; + effect = DispatchEffectKind.ConstantFill; return true; } } @@ -348,8 +352,9 @@ private bool TryConsume(ResolvedDispatch record, ShaderProgramInfo program, out if (record.BoundedFill is { } bounded) { ReadOnlySpan pattern = bounded.Pattern; - var consumed = (bounded.Uniform && _host.TryFillDccMetadata(bounded.Address, bounded.Size, bounded.Value)) || - _host.TryClearImageFromKernelFill(bounded.Address, bounded.Size, pattern[..bounded.PatternLength]); + // Which of the two took it: a DCC metadata fill and a kernel fill change different host state. + var dcc = bounded.Uniform && _host.TryFillDccMetadata(bounded.Address, bounded.Size, bounded.Value); + var consumed = dcc || _host.TryClearImageFromKernelFill(bounded.Address, bounded.Size, pattern[..bounded.PatternLength]); if (RenderTrace.Enabled && RenderTrace.MetadataClear()) { RenderTrace.Write($"Bounded fill: shader=0x{program.Hash:X16} address=0x{bounded.Address:X16} size=0x{bounded.Size:X} value=0x{bounded.Value:X8} consumed={consumed}"); @@ -358,6 +363,7 @@ private bool TryConsume(ResolvedDispatch record, ShaderProgramInfo program, out if (consumed) { disposition = "bounded-fill"; + effect = dcc ? DispatchEffectKind.DccFill : DispatchEffectKind.KernelFill; return true; } } @@ -375,6 +381,7 @@ private bool TryConsume(ResolvedDispatch record, ShaderProgramInfo program, out { record.Program.KnownWrite?.Release(); disposition = "bounded-copy"; + effect = DispatchEffectKind.KernelCopy; return true; } @@ -401,6 +408,7 @@ private bool TryConsume(ResolvedDispatch record, ShaderProgramInfo program, out if (registered || filledOnHost) { disposition = "image-clear"; + effect = DispatchEffectKind.ImageClear; return true; } @@ -413,6 +421,7 @@ private bool TryConsume(ResolvedDispatch record, ShaderProgramInfo program, out } disposition = "image-clear"; + effect = DispatchEffectKind.ImageClear; return true; } diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.ConcurrentResolve.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.ConcurrentResolve.cs index 489a2b124..b782e1582 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.ConcurrentResolve.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.ConcurrentResolve.cs @@ -61,6 +61,13 @@ internal sealed partial class MetalRenderHost : IConcurrentResolveHost // and the copies read through as a dispatch's does (IsConcurrentResolveStillCurrentAcrossDispatches). bool IConcurrentResolveHost.PrefetchedDrawsCrossDispatches => true; + // A consumed kernel fill or copy (TryClearImageFromKernelFill, TryCopyWordsOnHost; MetalRenderHost.KernelFills) is + // either intercepted, which does the bookkeeping a storage store into its destination would and logs that write + // (TryInterceptKernelFill, TryInterceptKernelCopy: NoteGuestMemoryWrite -> MetalGpuWriteRanges.Note -> LogWrite), + // or found identical, which writes nothing (TakeIdenticalKernel). So IsConcurrentResolveStillCurrent sees it as it + // sees a dispatch's store. A DCC or constant fill and an image clear are not logged this way and stay blunt. + bool IConcurrentResolveHost.KernelFillWritesLogged => true; + bool IConcurrentResolveHost.IsStillCurrentAcrossDispatches(object assumptions) => IsConcurrentResolveStillCurrentAcrossDispatches(assumptions); private long _writeLogRefusals; diff --git a/tests/SharpEmu.Gpu.Metal.Tests/MetalClearFoldingTests.DispatchPrefetch.cs b/tests/SharpEmu.Gpu.Metal.Tests/MetalClearFoldingTests.DispatchPrefetch.cs index 65d15e251..9f74abb0b 100644 --- a/tests/SharpEmu.Gpu.Metal.Tests/MetalClearFoldingTests.DispatchPrefetch.cs +++ b/tests/SharpEmu.Gpu.Metal.Tests/MetalClearFoldingTests.DispatchPrefetch.cs @@ -74,6 +74,39 @@ public void ADispatchResolutionStandsAcrossAWriteToBytesItDidNotRead() concurrent.ReleaseAssumptions(assumptions); } + // A kernel copy consumed because its destination already holds the result writes nothing, so a resolution that read + // the destination before it stands across it (KernelFillWritesLogged: the take leaves a consumed kernel fill or copy + // to this check); a store logged over the destination, as an intercepted fill or copy logs, refuses it. + [Theory] + [InlineData(false)] + [InlineData(true)] + public void AResolutionStandsAcrossAnIdenticalKernelCopyOfWhatItReadButNotAcrossALoggedFill(bool fill) + { + if (!RequireDevice()) return; + using var rig = new Rig(Device.Value); + var host = rig.Host; + host.HostKernelCopyMode = MetalHostKernelCopyMode.Identical; + WriteKernelSource(rig); + WriteKernelResult(rig); + var concurrent = (IConcurrentResolveHost)host; + Assert.True(concurrent.KernelFillWritesLogged); + var assumptions = ResolveWordConcurrently(host, KernelDestination + 5 * sizeof(uint)); + + if (fill) + { + // What TryInterceptKernelFill notes for the bytes it clears. + host.NoteGuestMemoryWrite(KernelDestination, KernelBytes, MetalGpuWriteOrigin.Fill); + } + else + { + Assert.True(host.TryCopyWordsOnHost(KernelDestination, KernelSource, KernelPeriod, KernelWords)); + Assert.Equal(1, host.KernelCopiesElided); + } + + Assert.Equal(!fill, concurrent.IsStillCurrentAcrossDispatches(assumptions)); + concurrent.ReleaseAssumptions(assumptions); + } + // A resolution (a draw's resolved ahead of dispatches, ParallelProgramPrefetch.SubmitDrawAhead, or a dispatch's) read // a destination word as the source of the pending copy that writes it, dropping the copy's owned answer. A dispatch // it was resolved ahead of then stores: over the word read (that store, not the copy, is now the word's latest diff --git a/tests/SharpEmu.Libs.Tests/Gpu/Rendering/ParallelProgramPrefetchComputeTests.cs b/tests/SharpEmu.Libs.Tests/Gpu/Rendering/ParallelProgramPrefetchComputeTests.cs index 185bc6983..8e5b37736 100644 --- a/tests/SharpEmu.Libs.Tests/Gpu/Rendering/ParallelProgramPrefetchComputeTests.cs +++ b/tests/SharpEmu.Libs.Tests/Gpu/Rendering/ParallelProgramPrefetchComputeTests.cs @@ -46,6 +46,8 @@ private sealed class ConcurrentHost : IConcurrentResolveHost internal bool Raced; private int _crossChecksSinceRace; internal int Checks, CrossChecks; + internal bool FillWritesLogged = true; + public bool KernelFillWritesLogged => FillWritesLogged; public void BeginConcurrentResolve() { } public object EndConcurrentResolve() => this; public bool IsStillCurrent(object assumptions) @@ -165,6 +167,81 @@ public void ADispatchEffectRefusesOnlyTheJobsResolvedAheadOfIt() Assert.True(Take(banks, behind)); } + // A kernel fill or copy on a host that logs its write (KernelFillWritesLogged) does not refuse a job resolved ahead of + // it for itself: the take's ownership check, which tests the host's write log over what the job read, decides. A job + // whose reads the logged write covers is refused (Ownership); one whose reads it does not cover is taken. + [Theory] + [InlineData(DispatchEffectKind.KernelFill, false)] + [InlineData(DispatchEffectKind.KernelFill, true)] + [InlineData(DispatchEffectKind.KernelCopy, false)] + [InlineData(DispatchEffectKind.KernelCopy, true)] + public void AKernelFillOrCopyRefusesOnlyAJobWhoseReadsItsLoggedWriteCovers(DispatchEffectKind kind, bool covers) + { + var banks = Banks().Snapshot(); + var ahead = Resolved(banks, gate: 3); + // Item 3 is the dispatch consumed as the fill or copy; the host logged its write over the destination, which + // covers what the job read or not. + _prefetch.NoteDispatchEffect(kind); + _concurrent.CurrentAcrossDispatches = !covers; + _prefetch.AdvanceGate(4); + Assert.Equal(!covers, Take(banks, ahead)); + Assert.Equal(1, _concurrent.CrossChecks); + var refused = _prefetch.TakeComputeCounters().Refused; + Assert.Equal(0, refused[(int)ParallelProgramPrefetch.ComputeRefusal.Effects]); + Assert.Equal(covers ? 1 : 0, refused[(int)ParallelProgramPrefetch.ComputeRefusal.Ownership]); + var report = _prefetch.TakeComputeReport(); + Assert.Contains($"{(kind == DispatchEffectKind.KernelFill ? "kernel_fill" : "kernel_copy")}=1", report); + Assert.Contains($"exact_effects=(mode=on,refused={(covers ? 1 : 0)},taken={(covers ? 0 : 1)})", report); + } + + // The blunt rule stands for every other kind, for a kernel fill or copy with SHARPEMU_PREFETCH_EXACT_EFFECTS=0 (the + // property), and on a host that does not log them: the job is refused for the effect, unchecked. + [Theory] + [InlineData(DispatchEffectKind.KernelFill, false, true)] + [InlineData(DispatchEffectKind.KernelCopy, false, true)] + [InlineData(DispatchEffectKind.KernelCopy, true, false)] + [InlineData(DispatchEffectKind.Unknown, true, true)] + [InlineData(DispatchEffectKind.Consumed, true, true)] + [InlineData(DispatchEffectKind.ImageCopy, true, true)] + [InlineData(DispatchEffectKind.KnownWrite, true, true)] + [InlineData(DispatchEffectKind.MetadataClear, true, true)] + [InlineData(DispatchEffectKind.ConstantFill, true, true)] + [InlineData(DispatchEffectKind.DccFill, true, true)] + [InlineData(DispatchEffectKind.ImageClear, true, true)] + public void TheBluntRuleRefusesEveryOtherKindAndAllOfThemWhenExactEffectsAreOff(DispatchEffectKind kind, bool exact, bool logged) + { + _prefetch.ExactEffects = exact; + _concurrent.FillWritesLogged = logged; + var banks = Banks().Snapshot(); + var ahead = Resolved(banks, gate: 3); + var behind = _prefetch.SubmitCompute(banks, 4, Initiator, 4, 2, 1, false); + _prefetch.NoteDispatchEffect(kind); + _prefetch.AdvanceGate(4); + _prefetch.WaitIdle(); + Assert.False(Take(banks, ahead)); + Assert.Equal(0, _concurrent.CrossChecks); + Assert.Equal(1, Refused(ParallelProgramPrefetch.ComputeRefusal.Effects)); + Assert.True(Take(banks, behind)); + Assert.Contains($"exact_effects=(mode={(exact && logged ? "on" : "off")},refused=0,taken=0)", _prefetch.TakeComputeReport()); + } + + // =verify resolves a job taken across a kernel fill again and finds the same program. + [Fact] + public void VerifyPassesAJobTakenAcrossAKernelFill() + { + _prefetch.LookaheadMode = ParallelProgramPrefetch.DrawLookaheadMode.Verify; + var banks = Banks().Snapshot(); + var ahead = Resolved(banks, gate: 3); + _prefetch.NoteDispatchEffect(DispatchEffectKind.KernelFill); + _prefetch.AdvanceGate(4); + var resolutions = _pipelines.ComputeAheadResolutions; + Assert.True(Take(banks, ahead)); + Assert.Equal(resolutions + 1, _pipelines.ComputeAheadResolutions); + var report = _prefetch.TakeComputeReport(); + Assert.Contains("exact_effects=(mode=on,refused=0,taken=1)", report); + Assert.EndsWith("dispatch_verify=(verified=1,raced=0,failed=0)", report); + } + // A collector call that noted an effect refuses the dispatch jobs resolved ahead of it as a dispatch's effect does; // one that did nothing refuses none. [Theory] diff --git a/tests/SharpEmu.Libs.Tests/Gpu/Rendering/ParallelProgramPrefetchDrawLookaheadTests.cs b/tests/SharpEmu.Libs.Tests/Gpu/Rendering/ParallelProgramPrefetchDrawLookaheadTests.cs index 8d0578921..c3c4a66d6 100644 --- a/tests/SharpEmu.Libs.Tests/Gpu/Rendering/ParallelProgramPrefetchDrawLookaheadTests.cs +++ b/tests/SharpEmu.Libs.Tests/Gpu/Rendering/ParallelProgramPrefetchDrawLookaheadTests.cs @@ -48,6 +48,7 @@ private sealed class ConcurrentHost : IConcurrentResolveHost internal bool CurrentAcrossDispatches = true; internal int Checks, CrossChecks; public bool PrefetchedDrawsCrossDispatches => true; + public bool KernelFillWritesLogged => true; public void BeginConcurrentResolve() { } public object EndConcurrentResolve() => this; public bool IsStillCurrent(object assumptions) @@ -162,6 +163,22 @@ public void ADispatchThatDidMoreThanEncodeRefusesTheDrawsResolvedAheadOfItOnly() Assert.Equal(1, counters.Refused[(int)ParallelProgramPrefetch.DrawLookaheadRefusal.Effects]); } + // A draw's take keeps the blunt rule for a kernel fill or copy the host logs, which a dispatch's take leaves to its + // ownership check (ParallelProgramPrefetch.ExactEffects). + [Theory] + [InlineData(DispatchEffectKind.KernelFill)] + [InlineData(DispatchEffectKind.KernelCopy)] + public void AKernelFillOrCopyStillRefusesTheDrawsResolvedAheadOfIt(DispatchEffectKind kind) + { + var banks = Banks().Snapshot(); + var ahead = Resolved(banks, gate: 0, fullGate: 1); + _prefetch.NoteDispatchEffect(kind); + _prefetch.AdvanceGate(1); + Assert.False(Take(banks, ahead)); + Assert.Equal(1, Counters().Refused[(int)ParallelProgramPrefetch.DrawLookaheadRefusal.Effects]); + Assert.Equal(0, _concurrent.CrossChecks); + } + [Fact] public void AnEffectOfTheLastDispatchAheadRefusesEveryDrawResolvedBeforeIt() { From a3f6c202423e209c910fb94cbd06312d05b6ea89 Mon Sep 17 00:00:00 2001 From: kuba Date: Tue, 17 Nov 2026 06:45:32 +0000 Subject: [PATCH 171/178] [GPU] Leave a draw resolved ahead of a logged kernel fill or copy to the ownership check too A draw's take over dispatches refused on every dispatch effect. For a kernel fill or copy the host logs as a GPU write it now makes the same check a dispatch's take makes (IsStillCurrentAcrossDispatches), which refuses the draw only when the write covers what its resolution read. Demon's Souls: about 9 more draws a frame taken; a verify run (SHARPEMU_PREFETCH_DRAW_LOOKAHEAD=verify) re-resolved 7,875 such draws without a difference. exact_effects= gains draws, draw_refused and draw_taken. SHARPEMU_PREFETCH_EXACT_EFFECTS=dispatch keeps the old rule for draws only. --- docs/macos/configuration.md | 2 +- .../Gpu/Rendering/ParallelProgramPrefetch.cs | 24 ++++++++++-- .../ParallelProgramPrefetchComputeTests.cs | 6 +-- ...rallelProgramPrefetchDrawLookaheadTests.cs | 38 +++++++++++++++++-- 4 files changed, 59 insertions(+), 11 deletions(-) diff --git a/docs/macos/configuration.md b/docs/macos/configuration.md index ec68b8f54..ce69cdb38 100644 --- a/docs/macos/configuration.md +++ b/docs/macos/configuration.md @@ -70,7 +70,7 @@ them for measurements or to isolate a problem. | `SHARPEMU_METAL_V2_ASYNC_PIPELINES` | on | `0` builds pipeline states on the GPU worker thread. | | `SHARPEMU_METAL_V2_ASYNC_LIBRARIES` | on | `0` compiles each shader library on the thread that needs it, not on the compile pool. | | `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 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 resolved ahead of them; a draw's take still refuses on all of them. The prefetch counters report `dispatch_effects=(...)` by kind and `exact_effects=(mode,refused,taken)`, the jobs the old rule would have refused that the check refused or took. `0` refuses on every effect again. | +| `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=`). | | `SHARPEMU_METAL_V2_PIPELINE_LIMIT` | `8192` | Pipeline states kept before idle ones are released. `0` is unlimited. | | `SHARPEMU_METAL_V2_MODULE_LIMIT` | `2048` | The same for shader modules. | diff --git a/src/SharpEmu.Libs/Gpu/Rendering/ParallelProgramPrefetch.cs b/src/SharpEmu.Libs/Gpu/Rendering/ParallelProgramPrefetch.cs index d10621df4..d5dbd21a4 100644 --- a/src/SharpEmu.Libs/Gpu/Rendering/ParallelProgramPrefetch.cs +++ b/src/SharpEmu.Libs/Gpu/Rendering/ParallelProgramPrefetch.cs @@ -469,7 +469,8 @@ public long[] TakeProviderRefusals() // (IConcurrentResolveHost.KernelFillWritesLogged) are noted apart (_lastExactDispatchEffect): a dispatch job resolved // ahead of one is not refused for it, since the take's IsStillCurrentAcrossDispatches already refuses a job whose // reads a write logged since its resolution began covers, the fill's or copy's as any dispatch's store. Every - // other kind keeps the blunt refusal. A draw's take still refuses on either (TryTakeGraphics). + // other kind keeps the blunt refusal. A draw's take over them follows the same rule (ExactDrawEffects): its + // resolution's reads are answers of the same kind, and its take makes the same check. public void NoteDispatchEffect(DispatchEffectKind kind) { Interlocked.Increment(ref _dispatchEffects[(int)kind]); @@ -485,6 +486,10 @@ private bool IsExactEffect(DispatchEffectKind kind) => // SHARPEMU_PREFETCH_EXACT_EFFECTS=0 refuses dispatch jobs for every effect kind again. Tests set it on one instance. internal bool ExactEffects { get; set; } = ExactEffectsDefault; + // SHARPEMU_PREFETCH_EXACT_EFFECTS=dispatch keeps the blunt rule for a draw's take only (and =0 for both). + internal bool ExactDrawEffects { get; set; } = + Environment.GetEnvironmentVariable("SHARPEMU_PREFETCH_EXACT_EFFECTS") != "dispatch"; + // The last kernel fill or copy noted exactly (NoteDispatchEffect), as _lastDispatchEffect; -1 while none was. private long _lastExactDispatchEffect = -1; @@ -492,6 +497,7 @@ private bool IsExactEffect(DispatchEffectKind kind) => // refused them) that the take refused anyway (ownership or write log) or took. private readonly long[] _dispatchEffects = new long[(int)DispatchEffectKind.Count]; private long _exactEffectRefused, _exactEffectTaken; + private long _exactDrawEffectRefused, _exactDrawEffectTaken; private static readonly string[] DispatchEffectNames = ["unknown", "consumed", "image_copy", "known_write", "metadata_clear", "constant_fill", "dcc_fill", "kernel_fill", "kernel_copy", "image_clear"]; @@ -791,11 +797,18 @@ public bool TryTakeGraphics(RegisterBanks banks, in GraphicsProgramInputs inputs : !lookedAhead ? (_concurrent.IsStillCurrent(job.Assumptions!) ? DrawLookaheadRefusal.Count : DrawLookaheadRefusal.Ownership) // A collector call or a dispatch that ran after the resolution began (gate above ExecutedAtStart) noted an effect. : Volatile.Read(ref _lastCollectEffect) >= job.ExecutedAtStart ? DrawLookaheadRefusal.CollectEffects - // Exact effects too: the draw's take keeps the blunt rule (NoteDispatchEffect). - : Math.Max(Volatile.Read(ref _lastDispatchEffect), Volatile.Read(ref _lastExactDispatchEffect)) >= job.ExecutedAtStart + // A logged kernel fill or copy is left to the ownership check below, as for a dispatch's take (ExactDrawEffects). + : Math.Max(Volatile.Read(ref _lastDispatchEffect), ExactDrawEffects ? -1 : Volatile.Read(ref _lastExactDispatchEffect)) >= job.ExecutedAtStart ? DrawLookaheadRefusal.Effects : !_concurrent.IsStillCurrentAcrossDispatches(job.Assumptions!) ? DrawLookaheadRefusal.Ownership : DrawLookaheadRefusal.Count; + // A kernel fill or copy the blunt rule would have refused the draw for: the ownership check decided instead. + if (lookedAhead && ExactDrawEffects && refusal is DrawLookaheadRefusal.Count or DrawLookaheadRefusal.Ownership && + Volatile.Read(ref _lastExactDispatchEffect) >= job.ExecutedAtStart) + { + Interlocked.Increment(ref refusal == DrawLookaheadRefusal.Count ? ref _exactDrawEffectTaken : ref _exactDrawEffectRefused); + } + // =verify keeps a taken look-ahead's assumptions to its comparison (VerifyLookahead): a difference whose answers // changed after the take is a race, not a hole. var verifies = refusal == DrawLookaheadRefusal.Count && lookedAhead && LookaheadMode == DrawLookaheadMode.Verify; @@ -1214,7 +1227,10 @@ private string TakeDispatchEffectReport() return builder.Append(") exact_effects=(mode=").Append(ExactEffects && _concurrent.KernelFillWritesLogged ? "on" : "off") .Append(",refused=").Append(Interlocked.Exchange(ref _exactEffectRefused, 0)) - .Append(",taken=").Append(Interlocked.Exchange(ref _exactEffectTaken, 0)).Append(')').ToString(); + .Append(",taken=").Append(Interlocked.Exchange(ref _exactEffectTaken, 0)) + .Append(",draws=").Append(ExactDrawEffects ? "on" : "off") + .Append(",draw_refused=").Append(Interlocked.Exchange(ref _exactDrawEffectRefused, 0)) + .Append(",draw_taken=").Append(Interlocked.Exchange(ref _exactDrawEffectTaken, 0)).Append(')').ToString(); } // Why a draw's job was not resolved when its draw took it: still gated on the work before it, the resolving diff --git a/tests/SharpEmu.Libs.Tests/Gpu/Rendering/ParallelProgramPrefetchComputeTests.cs b/tests/SharpEmu.Libs.Tests/Gpu/Rendering/ParallelProgramPrefetchComputeTests.cs index 8e5b37736..8982b2737 100644 --- a/tests/SharpEmu.Libs.Tests/Gpu/Rendering/ParallelProgramPrefetchComputeTests.cs +++ b/tests/SharpEmu.Libs.Tests/Gpu/Rendering/ParallelProgramPrefetchComputeTests.cs @@ -191,7 +191,7 @@ public void AKernelFillOrCopyRefusesOnlyAJobWhoseReadsItsLoggedWriteCovers(Dispa Assert.Equal(covers ? 1 : 0, refused[(int)ParallelProgramPrefetch.ComputeRefusal.Ownership]); var report = _prefetch.TakeComputeReport(); Assert.Contains($"{(kind == DispatchEffectKind.KernelFill ? "kernel_fill" : "kernel_copy")}=1", report); - Assert.Contains($"exact_effects=(mode=on,refused={(covers ? 1 : 0)},taken={(covers ? 0 : 1)})", report); + Assert.Contains($"exact_effects=(mode=on,refused={(covers ? 1 : 0)},taken={(covers ? 0 : 1)},", report); } // The blunt rule stands for every other kind, for a kernel fill or copy with SHARPEMU_PREFETCH_EXACT_EFFECTS=0 (the @@ -222,7 +222,7 @@ public void TheBluntRuleRefusesEveryOtherKindAndAllOfThemWhenExactEffectsAreOff( Assert.Equal(0, _concurrent.CrossChecks); Assert.Equal(1, Refused(ParallelProgramPrefetch.ComputeRefusal.Effects)); Assert.True(Take(banks, behind)); - Assert.Contains($"exact_effects=(mode={(exact && logged ? "on" : "off")},refused=0,taken=0)", _prefetch.TakeComputeReport()); + Assert.Contains($"exact_effects=(mode={(exact && logged ? "on" : "off")},refused=0,taken=0,", _prefetch.TakeComputeReport()); } // =verify resolves a job taken across a kernel fill again and finds the same program. @@ -238,7 +238,7 @@ public void VerifyPassesAJobTakenAcrossAKernelFill() Assert.True(Take(banks, ahead)); Assert.Equal(resolutions + 1, _pipelines.ComputeAheadResolutions); var report = _prefetch.TakeComputeReport(); - Assert.Contains("exact_effects=(mode=on,refused=0,taken=1)", report); + Assert.Contains("exact_effects=(mode=on,refused=0,taken=1,", report); Assert.EndsWith("dispatch_verify=(verified=1,raced=0,failed=0)", report); } diff --git a/tests/SharpEmu.Libs.Tests/Gpu/Rendering/ParallelProgramPrefetchDrawLookaheadTests.cs b/tests/SharpEmu.Libs.Tests/Gpu/Rendering/ParallelProgramPrefetchDrawLookaheadTests.cs index c3c4a66d6..1bc9abf06 100644 --- a/tests/SharpEmu.Libs.Tests/Gpu/Rendering/ParallelProgramPrefetchDrawLookaheadTests.cs +++ b/tests/SharpEmu.Libs.Tests/Gpu/Rendering/ParallelProgramPrefetchDrawLookaheadTests.cs @@ -163,13 +163,45 @@ public void ADispatchThatDidMoreThanEncodeRefusesTheDrawsResolvedAheadOfItOnly() Assert.Equal(1, counters.Refused[(int)ParallelProgramPrefetch.DrawLookaheadRefusal.Effects]); } - // A draw's take keeps the blunt rule for a kernel fill or copy the host logs, which a dispatch's take leaves to its - // ownership check (ParallelProgramPrefetch.ExactEffects). + // A kernel fill or copy the host logs does not refuse the draws resolved ahead of it by itself: the take's ownership + // check decides, as for a dispatch's take (ParallelProgramPrefetch.ExactDrawEffects). [Theory] [InlineData(DispatchEffectKind.KernelFill)] [InlineData(DispatchEffectKind.KernelCopy)] - public void AKernelFillOrCopyStillRefusesTheDrawsResolvedAheadOfIt(DispatchEffectKind kind) + public void AKernelFillOrCopyLeavesTheDrawsResolvedAheadOfItToTheOwnershipCheck(DispatchEffectKind kind) { + var banks = Banks().Snapshot(); + var ahead = Resolved(banks, gate: 0, fullGate: 1); + _prefetch.NoteDispatchEffect(kind); + _prefetch.AdvanceGate(1); + Assert.True(Take(banks, ahead)); + Assert.Equal(0, Counters().Refused[(int)ParallelProgramPrefetch.DrawLookaheadRefusal.Effects]); + Assert.Equal(1, _concurrent.CrossChecks); + } + + [Theory] + [InlineData(DispatchEffectKind.KernelFill)] + [InlineData(DispatchEffectKind.KernelCopy)] + public void AKernelFillOrCopyOverWhatTheDrawReadRefusesItForOwnership(DispatchEffectKind kind) + { + var banks = Banks().Snapshot(); + var ahead = Resolved(banks, gate: 0, fullGate: 1); + _prefetch.NoteDispatchEffect(kind); + _prefetch.AdvanceGate(1); + _concurrent.CurrentAcrossDispatches = false; + Assert.False(Take(banks, ahead)); + Assert.Equal(1, Counters().Refused[(int)ParallelProgramPrefetch.DrawLookaheadRefusal.Ownership]); + } + + // SHARPEMU_PREFETCH_EXACT_EFFECTS=dispatch (and =0): the draw's take refuses on a kernel fill or copy as on any effect. + [Theory] + [InlineData(DispatchEffectKind.KernelFill, false, true)] + [InlineData(DispatchEffectKind.KernelCopy, false, true)] + [InlineData(DispatchEffectKind.KernelFill, true, false)] + public void TheBluntRuleForDrawsRefusesOnAKernelFillOrCopy(DispatchEffectKind kind, bool exactDraws, bool exact) + { + _prefetch.ExactDrawEffects = exactDraws; + _prefetch.ExactEffects = exact; var banks = Banks().Snapshot(); var ahead = Resolved(banks, gate: 0, fullGate: 1); _prefetch.NoteDispatchEffect(kind); From 37e588b39798aa10da8145e4cd72e192c9a490f9 Mon Sep 17 00:00:00 2001 From: kuba Date: Tue, 17 Nov 2026 07:13:14 +0000 Subject: [PATCH 172/178] [Core] Dump guest memory named by register/deref expressions on a native fault SHARPEMU_FAULT_DUMP=label=expr:len[,...] (expr: register, hex, [expr] qword load, joined by + or -) prints windows the fixed register dumps cannot reach, such as a caller's locals or a structure two pointers away. SHARPEMU_FAULT_DUMP_REPEAT_MS dumps them again after a delay, so bytes another thread is still writing show up as a difference. Off unless set; used to trace the Demon's Souls load SIGSEGV. --- .../DirectExecutionBackend.Exceptions.cs | 111 ++++++++++++++++++ .../Cpu/FaultDumpExpressionTests.cs | 53 +++++++++ 2 files changed, 164 insertions(+) create mode 100644 tests/SharpEmu.Libs.Tests/Cpu/FaultDumpExpressionTests.cs diff --git a/src/SharpEmu.Core/Cpu/Native/DirectExecutionBackend.Exceptions.cs b/src/SharpEmu.Core/Cpu/Native/DirectExecutionBackend.Exceptions.cs index 8c089d0f2..b52a2d5fa 100644 --- a/src/SharpEmu.Core/Cpu/Native/DirectExecutionBackend.Exceptions.cs +++ b/src/SharpEmu.Core/Cpu/Native/DirectExecutionBackend.Exceptions.cs @@ -360,6 +360,13 @@ internal unsafe int VectoredHandler(void* exceptionInfo) Console.Error.WriteLine("[LOADER][WARNING] Could not walk RBP frame chain."); } + DumpFaultExpressions(new Dictionary(StringComparer.OrdinalIgnoreCase) + { + ["rax"] = rax, ["rbx"] = rbx, ["rcx"] = rcx, ["rdx"] = rdx, ["rsi"] = rsi, ["rdi"] = rdi, + ["rbp"] = rbp, ["rsp"] = rsp, ["rip"] = rip, ["r8"] = r8, ["r9"] = r9, ["r10"] = r10, + ["r11"] = r11, ["r12"] = r12, ["r13"] = r13, ["r14"] = r14, ["r15"] = r15, + }); + switch (exceptionCode) { case 3221225477u: @@ -1252,6 +1259,110 @@ private void DumpPointerWindow(string name, ulong baseAddress, int size) } } + // SHARPEMU_FAULT_DUMP=label=expr:len[,label=expr:len...] dumps guest memory the + // fixed register windows cannot reach, such as a caller's locals or a structure + // two pointers away. expr: register | hex | [expr] (qword load) joined by + or -, + // for example elem=[[rbp]-0x360]:0x60. SHARPEMU_FAULT_DUMP_REPEAT_MS= dumps the + // same windows again after n ms, so bytes another thread is still writing show up + // as a difference between the two passes. + private void DumpFaultExpressions(Dictionary registers) + { + var spec = Environment.GetEnvironmentVariable("SHARPEMU_FAULT_DUMP"); + if (string.IsNullOrWhiteSpace(spec)) + { + return; + } + + var entries = spec.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries); + DumpFaultExpressionPass("now", entries, registers); + if (int.TryParse(Environment.GetEnvironmentVariable("SHARPEMU_FAULT_DUMP_REPEAT_MS"), out var repeatMs) && + repeatMs > 0) + { + Thread.Sleep(Math.Min(repeatMs, 5000)); + DumpFaultExpressionPass($"after {repeatMs} ms", entries, registers); + } + } + + private void DumpFaultExpressionPass(string pass, string[] entries, Dictionary registers) + { + foreach (var entry in entries) + { + var equals = entry.IndexOf('='); + var colon = entry.LastIndexOf(':'); + if (equals <= 0 || colon <= equals || + !TryParseFaultHex(entry[(colon + 1)..], out var length) || length == 0 || length > 0x1000) + { + Console.Error.WriteLine($"[LOADER][WARN] fault-dump: malformed entry '{entry}'"); + continue; + } + + var label = entry[..equals]; + var expression = entry[(equals + 1)..colon]; + var position = 0; + if (!TryEvaluateFaultExpression(expression, ref position, registers, out var address) || + position != expression.Length) + { + Console.Error.WriteLine($"[LOADER][INFO] fault-dump[{pass}] {label}: '{expression}' unresolved"); + continue; + } + + DumpPointerWindow($"fault-dump[{pass}] {label}={expression}", address, (int)length); + } + Console.Error.Flush(); + } + + internal static bool TryEvaluateFaultExpression( + string text, ref int position, Dictionary registers, out ulong value) + { + value = 0; + var sign = 1; + var first = true; + while (position < text.Length && text[position] != ']') + { + if (!first) + { + if (text[position] == '+') sign = 1; + else if (text[position] == '-') sign = -1; + else return false; + position++; + } + first = false; + + ulong term; + if (position < text.Length && text[position] == '[') + { + position++; + if (!TryEvaluateFaultExpression(text, ref position, registers, out var inner) || + position >= text.Length || text[position] != ']' || + !TryReadDiagnosticHostQword(inner, out term)) + { + return false; + } + position++; + } + else + { + var start = position; + while (position < text.Length && char.IsLetterOrDigit(text[position])) position++; + var token = text[start..position]; + if (!registers.TryGetValue(token, out term) && !TryParseFaultHex(token, out term)) + { + return false; + } + } + + value = sign > 0 ? value + term : value - term; + } + + return !first; + } + + private static bool TryParseFaultHex(string text, out ulong value) + { + var digits = text.StartsWith("0x", StringComparison.OrdinalIgnoreCase) ? text[2..] : text; + return ulong.TryParse(digits, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out value); + } + private unsafe bool TryReadQword(ulong address, out ulong value) { value = 0; diff --git a/tests/SharpEmu.Libs.Tests/Cpu/FaultDumpExpressionTests.cs b/tests/SharpEmu.Libs.Tests/Cpu/FaultDumpExpressionTests.cs new file mode 100644 index 000000000..d5522f001 --- /dev/null +++ b/tests/SharpEmu.Libs.Tests/Cpu/FaultDumpExpressionTests.cs @@ -0,0 +1,53 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using System.Runtime.InteropServices; +using SharpEmu.Core.Cpu.Native; +using Xunit; + +namespace SharpEmu.Libs.Tests.Cpu; + +public sealed class FaultDumpExpressionTests +{ + private static bool Evaluate(string text, Dictionary registers, out ulong value) + { + var position = 0; + return DirectExecutionBackend.TryEvaluateFaultExpression(text, ref position, registers, out value) && + position == text.Length; + } + + [Fact] + public void RegistersAndOffsetsAddAndSubtract() + { + var registers = new Dictionary(StringComparer.OrdinalIgnoreCase) { ["rbp"] = 0x1000, ["r13"] = 3 }; + + Assert.True(Evaluate("rbp-0x360+r13", registers, out var value)); + Assert.Equal(0x1000UL - 0x360 + 3, value); + Assert.False(Evaluate("rbp*2", registers, out _)); + Assert.False(Evaluate("nosuchreg", registers, out _)); + } + + [Fact] + public unsafe void BracketsLoadAQwordAndNest() + { + var block = (ulong*)NativeMemory.AlignedAlloc(32, 16); + try + { + // block[0] -> block[2]; block[2] holds the payload two loads away. + block[0] = (ulong)(block + 2); + block[1] = 0; + block[2] = 0x1122334455667788; + var registers = new Dictionary(StringComparer.OrdinalIgnoreCase) { ["rdi"] = (ulong)block + 8 }; + + Assert.True(Evaluate("[rdi-8]", registers, out var pointer)); + Assert.Equal((ulong)(block + 2), pointer); + Assert.True(Evaluate("[[rdi-0x8]]+1", registers, out var payload)); + Assert.Equal(0x1122334455667789UL, payload); + Assert.False(Evaluate("[rdi-8", registers, out _)); + } + finally + { + NativeMemory.AlignedFree(block); + } + } +} From ff37c7de013cbe73b68ad0a3603033fc76b847ea Mon Sep 17 00:00:00 2001 From: kuba Date: Tue, 17 Nov 2026 07:25:07 +0000 Subject: [PATCH 173/178] [Libc] Do not hand __cxa_guard_acquire's construction to a thread that claimed after the release A waiting thread read the guard as pending, the owner then released (complete written, claim dropped), and the waiter's claim succeeded: it wrote pending over complete and returned 1, so a function-local static was constructed a second time under the threads already using it. The guard is read again under the claim; a release writes it complete before dropping its own, so that read sees it and the caller gets 0. Found while tracing the Demon's Souls load crash; not shown to be its cause. --- src/SharpEmu.Libs/CxxAbiExports.cs | 22 +++- .../CxaGuardExportsTests.cs | 108 ++++++++++++++++++ 2 files changed, 129 insertions(+), 1 deletion(-) create mode 100644 tests/SharpEmu.Libs.Tests/CxaGuardExportsTests.cs diff --git a/src/SharpEmu.Libs/CxxAbiExports.cs b/src/SharpEmu.Libs/CxxAbiExports.cs index fab20ee57..85b674061 100644 --- a/src/SharpEmu.Libs/CxxAbiExports.cs +++ b/src/SharpEmu.Libs/CxxAbiExports.cs @@ -3,6 +3,7 @@ using System; using System.Collections.Concurrent; +using System.Collections.Generic; using System.Threading; using SharpEmu.HLE; @@ -62,9 +63,28 @@ public static int CxaGuardAcquire(CpuContext ctx) }; if (_inProgress.TryAdd(guardPtr, newState)) { + // The guard was read before the claim, so the thread that held it may have released in between: a + // release writes the guard complete before it drops its claim, so a read made under ours sees that. + // Without it this thread wrote "pending" over "complete" and built the object a second time under + // the threads already using it. + if (!TryReadGuardState(ctx, guardPtr, out _, out initialized, out _)) + { + _inProgress.TryRemove(new KeyValuePair(guardPtr, newState)); + ctx[CpuRegister.Rax] = 0; + return (int)OrbisGen2Result.ORBIS_GEN2_ERROR_MEMORY_FAULT; + } + + if (initialized) + { + _inProgress.TryRemove(new KeyValuePair(guardPtr, newState)); + ctx[CpuRegister.Rax] = 0; + LogGuardResult("guard_acquire", guardPtr, result: 0, initialized, inProgress: false, ownerThreadId: 0); + return (int)OrbisGen2Result.ORBIS_GEN2_OK; + } + if (!TryWriteGuardState(ctx, guardPtr, GuardPendingValue)) { - _inProgress.TryRemove(guardPtr, out _); + _inProgress.TryRemove(new KeyValuePair(guardPtr, newState)); ctx[CpuRegister.Rax] = 0; return (int)OrbisGen2Result.ORBIS_GEN2_ERROR_MEMORY_FAULT; } diff --git a/tests/SharpEmu.Libs.Tests/CxaGuardExportsTests.cs b/tests/SharpEmu.Libs.Tests/CxaGuardExportsTests.cs new file mode 100644 index 000000000..af62d8ae4 --- /dev/null +++ b/tests/SharpEmu.Libs.Tests/CxaGuardExportsTests.cs @@ -0,0 +1,108 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using SharpEmu.HLE; +using SharpEmu.Libs.CxxAbi; +using Xunit; + +namespace SharpEmu.Libs.Tests; + +// __cxa_guard_acquire hands the construction of a function-local static to one caller only. +public sealed class CxaGuardExportsTests +{ + private const ulong Base = 0x1000; + + // Runs an action once, right after a chosen read of a chosen address has returned its bytes. + private sealed class ReadHookMemory(ICpuMemory inner, ulong address, int onRead, Action hook) : ICpuMemory + { + private int _reads; + + public bool TryRead(ulong virtualAddress, Span destination) + { + var read = inner.TryRead(virtualAddress, destination); + if (virtualAddress == address && ++_reads == onRead) + { + hook(); + } + + return read; + } + + public bool TryWrite(ulong virtualAddress, ReadOnlySpan source) => inner.TryWrite(virtualAddress, source); + } + + private static int Acquire(CpuContext context, ulong guard) + { + context[CpuRegister.Rdi] = guard; + Assert.Equal(0, CxaGuardExports.CxaGuardAcquire(context)); + return (int)context[CpuRegister.Rax]; + } + + private static void Release(CpuContext context, ulong guard) + { + context[CpuRegister.Rdi] = guard; + Assert.Equal(0, CxaGuardExports.CxaGuardRelease(context)); + } + + [Fact] + public void TheFirstCallerConstructsAndLaterCallersDoNot() + { + var guard = Base + 0x100; + var context = new CpuContext(new FakeCpuMemory(Base, 0x1000), Generation.Gen5); + Assert.Equal(1, Acquire(context, guard)); + Release(context, guard); + Assert.True(context.TryReadUInt64(guard, out var word)); + Assert.Equal(1ul, word & 0xFF); + Assert.Equal(0, Acquire(context, guard)); + } + + // The owner releases after a second thread has read the guard as pending and before that thread claims it: the + // second thread must find the guard complete, not construct the object again. + [Fact] + public void AReleaseBetweenAWaitersReadAndItsClaimDoesNotHandItTheConstruction() + { + var guard = Base + 0x200; + var memory = new FakeCpuMemory(Base, 0x1000); + var owner = new CpuContext(memory, Generation.Gen5); + var ownerDone = new ManualResetEventSlim(); + var ownerAcquired = new ManualResetEventSlim(); + var release = new ManualResetEventSlim(); + var ownerThread = new Thread(() => + { + Assert.Equal(1, Acquire(owner, guard)); + ownerAcquired.Set(); + release.Wait(); + Release(owner, guard); + ownerDone.Set(); + }); + ownerThread.Start(); + Assert.True(ownerAcquired.Wait(TimeSpan.FromSeconds(10))); + + // The waiter's first read of the guard sees "pending"; the owner then releases before the waiter goes on. + var hooked = new ReadHookMemory(memory, guard, onRead: 1, () => + { + release.Set(); + Assert.True(ownerDone.Wait(TimeSpan.FromSeconds(10))); + }); + var waiter = new CpuContext(hooked, Generation.Gen5); + Assert.Equal(0, Acquire(waiter, guard)); + ownerThread.Join(); + var first = new byte[1]; + Assert.True(memory.TryRead(guard, first)); + Assert.Equal(1, first[0]); + } + + // After an abort the guard is free again and the next caller constructs. + [Fact] + public void AnAbortedConstructionIsHandedToTheNextCaller() + { + var guard = Base + 0x300; + var context = new CpuContext(new FakeCpuMemory(Base, 0x1000), Generation.Gen5); + Assert.Equal(1, Acquire(context, guard)); + context[CpuRegister.Rdi] = guard; + Assert.Equal(0, CxaGuardExports.CxaGuardAbort(context)); + Assert.Equal(1, Acquire(context, guard)); + Release(context, guard); + Assert.Equal(0, Acquire(context, guard)); + } +} From 7a0981220cf970c94a32c964ddf3f6ef18a65264 Mon Sep 17 00:00:00 2001 From: kuba Date: Tue, 17 Nov 2026 08:11:26 +0000 Subject: [PATCH 174/178] [GPU] Name the host or GPU write that covered a faulting guest range SHARPEMU_GPU_WRITE_RING=1 keeps the last 1 Mi writes of 16 bytes or more the host makes or encodes into guest memory for the GPU: every image texel piece EncodeTextureToGuest writes back (with the image's address, format, extent, tile mode, levels and piece), every store, fill, copy and writeback declared through NoteGuestMemoryWrite (with the transfer label or the draw/dispatch), and the host-side fills and copies. The fault dump's windows are looked up locally and handed to the GPU host through $TMPDIR/sharpemu-fault-ranges-.txt, which prints the intersecting entries once it sees the guest process gone. Transfer labels also carry the image's guest address. Diagnostic only, off by default; for the Demon's Souls load crash, where 1 KiB of RGBA8 texels landed in a freshly copied animation file. --- .../DirectExecutionBackend.Exceptions.cs | 12 +- src/SharpEmu.GpuHost/GpuHostMain.cs | 6 + src/SharpEmu.HLE/GpuWriteRing.cs | 216 ++++++++++++++++++ .../V2/MetalGpuWriteRanges.cs | 4 + .../SharpEmu.Gpu.Metal/V2/MetalImageCache.cs | 3 +- .../V2/MetalImageTransfer.cs | 15 ++ .../V2/MetalRenderHost.Profile.cs | 3 +- .../SharpEmu.Gpu.Metal/V2/MetalRenderHost.cs | 12 + .../HLE/GpuWriteRingTests.cs | 81 +++++++ 9 files changed, 347 insertions(+), 5 deletions(-) create mode 100644 src/SharpEmu.HLE/GpuWriteRing.cs create mode 100644 tests/SharpEmu.Libs.Tests/HLE/GpuWriteRingTests.cs diff --git a/src/SharpEmu.Core/Cpu/Native/DirectExecutionBackend.Exceptions.cs b/src/SharpEmu.Core/Cpu/Native/DirectExecutionBackend.Exceptions.cs index b52a2d5fa..34d76d6fd 100644 --- a/src/SharpEmu.Core/Cpu/Native/DirectExecutionBackend.Exceptions.cs +++ b/src/SharpEmu.Core/Cpu/Native/DirectExecutionBackend.Exceptions.cs @@ -1274,16 +1274,21 @@ private void DumpFaultExpressions(Dictionary registers) } var entries = spec.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries); - DumpFaultExpressionPass("now", entries, registers); + var ranges = new List<(ulong Start, ulong Size, string Label)>(); + DumpFaultExpressionPass("now", entries, registers, ranges); + // SHARPEMU_GPU_WRITE_RING=1: which recorded host/GPU writes covered the dumped bytes. + SharpEmu.HLE.GpuWriteRing.ReportFaultRanges(ranges); if (int.TryParse(Environment.GetEnvironmentVariable("SHARPEMU_FAULT_DUMP_REPEAT_MS"), out var repeatMs) && repeatMs > 0) { Thread.Sleep(Math.Min(repeatMs, 5000)); - DumpFaultExpressionPass($"after {repeatMs} ms", entries, registers); + DumpFaultExpressionPass($"after {repeatMs} ms", entries, registers, ranges: null); } } - private void DumpFaultExpressionPass(string pass, string[] entries, Dictionary registers) + private void DumpFaultExpressionPass( + string pass, string[] entries, Dictionary registers, + List<(ulong Start, ulong Size, string Label)>? ranges) { foreach (var entry in entries) { @@ -1307,6 +1312,7 @@ private void DumpFaultExpressionPass(string pass, string[] entries, Dictionary +/// The last 1 Mi writes (SHARPEMU_GPU_WRITE_RING_ENTRIES, a power of two) of 16 bytes or more that +/// the host made or encoded into guest memory on the GPU's behalf: image +/// texels written back (with the image's description), declared GPU stores, fills, copies, and +/// the host-side fills and copies. A guest fault over bytes that hold something the guest never +/// wrote asks this ring which of those writes covered them. +/// +/// Off unless SHARPEMU_GPU_WRITE_RING=1. A record is an interlocked add and a struct store; +/// the strings are references the caller already holds. Writes under 16 bytes (labels, write-data +/// dwords) are not kept: they are most of the traffic (Demon's Souls boot: ~18k writes a second in +/// all) and cannot be the multi-texel run this ring is for, so leaving them out keeps about a minute. +/// +/// The ring lives in whichever process encodes GPU work. In one process the fault dump queries it +/// directly. In the split, the guest process's fault dump writes the ranges it dumped to +/// (keyed by its pid) and the GPU host, once it sees that process +/// gone, prints the entries that intersect them () into the same +/// log. +/// +public static class GpuWriteRing +{ + private const ulong MinimumSize = 16; + private static readonly int Capacity = ReadCapacity(); + private const int MaxReportedPerRange = 64; + + private struct Entry + { + public long Sequence; + public long Ticks; + public ulong Address; + public ulong Size; + public ulong Serial; + public string? Kind; + public string? ProducerA; + public string? ProducerB; + } + + private static Entry[]? _entries; + private static Entry[] Entries => _entries ??= AllocateEntries(); + + private static Entry[] AllocateEntries() + { + var entries = new Entry[Capacity]; + Interlocked.CompareExchange(ref _entries, entries, null); + return _entries!; + } + + private static int ReadCapacity() + { + var text = Environment.GetEnvironmentVariable("SHARPEMU_GPU_WRITE_RING_ENTRIES"); + return int.TryParse(text, NumberStyles.Integer, CultureInfo.InvariantCulture, out var entries) && + entries >= 1024 && entries <= 1 << 24 && (entries & (entries - 1)) == 0 + ? entries + : 1 << 20; + } + private static long _sequence; + + /// True while writes are recorded. + public static bool Enabled { get; set; } = string.Equals( + Environment.GetEnvironmentVariable("SHARPEMU_GPU_WRITE_RING"), "1", StringComparison.Ordinal); + + /// How many writes have been recorded since startup. + public static long Recorded => Volatile.Read(ref _sequence); + + /// + /// Notes a write of [address, address + size). says what wrote it and + /// whether it is a GPU command encoded for later or a host store made now; the two producer + /// strings (either may be null) name the image or the draw, and are joined only when printed. + /// + public static void Record(ulong address, ulong size, ulong serial, string kind, string? producerA, string? producerB = null) + { + if (!Enabled || size < MinimumSize) + { + return; + } + + var sequence = Interlocked.Increment(ref _sequence); + ref var entry = ref Entries[(int)(sequence & (Capacity - 1))]; + // Sequence last: a reader that sees it sees the rest (or skips an entry being rewritten). + Volatile.Write(ref entry.Sequence, 0); + entry.Ticks = Stopwatch.GetTimestamp(); + entry.Address = address; + entry.Size = size; + entry.Serial = serial; + entry.Kind = kind; + entry.ProducerA = producerA; + entry.ProducerB = producerB; + Volatile.Write(ref entry.Sequence, sequence); + } + + /// + /// The recorded writes intersecting [start, end), newest first, at most + /// , each formatted on one line with its age at the time of the call. + /// + public static List Describe(ulong start, ulong end, int limit = MaxReportedPerRange) + { + var lines = new List(); + var newest = Volatile.Read(ref _sequence); + var now = Stopwatch.GetTimestamp(); + for (var sequence = newest; sequence > 0 && sequence > newest - Capacity && lines.Count < limit; sequence--) + { + ref var entry = ref Entries[(int)(sequence & (Capacity - 1))]; + if (Volatile.Read(ref entry.Sequence) != sequence) + { + continue; + } + + var entryEnd = entry.Address + entry.Size; + if (entryEnd <= start || entry.Address >= end) + { + continue; + } + + var ageMs = (now - entry.Ticks) * 1000.0 / Stopwatch.Frequency; + var producer = entry.ProducerB is null ? entry.ProducerA : $"{entry.ProducerA} {entry.ProducerB}"; + lines.Add( + $"#{sequence} age={ageMs.ToString("F1", CultureInfo.InvariantCulture)}ms " + + $"[0x{entry.Address:X16}, 0x{entryEnd:X16}) size=0x{entry.Size:X} serial={entry.Serial} " + + $"kind={entry.Kind} producer={producer ?? "?"}"); + } + + return lines; + } + + /// The file a guest process with this pid hands its fault ranges over in. + public static string FaultRangesPath(int processId) => + Path.Combine(Path.GetTempPath(), $"sharpemu-fault-ranges-{processId}.txt"); + + /// + /// Prints the entries intersecting each range here, and (with the ring on) leaves the ranges + /// for a GPU host process to answer: one "start size label" line per range. + /// + public static void ReportFaultRanges(IReadOnlyList<(ulong Start, ulong Size, string Label)> ranges) + { + if (!Enabled || ranges.Count == 0) + { + return; + } + + Print("local", ranges); + try + { + var text = new StringBuilder(); + foreach (var (start, size, label) in ranges) + { + text.Append(CultureInfo.InvariantCulture, $"{start:X} {size:X} {label}\n"); + } + + File.WriteAllText(FaultRangesPath(Environment.ProcessId), text.ToString()); + } + catch (Exception exception) + { + Console.Error.WriteLine($"[GPU-WRITE-RING][WARN] could not hand the fault ranges to the GPU host: {exception.Message}"); + } + } + + /// + /// In the GPU host, after its guest process exited: prints the + /// entries intersecting the ranges that process's fault dump left, then removes the file. + /// + public static void ReportFaultRangesOf(int processId) + { + if (!Enabled) + { + return; + } + + var path = FaultRangesPath(processId); + if (!File.Exists(path)) + { + Console.Error.WriteLine($"[GPU-WRITE-RING][INFO] guest process {processId} left no fault ranges; recorded={Recorded}."); + return; + } + + var ranges = new List<(ulong Start, ulong Size, string Label)>(); + foreach (var line in File.ReadAllLines(path)) + { + var parts = line.Split(' ', 3); + if (parts.Length >= 2 && + ulong.TryParse(parts[0], NumberStyles.HexNumber, CultureInfo.InvariantCulture, out var start) && + ulong.TryParse(parts[1], NumberStyles.HexNumber, CultureInfo.InvariantCulture, out var size)) + { + ranges.Add((start, size, parts.Length > 2 ? parts[2] : string.Empty)); + } + } + + Print($"gpu-host for pid {processId}", ranges); + try { File.Delete(path); } catch (IOException) { } + } + + private static void Print(string side, IReadOnlyList<(ulong Start, ulong Size, string Label)> ranges) + { + foreach (var (start, size, label) in ranges) + { + var lines = Describe(start, start + size); + Console.Error.WriteLine( + $"[GPU-WRITE-RING][INFO] {side}: {label} [0x{start:X16}, 0x{start + size:X16}) " + + $"writes={lines.Count}{(lines.Count == MaxReportedPerRange ? "+" : string.Empty)} recorded={Recorded}"); + foreach (var line in lines) + { + Console.Error.WriteLine($"[GPU-WRITE-RING][INFO] {line}"); + } + } + + Console.Error.Flush(); + } +} diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalGpuWriteRanges.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalGpuWriteRanges.cs index 1fcacaabf..74b9f170a 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalGpuWriteRanges.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalGpuWriteRanges.cs @@ -59,6 +59,10 @@ internal static class MetalGpuWriteOrigins public static readonly string[] Names = ["storage", "binding", "device_address", "fill", "copy", "writeback", "eop_label", "unbounded"]; + + // The same names as GpuWriteRing kinds: each one a GPU command encoded for later. + public static readonly string[] RingKinds = + ["gpu:storage", "gpu:binding", "gpu:device_address", "gpu:fill", "gpu:copy", "gpu:writeback", "gpu:eop_label", "gpu:unbounded"]; } /// diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.cs index 9ef9e0a2a..822662bcc 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.cs @@ -4027,7 +4027,8 @@ private static string ProfileLabel(string direction, in ImageDescription descrip $"{direction} format={description.PixelFormat} type={description.Type} " + $"extent={description.Extent.Width}x{description.Extent.Height}x{description.Extent.Depth} " + $"levels={description.Resources.Levels} layers={description.TransferLayers} " + - $"tile={description.TileMode} samples={description.Samples} bytes=0x{description.Data.Size:X}"; + $"tile={description.TileMode} samples={description.Samples} addr=0x{description.Data.Address:X} " + + $"bytes=0x{description.Data.Size:X}"; // Linear images the GPU wrote since the last end-of-pipe write. Linear is the layout a // guest CPU reads in place - a readback staging surface - so these are the GPU writes diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageTransfer.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageTransfer.cs index 060e2da39..3664011bd 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageTransfer.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageTransfer.cs @@ -863,6 +863,21 @@ public bool EncodeTextureToGuest(IMetalSubmissionContext context, in ImageDescri return false; } + if (SharpEmu.HLE.GpuWriteRing.Enabled) + { + // The guest bytes this piece stands for, whether the retile lands there or in a + // scratch the caller copies back: the image that owned them is what a clobber names. + SharpEmu.HLE.GpuWriteRing.Record( + description.Data.Address + guestBase, pieceSize, context.SubmissionSerial, "gpu:image-texels", + $"image addr=0x{description.Data.Address:X} bytes=0x{description.Data.Size:X} " + + $"format={description.PixelFormat} type={description.Type} " + + $"extent={description.Extent.Width}x{description.Extent.Height}x{description.Extent.Depth} " + + $"tile={description.TileMode} pitch={description.Pitch} levels={range.BaseLevel}+{range.LevelCount}/{description.Resources.Levels} " + + $"layers={range.BaseLayer}+{range.LayerCount} firstLevel={textureFirstLevel} " + + $"piece=+0x{guestBase:X}..+0x{guestBase + pieceSize:X} " + + $"dest={(destination.Buffer == 0 ? "?" : "window")}+0x{destination.Offset:X}"); + } + var plan = PlanFor(description); if (plan.DepthStencil) { diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Profile.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Profile.cs index 73f010986..5d6dcc27f 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Profile.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Profile.cs @@ -227,7 +227,8 @@ void IMetalSubmissionContext.ProfileEncoded(string label) // The label is read by the shader and pass profilers, and by the write guard and slot trap // that name the last transfer (LastTransferDescription is read only with the guard on). bool IMetalSubmissionContext.WantsEncodedLabels => - MetalShaderProfile.Enabled || PassProfileEnabled || _guard is not null || _slotTrap is not null; + MetalShaderProfile.Enabled || PassProfileEnabled || _guard is not null || _slotTrap is not null || + SharpEmu.HLE.GpuWriteRing.Enabled; /// The last image transfer, fill or copy encoded, for a diagnostic that has /// to name which one wrote a guest byte. diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.cs index 6860f2b5d..d6fc7ce7e 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.cs @@ -1421,6 +1421,15 @@ public void NoteGuestMemoryWriteBeyondOverlays(ulong address, ulong size, MetalG NoteLabelStagedReadsWrite(address, size); } + if (SharpEmu.HLE.GpuWriteRing.Enabled) + { + // Producer strings by reference: the transfer's label, or the draw/dispatch's kind and label. + var transfer = origin is MetalGpuWriteOrigin.Fill or MetalGpuWriteOrigin.Copy or MetalGpuWriteOrigin.ImageWriteback; + SharpEmu.HLE.GpuWriteRing.Record( + address, size, SubmissionSerial, MetalGpuWriteOrigins.RingKinds[(int)origin], + transfer ? _lastTransferLabel : _lastWorkKind, transfer ? null : _lastWorkLabel); + } + if (_guard is not null && size != 0) { // A fill, copy or writeback has just been encoded, so the last transfer label @@ -1769,6 +1778,7 @@ private void EncodeBlitFill(nint encoder, nint buffer, ulong offset, ulong size, private void WriteGuestPattern(ulong address, ulong size, uint value) { + SharpEmu.HLE.GpuWriteRing.Record(address, size, SubmissionSerial, "host-fill", "fill pattern"); if (_guard is null) { WriteGuestPatternCore(address, size, value); @@ -1948,6 +1958,8 @@ private void CopyGuestBytesOnHost(ulong destination, ulong source, ulong size) SupersedeKernelCopyChecks(destination, size); _cpOverlay.Forget(destination, size); _labelOverlay.Forget(destination, size); + SharpEmu.HLE.GpuWriteRing.Record(destination, size, SubmissionSerial, "host-copy", + SharpEmu.HLE.GpuWriteRing.Enabled ? $"from=0x{source:X16}" : null); if (_guard is null) { CopyGuestBytesOnHostCore(destination, source, size); diff --git a/tests/SharpEmu.Libs.Tests/HLE/GpuWriteRingTests.cs b/tests/SharpEmu.Libs.Tests/HLE/GpuWriteRingTests.cs new file mode 100644 index 000000000..af4eeee90 --- /dev/null +++ b/tests/SharpEmu.Libs.Tests/HLE/GpuWriteRingTests.cs @@ -0,0 +1,81 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using SharpEmu.HLE; +using Xunit; + +namespace SharpEmu.Libs.Tests.HLE; + +[Collection(nameof(GpuWriteRingTests))] +public sealed class GpuWriteRingTests +{ + // Addresses no other test records, so a shared static ring still answers only for these. + private const ulong Base = 0x7F12_3450_0000; + + [Fact] + public void ReportsOnlyTheWritesThatIntersectARangeNewestFirst() + { + var was = GpuWriteRing.Enabled; + GpuWriteRing.Enabled = true; + try + { + GpuWriteRing.Record(Base + 0x0800, 0x400, 7, "gpu:image-texels", "image addr=0x1 format=R8G8B8A8Unorm"); + GpuWriteRing.Record(Base + 0x2000, 0x100, 8, "host-copy", "from=0x2"); + GpuWriteRing.Record(Base + 0x0C00, 0x10, 9, "gpu:storage", "dispatch", "cs#1"); + + var lines = GpuWriteRing.Describe(Base + 0x0A00, Base + 0x0C01); + + Assert.Equal(2, lines.Count); + Assert.Contains("kind=gpu:storage producer=dispatch cs#1", lines[0]); + Assert.Contains("serial=7 kind=gpu:image-texels", lines[1]); + Assert.Empty(GpuWriteRing.Describe(Base + 0x0C10, Base + 0x2000)); + + // A label-sized write is not kept. + GpuWriteRing.Record(Base + 0x3000, 8, 10, "gpu:eop_label", null); + Assert.Empty(GpuWriteRing.Describe(Base + 0x3000, Base + 0x3008)); + } + finally + { + GpuWriteRing.Enabled = was; + } + } + + [Fact] + public void RecordsNothingWhileOff() + { + var was = GpuWriteRing.Enabled; + GpuWriteRing.Enabled = false; + try + { + GpuWriteRing.Record(Base + 0x9000, 0x400, 1, "gpu:copy", null); + Assert.Empty(GpuWriteRing.Describe(Base + 0x9000, Base + 0x9400)); + } + finally + { + GpuWriteRing.Enabled = was; + } + } + + [Fact] + public void FaultRangesLeftByOneProcessAreAnsweredAndRemovedByTheOther() + { + var was = GpuWriteRing.Enabled; + GpuWriteRing.Enabled = true; + var path = GpuWriteRing.FaultRangesPath(Environment.ProcessId); + try + { + GpuWriteRing.Record(Base + 0x5000, 0x400, 3, "gpu:image-texels", "image"); + GpuWriteRing.ReportFaultRanges([(Base + 0x4F00, 0x200UL, "e0a=[[rbp]]")]); + Assert.True(File.Exists(path)); + Assert.StartsWith($"{Base + 0x4F00:X} 200 e0a=[[rbp]]", File.ReadAllText(path)); + + GpuWriteRing.ReportFaultRangesOf(Environment.ProcessId); + Assert.False(File.Exists(path)); + } + finally + { + GpuWriteRing.Enabled = was; + File.Delete(path); + } + } +} From e0478697d4d855a1e5f4b8212458e4dc8570a7e6 Mon Sep 17 00:00:00 2001 From: kuba Date: Tue, 17 Nov 2026 08:40:54 +0000 Subject: [PATCH 175/178] [Core] Fault forensics: HLE write ring, backing alias report and find= byte search SHARPEMU_HLE_WRITE_RING=1 records file reads into guest memory (AMPR, read, pread/readv) with the file and offset, and the libc memcpy/memmove import with its source, into the write ring the fault dump prints. SHARPEMU_FAULT_ALIASES=1 prints the backing bytes each dumped window maps and every other guest range mapping them; a SHARPEMU_FAULT_DUMP label starting with find searches mapped backing bytes for the window's bytes and names every guest address holding them. --- .../DirectExecutionBackend.Exceptions.cs | 50 ++++ src/SharpEmu.HLE/GpuWriteRing.cs | 47 +++- .../GuestMemory/GuestBackingForensics.cs | 253 ++++++++++++++++++ .../GuestMemory/GuestSpaceOwner.cs | 4 + .../GuestMemory/SharedBackingViews.cs | 22 ++ src/SharpEmu.Libs/Ampr/AmprExports.cs | 1 + .../Kernel/KernelFileExtendedExports.cs | 4 + .../Kernel/KernelMemoryCompatExports.cs | 6 + .../HLE/GpuWriteRingTests.cs | 30 ++- .../HLE/GuestBackingForensicsTests.cs | 70 +++++ 10 files changed, 482 insertions(+), 5 deletions(-) create mode 100644 src/SharpEmu.HLE/GuestMemory/GuestBackingForensics.cs create mode 100644 tests/SharpEmu.Libs.Tests/HLE/GuestBackingForensicsTests.cs diff --git a/src/SharpEmu.Core/Cpu/Native/DirectExecutionBackend.Exceptions.cs b/src/SharpEmu.Core/Cpu/Native/DirectExecutionBackend.Exceptions.cs index 34d76d6fd..1d3a1333f 100644 --- a/src/SharpEmu.Core/Cpu/Native/DirectExecutionBackend.Exceptions.cs +++ b/src/SharpEmu.Core/Cpu/Native/DirectExecutionBackend.Exceptions.cs @@ -1265,6 +1265,12 @@ private void DumpPointerWindow(string name, ulong baseAddress, int size) // for example elem=[[rbp]-0x360]:0x60. SHARPEMU_FAULT_DUMP_REPEAT_MS= dumps the // same windows again after n ms, so bytes another thread is still writing show up // as a difference between the two passes. + // + // A label starting with "find" searches instead of dumping: the len bytes at expr are + // looked for in every mapped backing byte, and each other guest address holding them is + // printed (SHARPEMU_FAULT_FIND_ALL=1 also reads pages the host reports as not resident). + // SHARPEMU_FAULT_ALIASES=1 prints, for each dumped window, the backing bytes it maps and + // every other guest range mapping the same bytes. private void DumpFaultExpressions(Dictionary registers) { var spec = Environment.GetEnvironmentVariable("SHARPEMU_FAULT_DUMP"); @@ -1278,6 +1284,20 @@ private void DumpFaultExpressions(Dictionary registers) DumpFaultExpressionPass("now", entries, registers, ranges); // SHARPEMU_GPU_WRITE_RING=1: which recorded host/GPU writes covered the dumped bytes. SharpEmu.HLE.GpuWriteRing.ReportFaultRanges(ranges); + if (Environment.GetEnvironmentVariable("SHARPEMU_FAULT_ALIASES") == "1") + { + foreach (var (start, size, label) in ranges) + { + Console.Error.WriteLine($"[LOADER][INFO] fault-aliases {label} [0x{start:X16}, 0x{start + size:X16}):"); + foreach (var line in SharpEmu.HLE.GuestMemory.GuestBackingForensics.DescribeAliases(start, size)) + { + Console.Error.WriteLine($"[LOADER][INFO] {line}"); + } + } + + Console.Error.Flush(); + } + if (int.TryParse(Environment.GetEnvironmentVariable("SHARPEMU_FAULT_DUMP_REPEAT_MS"), out var repeatMs) && repeatMs > 0) { @@ -1311,12 +1331,42 @@ private void DumpFaultExpressionPass( continue; } + if (label.StartsWith("find", StringComparison.OrdinalIgnoreCase)) + { + if (ranges is not null) + { + FindFaultBytes($"fault-find {label}={expression}", address, (int)length); + } + + continue; + } + DumpPointerWindow($"fault-dump[{pass}] {label}={expression}", address, (int)length); ranges?.Add((address, length, $"{label}={expression}")); } Console.Error.Flush(); } + private void FindFaultBytes(string name, ulong address, int length) + { + var needle = new byte[length]; + if (!_cpuContext.Memory.TryRead(address, needle)) + { + Console.Error.WriteLine($"[LOADER][INFO] {name} @0x{address:X16}: "); + return; + } + + Console.Error.WriteLine( + $"[LOADER][INFO] {name} @0x{address:X16} len=0x{length:X} bytes={Convert.ToHexString(needle, 0, Math.Min(length, 64))}:"); + var scanAll = Environment.GetEnvironmentVariable("SHARPEMU_FAULT_FIND_ALL") == "1"; + foreach (var line in SharpEmu.HLE.GuestMemory.GuestBackingForensics.FindBytes(needle, scanAll: scanAll)) + { + Console.Error.WriteLine($"[LOADER][INFO] {line}"); + } + + Console.Error.Flush(); + } + internal static bool TryEvaluateFaultExpression( string text, ref int position, Dictionary registers, out ulong value) { diff --git a/src/SharpEmu.HLE/GpuWriteRing.cs b/src/SharpEmu.HLE/GpuWriteRing.cs index 8b6a2f38b..20eac35c9 100644 --- a/src/SharpEmu.HLE/GpuWriteRing.cs +++ b/src/SharpEmu.HLE/GpuWriteRing.cs @@ -25,6 +25,12 @@ namespace SharpEmu.HLE; /// (keyed by its pid) and the GPU host, once it sees that process /// gone, prints the entries that intersect them () into the same /// log. +/// +/// SHARPEMU_HLE_WRITE_RING=1 records the guest process's own bulk HLE writes into the same +/// ring (): file reads into guest memory (AMPR, read, pread) with the file +/// and its offset, and the libc memcpy/memmove import with its source. Those are the host writes a +/// fault over foreign bytes has to tell apart from GPU work, and the guest process's fault dump +/// prints them directly. /// public static class GpuWriteRing { @@ -39,6 +45,8 @@ private struct Entry public ulong Address; public ulong Size; public ulong Serial; + public ulong Source; + public int Thread; public string? Kind; public string? ProducerA; public string? ProducerB; @@ -68,6 +76,10 @@ private static int ReadCapacity() public static bool Enabled { get; set; } = string.Equals( Environment.GetEnvironmentVariable("SHARPEMU_GPU_WRITE_RING"), "1", StringComparison.Ordinal); + /// True while the guest process's bulk HLE writes are recorded (). + public static bool HleEnabled { get; set; } = string.Equals( + Environment.GetEnvironmentVariable("SHARPEMU_HLE_WRITE_RING"), "1", StringComparison.Ordinal); + /// How many writes have been recorded since startup. public static long Recorded => Volatile.Read(ref _sequence); @@ -83,6 +95,26 @@ public static void Record(ulong address, ulong size, ulong serial, string kind, return; } + Store(address, size, serial, source: 0, kind, producerA, producerB); + } + + /// + /// Notes an HLE write of [address, address + size) made by the guest process itself: + /// is the guest source address of a copy or the file offset of a + /// read, and the file read (null for a copy). + /// + public static void RecordHle(ulong address, ulong size, ulong source, string kind, string? producer) + { + if (!HleEnabled || size < MinimumSize) + { + return; + } + + Store(address, size, serial: 0, source, kind, producer, producerB: null); + } + + private static void Store(ulong address, ulong size, ulong serial, ulong source, string kind, string? producerA, string? producerB) + { var sequence = Interlocked.Increment(ref _sequence); ref var entry = ref Entries[(int)(sequence & (Capacity - 1))]; // Sequence last: a reader that sees it sees the rest (or skips an entry being rewritten). @@ -91,6 +123,8 @@ public static void Record(ulong address, ulong size, ulong serial, string kind, entry.Address = address; entry.Size = size; entry.Serial = serial; + entry.Source = source; + entry.Thread = Environment.CurrentManagedThreadId; entry.Kind = kind; entry.ProducerA = producerA; entry.ProducerB = producerB; @@ -125,7 +159,7 @@ public static List Describe(ulong start, ulong end, int limit = MaxRepor lines.Add( $"#{sequence} age={ageMs.ToString("F1", CultureInfo.InvariantCulture)}ms " + $"[0x{entry.Address:X16}, 0x{entryEnd:X16}) size=0x{entry.Size:X} serial={entry.Serial} " + - $"kind={entry.Kind} producer={producer ?? "?"}"); + $"src=0x{entry.Source:X} tid={entry.Thread} kind={entry.Kind} producer={producer ?? "?"}"); } return lines; @@ -136,17 +170,22 @@ public static string FaultRangesPath(int processId) => Path.Combine(Path.GetTempPath(), $"sharpemu-fault-ranges-{processId}.txt"); /// - /// Prints the entries intersecting each range here, and (with the ring on) leaves the ranges - /// for a GPU host process to answer: one "start size label" line per range. + /// Prints the entries intersecting each range here, and (with the GPU ring on) leaves the + /// ranges for a GPU host process to answer: one "start size label" line per range. /// public static void ReportFaultRanges(IReadOnlyList<(ulong Start, ulong Size, string Label)> ranges) { - if (!Enabled || ranges.Count == 0) + if ((!Enabled && !HleEnabled) || ranges.Count == 0) { return; } Print("local", ranges); + if (!Enabled) + { + return; + } + try { var text = new StringBuilder(); diff --git a/src/SharpEmu.HLE/GuestMemory/GuestBackingForensics.cs b/src/SharpEmu.HLE/GuestMemory/GuestBackingForensics.cs new file mode 100644 index 000000000..61edf0b00 --- /dev/null +++ b/src/SharpEmu.HLE/GuestMemory/GuestBackingForensics.cs @@ -0,0 +1,253 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using System.Globalization; +using System.Runtime.InteropServices; + +namespace SharpEmu.HLE.GuestMemory; + +/// +/// Fault-time forensics over the shared guest backing, for the fault dump (SHARPEMU_FAULT_DUMP): +/// which backing bytes a guest range maps and which other guest ranges map the same bytes +/// (), and where else in mapped guest memory a run +/// of bytes appears (). Read only: it takes +/// a copy of the view records and reads the canonical alias, and changes nothing. +/// +public static unsafe class GuestBackingForensics +{ + private static SharedBackingViews? _views; + + // The newest backing views constructed in this process: the guest's, in a running game. + internal static void Register(SharedBackingViews views) => Volatile.Write(ref _views, views); + + /// + /// For each view the guest range [address, address + size) lies in: its backing bytes, and + /// every other view that maps any of those same backing bytes. + /// + public static List DescribeAliases(ulong address, ulong size, int limit = 32) + { + if (Volatile.Read(ref _views) is not { } views || !views.TrySnapshotViews(out var records)) + { + return ["no backing views to inspect"]; + } + + return DescribeAliases(records, address, size, limit); + } + + internal static List DescribeAliases(IReadOnlyList records, ulong address, ulong size, int limit) + { + var lines = new List(); + var end = address + size; + foreach (var view in records) + { + if (view.Address + view.Size <= address || view.Address >= end) + { + continue; + } + + var from = Math.Max(address, view.Address); + var to = Math.Min(end, view.Address + view.Size); + var backingStart = view.Offset + (from - view.Address); + var backingEnd = backingStart + (to - from); + lines.Add( + $"guest [0x{from:X16}, 0x{to:X16}) = backing [0x{backingStart:X}, 0x{backingEnd:X}) " + + $"in view guest=0x{view.Address:X16} size=0x{view.Size:X} offset=0x{view.Offset:X} prot={view.Protection}"); + var others = 0; + foreach (var other in records) + { + if (other.Address == view.Address || + other.Offset + other.Size <= backingStart || other.Offset >= backingEnd) + { + continue; + } + + var shared = Math.Max(backingStart, other.Offset); + var sharedEnd = Math.Min(backingEnd, other.Offset + other.Size); + lines.Add( + $" ALIAS backing [0x{shared:X}, 0x{sharedEnd:X}) is also guest " + + $"[0x{other.Address + (shared - other.Offset):X16}, 0x{other.Address + (sharedEnd - other.Offset):X16}) " + + $"in view guest=0x{other.Address:X16} size=0x{other.Size:X} offset=0x{other.Offset:X} prot={other.Protection}"); + if (++others >= limit) + { + lines.Add(" ALIAS list cut short"); + break; + } + } + + if (others == 0) + { + lines.Add(" no other view maps these backing bytes"); + } + } + + if (lines.Count == 0) + { + lines.Add($"guest [0x{address:X16}, 0x{end:X16}) is in no backing view"); + } + + return lines; + } + + /// + /// Every place in the backing bytes some view maps that holds , as + /// "backing offset → each guest address mapping it", newest view order. Pages the host reports + /// as not resident are skipped (they cannot hold bytes anyone wrote) unless + /// ; the last line says how much was scanned and skipped. + /// + public static List FindBytes(ReadOnlySpan needle, int limit = 32, bool scanAll = false) + { + if (Volatile.Read(ref _views) is not { } views || !views.TrySnapshotViews(out var records) || + views.AliasBase == 0) + { + return ["no backing views to search"]; + } + + return FindBytes(records, (byte*)views.AliasBase, views.Size, needle, limit, + scanAll || OperatingSystem.IsWindows() ? null : IsResidentPosix); + } + + // residency(start, length, pageSize, vector) fills one byte per page, nonzero when resident; + // false when it cannot tell, and the range is then scanned anyway. + internal delegate bool ResidencyQuery(byte* start, ulong length, ulong pageSize, byte[] vector); + + internal static List FindBytes( + IReadOnlyList records, byte* alias, ulong backingSize, ReadOnlySpan needle, int limit, + ResidencyQuery? residency) + { + var lines = new List(); + if (needle.IsEmpty) + { + return ["empty needle"]; + } + + // The backing bytes some view maps, merged. + var spans = new List<(ulong Start, ulong End)>(); + foreach (var view in records) + { + var start = Math.Min(view.Offset, backingSize); + var end = Math.Min(view.Offset + view.Size, backingSize); + if (end > start) + { + spans.Add((start, end)); + } + } + + spans.Sort((a, b) => a.Start.CompareTo(b.Start)); + var merged = new List<(ulong Start, ulong End)>(); + foreach (var span in spans) + { + if (merged.Count > 0 && span.Start <= merged[^1].End) + { + merged[^1] = (merged[^1].Start, Math.Max(merged[^1].End, span.End)); + } + else + { + merged.Add(span); + } + } + + var pageSize = (ulong)Math.Max(Environment.SystemPageSize, 4096); + const ulong Batch = 256UL * 1024 * 1024; + var vector = residency is null ? [] : new byte[Batch / pageSize + 2]; + ulong scanned = 0, skipped = 0, hits = 0; + var overlap = (ulong)needle.Length - 1; + foreach (var (spanStart, spanEnd) in merged) + { + for (var batchStart = spanStart; batchStart < spanEnd; batchStart += Batch) + { + var batchEnd = Math.Min(spanEnd, batchStart + Batch); + var runs = new List<(ulong Start, ulong End)>(); + var pageStart = batchStart / pageSize * pageSize; + if (residency is not null && + residency(alias + pageStart, batchEnd - pageStart, pageSize, vector)) + { + for (var page = pageStart; page < batchEnd; page += pageSize) + { + var index = (int)((page - pageStart) / pageSize); + var from = Math.Max(page, batchStart); + var to = Math.Min(page + pageSize, batchEnd); + if (vector[index] == 0) + { + skipped += to - from; + } + else if (runs.Count > 0 && runs[^1].End == from) + { + runs[^1] = (runs[^1].Start, to); + } + else + { + runs.Add((from, to)); + } + } + } + else + { + runs.Add((batchStart, batchEnd)); + } + + foreach (var (runStart, runEnd) in runs) + { + // A match may start in this run and end in the resident bytes after it. + var scanEnd = Math.Min(spanEnd, runEnd + overlap); + var cursor = runStart; + while (cursor + (ulong)needle.Length <= scanEnd && lines.Count < limit) + { + var window = new ReadOnlySpan(alias + cursor, (int)Math.Min(scanEnd - cursor, int.MaxValue)); + var found = window.IndexOf(needle); + if (found < 0 || cursor + (ulong)found >= runEnd) + { + break; + } + + var offset = cursor + (ulong)found; + hits++; + lines.Add(DescribeHit(records, offset)); + cursor = offset + 1; + } + + scanned += runEnd - runStart; + } + } + } + + lines.Add( + string.Create(CultureInfo.InvariantCulture, + $"searched {needle.Length} bytes: hits={hits}{(lines.Count >= limit ? "+" : string.Empty)} " + + $"scanned_mb={scanned / 1048576.0:F1} skipped_not_resident_mb={skipped / 1048576.0:F1} views={records.Count}")); + return lines; + } + + private static string DescribeHit(IReadOnlyList records, ulong offset) + { + var text = new System.Text.StringBuilder($"backing 0x{offset:X} ="); + foreach (var view in records) + { + if (offset >= view.Offset && offset < view.Offset + view.Size) + { + text.Append(CultureInfo.InvariantCulture, + $" guest 0x{view.Address + (offset - view.Offset):X16} (view guest=0x{view.Address:X16} size=0x{view.Size:X} offset=0x{view.Offset:X})"); + } + } + + return text.ToString(); + } + + [DllImport("libc", EntryPoint = "mincore", SetLastError = true)] + private static extern int MinCore(void* address, nuint length, byte* vector); + + private static bool IsResidentPosix(byte* start, ulong length, ulong pageSize, byte[] vector) + { + Array.Clear(vector); + try + { + fixed (byte* output = vector) + { + return MinCore(start, (nuint)length, output) == 0; + } + } + catch (Exception exception) when (exception is DllNotFoundException or EntryPointNotFoundException) + { + return false; + } + } +} diff --git a/src/SharpEmu.HLE/GuestMemory/GuestSpaceOwner.cs b/src/SharpEmu.HLE/GuestMemory/GuestSpaceOwner.cs index 74bc614cf..a529b0965 100644 --- a/src/SharpEmu.HLE/GuestMemory/GuestSpaceOwner.cs +++ b/src/SharpEmu.HLE/GuestMemory/GuestSpaceOwner.cs @@ -57,6 +57,10 @@ public GuestSpaceOwner(IHostViewMemory host, ulong backingSize, bool preReserveG ? $"Could not allocate {megabytes} MB for guest direct memory. Windows requires this amount of available system commit. Close other applications or increase the paging file size." : $"Could not allocate {megabytes} MB for guest direct memory."); } + else + { + GuestBackingForensics.Register(_views); + } } public ulong Granularity { get; } diff --git a/src/SharpEmu.HLE/GuestMemory/SharedBackingViews.cs b/src/SharpEmu.HLE/GuestMemory/SharedBackingViews.cs index 92b6aa78e..a40178a1b 100644 --- a/src/SharpEmu.HLE/GuestMemory/SharedBackingViews.cs +++ b/src/SharpEmu.HLE/GuestMemory/SharedBackingViews.cs @@ -581,6 +581,28 @@ private void CopyCanonicalAliasChunk(ulong source, ulong destination, int bytes, finally { HostBackingObject.EndManagedWrite(interval, succeeded); } } + // Fault forensics (GuestBackingForensics): a copy of every view record. A fault dump may run + // while another thread holds the lock, so it waits a second at most and then gives up. + internal bool TrySnapshotViews(out ViewRecord[] records) + { + records = []; + if (!Monitor.TryEnter(_lock, TimeSpan.FromSeconds(1))) + { + return false; + } + + try + { + records = new ViewRecord[_views.Count]; + _views.Values.CopyTo(records, 0); + return true; + } + finally + { + Monitor.Exit(_lock); + } + } + // The lock-free single-view read only; false (with nothing read) for anything else. public bool TryReadSingleView(ulong address, Span data) { diff --git a/src/SharpEmu.Libs/Ampr/AmprExports.cs b/src/SharpEmu.Libs/Ampr/AmprExports.cs index 4b56a731b..59507fe9d 100644 --- a/src/SharpEmu.Libs/Ampr/AmprExports.cs +++ b/src/SharpEmu.Libs/Ampr/AmprExports.cs @@ -1236,6 +1236,7 @@ private static int CompleteReadFileRecord(CpuContext ctx, ulong commandBuffer, R var result = TryReadFileToGuestMemory(ctx, hostPath, fileOffset, destination, size, out var bytesRead); SharpEmu.HLE.GuestLoadProgress.NoteAmprRead((long)bytesRead); + SharpEmu.HLE.GpuWriteRing.RecordHle(destination, bytesRead, fileOffset, "hle:ampr-read", hostPath); TraceAmprRead(ctx, commandBuffer, fileId, destination, size, fileOffset, bytesRead, hostPath, result); if (result != (int)OrbisGen2Result.ORBIS_GEN2_OK) { diff --git a/src/SharpEmu.Libs/Kernel/KernelFileExtendedExports.cs b/src/SharpEmu.Libs/Kernel/KernelFileExtendedExports.cs index 4a6fc314f..c9d8c70c9 100644 --- a/src/SharpEmu.Libs/Kernel/KernelFileExtendedExports.cs +++ b/src/SharpEmu.Libs/Kernel/KernelFileExtendedExports.cs @@ -149,6 +149,10 @@ private static int KernelPreadCoreInner(CpuContext ctx) } SharpEmu.HLE.GuestLoadProgress.NoteFileRead(read); + if (read > 0 && SharpEmu.HLE.GpuWriteRing.HleEnabled) + { + SharpEmu.HLE.GpuWriteRing.RecordHle(bufferAddress, (ulong)read, unchecked((ulong)offset), "hle:pread", OpenFileName(stream)); + } if (read > 0 && buffer is not null && !ctx.Memory.TryWrite(bufferAddress, buffer.AsSpan(0, read))) { diff --git a/src/SharpEmu.Libs/Kernel/KernelMemoryCompatExports.cs b/src/SharpEmu.Libs/Kernel/KernelMemoryCompatExports.cs index 4285fba33..ee74c3cd9 100644 --- a/src/SharpEmu.Libs/Kernel/KernelMemoryCompatExports.cs +++ b/src/SharpEmu.Libs/Kernel/KernelMemoryCompatExports.cs @@ -1235,6 +1235,7 @@ public static int Memcpy(CpuContext ctx) return (int)OrbisGen2Result.ORBIS_GEN2_ERROR_INVALID_ARGUMENT; } + SharpEmu.HLE.GpuWriteRing.RecordHle(destination, (ulong)count, source, "hle:memcpy", null); if (count > 0 && !ctx.Memory.TryCopy(destination, source, (ulong)count)) { var payload = GC.AllocateUninitializedArray(count); @@ -3008,6 +3009,11 @@ private static int KernelReadUnderscoreInner(CpuContext ctx) } } SharpEmu.HLE.GuestLoadProgress.NoteFileRead(read); + if (read > 0 && SharpEmu.HLE.GpuWriteRing.HleEnabled) + { + SharpEmu.HLE.GpuWriteRing.RecordHle(bufferAddress, (ulong)read, unchecked((ulong)positionBefore), "hle:read", OpenFileName(stream)); + } + if (read > 0 && buffer is not null && !ctx.Memory.TryWrite(bufferAddress, buffer.AsSpan(0, read))) { return (int)OrbisGen2Result.ORBIS_GEN2_ERROR_MEMORY_FAULT; diff --git a/tests/SharpEmu.Libs.Tests/HLE/GpuWriteRingTests.cs b/tests/SharpEmu.Libs.Tests/HLE/GpuWriteRingTests.cs index af4eeee90..689833c5d 100644 --- a/tests/SharpEmu.Libs.Tests/HLE/GpuWriteRingTests.cs +++ b/tests/SharpEmu.Libs.Tests/HLE/GpuWriteRingTests.cs @@ -27,7 +27,8 @@ public void ReportsOnlyTheWritesThatIntersectARangeNewestFirst() Assert.Equal(2, lines.Count); Assert.Contains("kind=gpu:storage producer=dispatch cs#1", lines[0]); - Assert.Contains("serial=7 kind=gpu:image-texels", lines[1]); + Assert.Contains("serial=7 src=0x0", lines[1]); + Assert.Contains("kind=gpu:image-texels", lines[1]); Assert.Empty(GpuWriteRing.Describe(Base + 0x0C10, Base + 0x2000)); // A label-sized write is not kept. @@ -40,6 +41,33 @@ public void ReportsOnlyTheWritesThatIntersectARangeNewestFirst() } } + [Fact] + public void HleWritesNameTheirSourceAndThreadAndFollowTheirOwnSwitch() + { + var was = GpuWriteRing.HleEnabled; + try + { + GpuWriteRing.HleEnabled = false; + GpuWriteRing.RecordHle(Base + 0xB000, 0x400, 0x1234, "hle:memcpy", null); + Assert.Empty(GpuWriteRing.Describe(Base + 0xB000, Base + 0xB400)); + + GpuWriteRing.HleEnabled = true; + GpuWriteRing.RecordHle(Base + 0xB000, 0x400, 0x1234, "hle:memcpy", null); + GpuWriteRing.RecordHle(Base + 0xB400, 0x8000, 0x20000, "hle:ampr-read", "/game/data.bin"); + + var lines = GpuWriteRing.Describe(Base + 0xB3F0, Base + 0xB410); + + Assert.Equal(2, lines.Count); + Assert.Contains("src=0x20000", lines[0]); + Assert.Contains("kind=hle:ampr-read producer=/game/data.bin", lines[0]); + Assert.Contains($"src=0x1234 tid={Environment.CurrentManagedThreadId} kind=hle:memcpy", lines[1]); + } + finally + { + GpuWriteRing.HleEnabled = was; + } + } + [Fact] public void RecordsNothingWhileOff() { diff --git a/tests/SharpEmu.Libs.Tests/HLE/GuestBackingForensicsTests.cs b/tests/SharpEmu.Libs.Tests/HLE/GuestBackingForensicsTests.cs new file mode 100644 index 000000000..a58c6adc1 --- /dev/null +++ b/tests/SharpEmu.Libs.Tests/HLE/GuestBackingForensicsTests.cs @@ -0,0 +1,70 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using SharpEmu.HLE.GuestMemory; +using SharpEmu.HLE.Host; +using Xunit; + +namespace SharpEmu.Libs.Tests.HLE; + +public sealed unsafe class GuestBackingForensicsTests +{ + private static readonly ViewRecord[] Views = + [ + new(0x7000_0000, 0x10000, 0x0, HostPageProtection.ReadWrite), + // Maps backing [0x8000, 0x18000): its first half is the same bytes as the second half above. + new(0x9000_0000, 0x10000, 0x8000, HostPageProtection.ReadWrite), + new(0xA000_0000, 0x4000, 0x40000, HostPageProtection.ReadOnly), + ]; + + [Fact] + public void AWindowListsTheOtherGuestRangesMappingTheSameBackingBytes() + { + var lines = GuestBackingForensics.DescribeAliases(Views, 0x7000_8800, 0x400, limit: 8); + + Assert.Equal(2, lines.Count); + Assert.Contains("= backing [0x8800, 0x8C00)", lines[0]); + Assert.Contains("ALIAS backing [0x8800, 0x8C00) is also guest [0x0000000090000800, 0x0000000090000C00)", lines[1]); + + var alone = GuestBackingForensics.DescribeAliases(Views, 0xA000_0100, 0x40, limit: 8); + Assert.Contains("no other view maps these backing bytes", alone[1]); + Assert.Contains("is in no backing view", GuestBackingForensics.DescribeAliases(Views, 0x1000, 0x10, 8)[0]); + } + + [Fact] + public void FindBytesNamesEveryGuestAddressOfEachHitAndSkipsPagesThatAreNotResident() + { + var backing = new byte[0x50000]; + byte[] needle = [0xDE, 0xAD, 0xBE, 0xEF, 0x01, 0x02, 0x03, 0x04]; + needle.CopyTo(backing, 0xC000); // mapped twice: 0x7000C000 and 0x90004000 + needle.CopyTo(backing, 0x40010); // 0xA0000010 + needle.CopyTo(backing, 0x30000); // no view maps it + + fixed (byte* alias = backing) + { + var all = GuestBackingForensics.FindBytes(Views, alias, (ulong)backing.Length, needle, 32, residency: null); + Assert.Equal(3, all.Count); + Assert.Contains("backing 0xC000 = guest 0x000000007000C000", all[0]); + Assert.Contains("guest 0x0000000090004000", all[0]); + Assert.Contains("backing 0x40010 = guest 0x00000000A0000010", all[1]); + Assert.Contains("hits=2", all[2]); + + // Only the page holding backing 0x40000.. counts as resident. + var aliasAddress = (nint)alias; + var resident = GuestBackingForensics.FindBytes(Views, alias, (ulong)backing.Length, needle, 32, + (start, length, pageSize, vector) => + { + for (ulong page = 0; page * pageSize < length; page++) + { + var offset = (ulong)((nint)start - aliasAddress) + page * pageSize; + vector[page] = offset == 0x40000 ? (byte)1 : (byte)0; + } + + return true; + }); + Assert.Equal(2, resident.Count); + Assert.Contains("backing 0x40010", resident[0]); + Assert.Contains("hits=1", resident[1]); + } + } +} From 59c894d8d538f455ef377b778df034a1c55f18dc Mon Sep 17 00:00:00 2001 From: kuba Date: Tue, 17 Nov 2026 12:00:26 +0000 Subject: [PATCH 176/178] [Core] Fault forensics: writes by backing, saved buffers, and samples around a read The write ring records the backing offset an address mapped to when it was written, so a fault's ranges are looked up by backing as well as by address in both processes, and a recorded copy into a range adds its source to the search. SHARPEMU_FAULT_DUMP labels starting with save write the bytes to SHARPEMU_FAULT_SAVE_DIR; find labels add the other holders of the bytes to the ranges. SHARPEMU_FAULT_RING_PRODUCER adds the ranges of writes whose producer contains a text (a file name), SHARPEMU_WRITE_RING_TAIL prints the newest records, and SHARPEMU_HLE_WRITE_RING_MIN keeps the HLE ring to large writes, since recording every small copy hid the race it was built to find. An AMPR read records its begin, and the 16 bytes at +0x20000 of its destination as the fill starts and ends. In Demon's Souls that showed a render target's texels already under the file's bytes when the read finished. The switches are documented in docs/macos/configuration.md. --- docs/macos/configuration.md | 17 ++ .../DirectExecutionBackend.Exceptions.cs | 71 ++++- src/SharpEmu.HLE/GpuWriteRing.cs | 251 ++++++++++++++++-- .../GuestMemory/GuestBackingForensics.cs | 37 ++- src/SharpEmu.Libs/Ampr/AmprExports.cs | 13 +- .../Kernel/KernelMemoryCompatExports.cs | 2 +- .../SharpEmu.Gpu.Metal/V2/MetalGuestMemory.cs | 6 + .../HLE/GpuWriteRingTests.cs | 54 ++++ 8 files changed, 422 insertions(+), 29 deletions(-) diff --git a/docs/macos/configuration.md b/docs/macos/configuration.md index ce69cdb38..98c053ff8 100644 --- a/docs/macos/configuration.md +++ b/docs/macos/configuration.md @@ -139,6 +139,23 @@ undoes an optimization to isolate a miscompile: | `SHARPEMU_FRAME_TIMES=` | Writes one timestamp line per guest flip. `1` writes `frame-times-.txt` under the logs folder. | | `SHARPEMU_INPUT_FILE=` | Test automation: the file lists the keys held right now; it is polled every 30 ms and works without window focus. | +### Finding what overwrote guest memory + +These cost nothing until the game faults. When it does, the crash report names +the writes that covered the bytes you asked about. + +| Variable | Effect | +| --- | --- | +| `SHARPEMU_FAULT_DUMP=