Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
100 changes: 84 additions & 16 deletions src/SharpEmu.GpuSplit/RemoteGuestAddressSpace.cs
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,12 @@ internal sealed unsafe class RemoteGuestAddressSpace :
private readonly IInterestSummary _summary;
private int _missReports;
private long _misses;
private long _suppressedMissReports;
private long _nullBaseMisses;
private long _lineFillMisses;
private long _nextMissSummary = FirstMissSummary;
// After the report cap, one summary line at 64 misses, then each time the count has grown fourfold.
private const long FirstMissSummary = 64;

public RemoteGuestAddressSpace(HostBackingObject mirror, GuestMirrorTranslator translator, GuestReplica? replica,
ulong chunkBytes, ulong objectBytes, IProtectionRequests protections, IInterestSummary summary)
Expand All @@ -89,6 +95,18 @@ public RemoteGuestAddressSpace(HostBackingObject mirror, GuestMirrorTranslator t
/// <summary>Accesses to memory the backing does not hold.</summary>
public long PrivateMemoryMisses => Interlocked.Read(ref _misses);

/// <summary>Misses of reads through a null resource base (GuestReadContext.NullBase): read as zero by design, not reported one by one.</summary>
public long NullBaseMisses => Interlocked.Read(ref _nullBaseMisses);

/// <summary>Word line fills that found no memory: not reported themselves, but with the word read that follows them.</summary>
public long LineFillMisses => Interlocked.Read(ref _lineFillMisses);

/// <summary>Misses past the report cap, counted instead of printed.</summary>
public long SuppressedMissReports => Interlocked.Read(ref _suppressedMissReports);

/// <summary>Where miss reports go (tests capture them).</summary>
internal Action<string> ReportLine { get; set; } = static line => Console.Error.WriteLine(line);

// ---- ICpuMemory ----

public bool TryRead(ulong virtualAddress, Span<byte> destination)
Expand Down Expand Up @@ -524,27 +542,77 @@ private bool Copy(ulong address, ulong size, byte* bytes, bool toGuest)
return true;
}

// One event per failed request: a word line fill that misses (GuestReadContext.LineFill) is not reported itself but
// with the word read that follows it, and names who asked (GuestReadContext.Describe). A miss through a null
// resource base is read as zero by design (GuestReadContext.NullBase): counted, its first one named once.
private void NoteMiss(ulong address, ulong size, string access, ulong? failedAddress = null)
{
Interlocked.Increment(ref _misses);
if (Interlocked.Increment(ref _missReports) <= MaxMissReports)
if (GuestReadContext.LineFill)
{
Interlocked.Increment(ref _lineFillMisses);
GuestReadContext.NoteLineMiss(address, size);
return;
}

var misses = Interlocked.Increment(ref _misses);
var line = GuestReadContext.TakeLineMiss(address, size, out var lineAddress, out var lineSize)
? $" (its word line 0x{lineAddress:X16}+0x{lineSize:X} failed first)" : "";
if (GuestReadContext.NullBase)
{
Console.Error.WriteLine(
$"[GPU-SPLIT][WARN] GPU {access} of guest 0x{address:X16}+0x{size:X} failed: not in the shared backing " +
"(unmapped, private, or outside the mirrored range).");
if (Environment.GetEnvironmentVariable("SHARPEMU_SPLIT_MISS_DETAILS") == "1")
if (Interlocked.Increment(ref _nullBaseMisses) == 1)
{
var failed = failedAddress ?? address;
var snapshot = _translator.Snapshot();
var before = snapshot.LastOrDefault(entry => entry.Address <= failed);
var after = snapshot.FirstOrDefault(entry => entry.Address > failed);
var sequence = _translator.ChangeSequence;
Console.Error.WriteLine($"[GPU-SPLIT][MISS] first=0x{failed:X16} generation={_translator.MappingGeneration} " +
$"complete={_translator.IsComplete} mirror_bytes=0x{_mirrorBytes:X} changes={sequence} " +
$"before=[0x{before.Address:X16},0x{before.End:X16}) offset=0x{before.Offset:X} " +
$"after=[0x{after.Address:X16},0x{after.End:X16}) offset=0x{after.Offset:X}");
Console.Error.WriteLine($"[GPU-SPLIT][MISS-CHANGE] {DescribeViewChanges(failed, 16)}");
ReportLine(
$"[GPU-SPLIT][INFO] GPU {access} of guest 0x{address:X16}+0x{size:X} through a null resource base found no memory{line}; " +
$"it reads as zero by design, later ones are counted (null_base=): {GuestReadContext.Describe()}.");
}

NoteMissSummary(misses);
return;
}

var report = Interlocked.Increment(ref _missReports);
if (report > MaxMissReports)
{
Interlocked.Increment(ref _suppressedMissReports);
NoteMissSummary(misses);
return;
}

ReportLine(
$"[GPU-SPLIT][WARN] GPU {access} of guest 0x{address:X16}+0x{size:X} failed: not in the shared backing " +
$"(unmapped, private, or outside the mirrored range){line}. {GuestReadContext.Describe()}" +
(report == MaxMissReports ? $" (report {MaxMissReports} of {MaxMissReports}; later misses are counted in summaries)" : ""));
if (report == 1)
{
ReportLine($"[GPU-SPLIT][MISS-STACK] {Environment.StackTrace}");
}

if (Environment.GetEnvironmentVariable("SHARPEMU_SPLIT_MISS_DETAILS") == "1")
{
var failed = failedAddress ?? address;
var snapshot = _translator.Snapshot();
var before = snapshot.LastOrDefault(entry => entry.Address <= failed);
var after = snapshot.FirstOrDefault(entry => entry.Address > failed);
var sequence = _translator.ChangeSequence;
ReportLine($"[GPU-SPLIT][MISS] first=0x{failed:X16} generation={_translator.MappingGeneration} " +
$"complete={_translator.IsComplete} mirror_bytes=0x{_mirrorBytes:X} changes={sequence} " +
$"before=[0x{before.Address:X16},0x{before.End:X16}) offset=0x{before.Offset:X} " +
$"after=[0x{after.Address:X16},0x{after.End:X16}) offset=0x{after.Offset:X}");
ReportLine($"[GPU-SPLIT][MISS-CHANGE] {DescribeViewChanges(failed, 16)}");
}
}

// After the report cap: one line at 64 misses and each time the count has grown fourfold since.
private void NoteMissSummary(long misses)
{
var next = Interlocked.Read(ref _nextMissSummary);
if (misses < next || Interlocked.CompareExchange(ref _nextMissSummary, next * 4, next) != next)
{
return;
}

ReportLine($"[GPU-SPLIT][INFO] GPU accesses outside the shared backing: misses={misses} " +
$"reported={Math.Min(Volatile.Read(ref _missReports), MaxMissReports)} suppressed={SuppressedMissReports} " +
$"null_base={NullBaseMisses} line_fills={LineFillMisses}.");
}
}
225 changes: 225 additions & 0 deletions src/SharpEmu.HLE/GuestMemory/GuestReadContext.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,225 @@
// Copyright (C) 2026 SharpEmu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later

namespace SharpEmu.HLE.GuestMemory;

/// <summary>
/// Who on this thread reads guest memory now, for the report of a read that fails (the split GPU process's
/// RemoteGuestAddressSpace): the reader kind, the shader whose resources are being read, and the work being resolved
/// (the packet the command-stream thread walked last, or the prefetch job a resolver thread resolves). Every field is
/// thread-static and set by the code that knows it, so a read costs nothing extra; only a failed read formats them.
/// </summary>
public static class GuestReadContext
{
[ThreadStatic] private static string? t_reader;
[ThreadStatic] private static bool t_nullBase;
[ThreadStatic] private static bool t_lineFill;
[ThreadStatic] private static ulong t_shaderHash;
[ThreadStatic] private static string? t_shaderStage;
// Queue + 1 and job + 1: zero is "none".
[ThreadStatic] private static int t_queue;
[ThreadStatic] private static ulong t_submission;
[ThreadStatic] private static ulong t_packet;
[ThreadStatic] private static IGuestReadPacketSource? t_packetSource;
[ThreadStatic] private static long t_job;
// The last line fill on this thread that found no memory, for the word read that follows it (one report for both).
[ThreadStatic] private static ulong t_lineMissAddress;
[ThreadStatic] private static ulong t_lineMissSize;

/// <summary>The reader kind set on this thread (null: none set).</summary>
public static string? Reader => t_reader;

/// <summary>
/// True while the read in progress goes through a null base (a resource pointer of zero): every resource read is
/// evaluated up front, including reads the shader skips at run time when the pointer is null, and such a read's
/// value is zero whether or not memory answers (RuntimeValueEvaluator.ReadRawWord). Its miss is not a failed read.
/// </summary>
public static bool NullBase => t_nullBase;

/// <summary>True while the read in progress fills a word line around the word asked for (it may cover more).</summary>
public static bool LineFill => t_lineFill;

public static ulong ShaderHash
{
get => t_shaderHash;
set => t_shaderHash = value;
}

public static string? ShaderStage
{
get => t_shaderStage;
set => t_shaderStage = value;
}

/// <summary>Names the reader for the reads inside the scope; the previous reader comes back at its end.</summary>
public static Scope EnterReader(string reader)
{
var scope = new Scope(Field.Reader, t_reader, false);
t_reader = reader;
return scope;
}

/// <summary>Names the shader whose resources the reads inside the scope serve; the previous one comes back at its end.</summary>
public static Scope EnterShader(ulong hash, string? stage)
{
var scope = new Scope(Field.Shader, t_shaderStage, false, t_shaderHash);
t_shaderHash = hash;
t_shaderStage = stage;
return scope;
}

public static Scope EnterNullBase()
{
var scope = new Scope(Field.NullBase, null, t_nullBase);
t_nullBase = true;
return scope;
}

public static Scope EnterLineFill()
{
var scope = new Scope(Field.LineFill, null, t_lineFill);
t_lineFill = true;
return scope;
}

/// <summary>The packet the command-stream thread walks now, as explicit values.</summary>
public static void SetPacket(int queue, ulong submission, ulong packet)
{
t_packetSource = null;
t_queue = queue + 1;
t_submission = submission;
t_packet = packet;
}

/// <summary>
/// The walker whose current packet this thread's reads serve. Set once per walk, not per packet: the walker
/// already keeps its packet address, and only a failed read asks for it.
/// </summary>
public static void SetPacketSource(IGuestReadPacketSource? source) => t_packetSource = source;

/// <summary>The prefetch job this thread resolves now, or -1 for none.</summary>
public static void SetJob(long job) => t_job = job + 1;

/// <summary>A line fill found no memory (called by the address space that refused it).</summary>
public static void NoteLineMiss(ulong address, ulong size)
{
t_lineMissAddress = address;
t_lineMissSize = size;
}

/// <summary>
/// The line fill miss this thread noted last, when it covers [address, address + size): taken, so it pairs with one
/// word read only.
/// </summary>
public static bool TakeLineMiss(ulong address, ulong size, out ulong lineAddress, out ulong lineSize)
{
lineAddress = t_lineMissAddress;
lineSize = t_lineMissSize;
if (lineSize == 0 || address < lineAddress || address - lineAddress > lineSize || size > lineSize - (address - lineAddress))
{
return false;
}

t_lineMissAddress = 0;
t_lineMissSize = 0;
return true;
}

/// <summary>The context as report fields: reader, shader, stage, then queue/submit/packet or job, whichever is set.</summary>
public static string Describe()
{
// A read made while a shader's resources are materialized needs no name of its own on the hot path.
var text = $"reader={t_reader ?? (t_shaderHash != 0 ? "resource-read" : "unnamed")}";
if (t_shaderHash != 0)
{
text += $" shader=0x{t_shaderHash:X16}";
}

if (t_shaderStage is { } stage)
{
text += $" stage={stage}";
}

if (t_job != 0)
{
text += $" prefetch_job={t_job - 1}";
}
else if (t_packetSource is { } source)
{
source.CurrentPacket(out var queue, out var submission, out var packet);
text += $" queue={queue} submit={submission} packet=0x{packet:X16}";
}
else if (t_queue != 0)
{
text += $" queue={t_queue - 1} submit={t_submission} packet=0x{t_packet:X16}";
}

return text;
}

/// <summary>Test seam: every field of this thread back to none.</summary>
public static void Reset()
{
t_reader = null;
t_nullBase = t_lineFill = false;
t_shaderHash = 0;
t_shaderStage = null;
t_queue = 0;
t_submission = t_packet = 0;
t_packetSource = null;
t_job = 0;
t_lineMissAddress = t_lineMissSize = 0;
}

internal enum Field : byte
{
None,
Reader,
NullBase,
LineFill,
Shader,
}

/// <summary>Restores the field it set when disposed; the default scope restores nothing.</summary>
public readonly ref struct Scope
{
private readonly Field _field;
private readonly string? _reader;
private readonly bool _flag;
private readonly ulong _hash;

internal Scope(Field field, string? reader, bool flag, ulong hash = 0)
{
_field = field;
_reader = reader;
_flag = flag;
_hash = hash;
}

public void Dispose()
{
switch (_field)
{
case Field.Reader:
t_reader = _reader;
break;
case Field.NullBase:
t_nullBase = _flag;
break;
case Field.LineFill:
t_lineFill = _flag;
break;
case Field.Shader:
t_shaderHash = _hash;
t_shaderStage = _reader;
break;
}
}
}
}

/// <summary>A command-stream walker that can say which packet it walks now (GuestReadContext.SetPacketSource).</summary>
public interface IGuestReadPacketSource
{
void CurrentPacket(out int queue, out ulong submission, out ulong packet);
}
11 changes: 10 additions & 1 deletion src/SharpEmu.Libs/Gpu/GpuCommands/GpuCommandInterpreter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ public readonly record struct PacketContext(uint Header, ulong PacketAddress, ui
public readonly record struct FlipRequest(int Handle, int Index, int FlipMode, long FlipArgument);

// Parses one queue's command stream and keeps that queue's register and packet state.
public sealed partial class GpuCommandInterpreter
public sealed partial class GpuCommandInterpreter : SharpEmu.HLE.GuestMemory.IGuestReadPacketSource
{
public const int ComputeQueueBase = 0x20;
public const uint ConstantRamDwords = 0x3000;
Expand Down Expand Up @@ -70,6 +70,13 @@ public sealed partial class GpuCommandInterpreter
private SoftWait? _softWait;
private bool _suspendedForLanding;
private ulong _packetAddress;

void SharpEmu.HLE.GuestMemory.IGuestReadPacketSource.CurrentPacket(out int queue, out ulong submission, out ulong packet)
{
queue = QueueId;
submission = SubmitId;
packet = _packetAddress;
}
// The deferred dispatch runs of the stream thread, the rollback a handler asked for, and the raw shader register
// mirror's undo log while a run is open.
private IDeferredDispatchRuns? _runs;
Expand Down Expand Up @@ -449,6 +456,8 @@ public SubmissionProgress Process(PacketCursorStack execution, ulong address, ui
_dispatchMayOverlap = false;
// So is whatever was copied out of a command buffer: the guest may have stored into it since.
BeginPacketBlockSlice();
// Who asked, for a failed guest read's report (the split GPU process): this walker's current packet.
SharpEmu.HLE.GuestMemory.GuestReadContext.SetPacketSource(this);
_sliceStartTicks = System.Diagnostics.Stopwatch.GetTimestamp();
_pendingCommands = _host.CommandSignal;
_packetWindowGeneration++;
Expand Down
Loading
Loading