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
9 changes: 6 additions & 3 deletions docs/macos/split-shared-memory.md
Original file line number Diff line number Diff line change
Expand Up @@ -108,9 +108,12 @@ Only a backing the host made shareable (`SHARPEMU_GPU_PROCESS=1` or
that address in every process started without `MallocNanoZone=0` (apps from Finder or the Dock,
and shell launches unless the shell sets it), so the layout checks the address when it is
selected and moves the arena to another free range if it is taken (a `[VMEM]` warning names the
new address). A sends the address to B in the split start, and B's replica covers it there.
If the arena still cannot be mapped at first use, it is private: an error line, and
`PhysicalVirtualMemory.SplitArenaMapFailures` counts it.
new address). The chosen range is held from then on (a no-access reservation, held again after
each `Clear`) until the arena's view replaces it at the first guest allocation, so nothing mapped
in between (the nano zone growing, dyld, a host library) can land there. A sends the address to B
in the split start, and B's replica covers it there. If no range could be held, or the arena still
cannot be mapped at first use, it is private: an error line, and
`PhysicalVirtualMemory.SplitArenaMapFailures` counts a map failure.
- **HLE data.** `TryAllocateHleData` takes its memory from the backed arena
(`IGuestMemoryAllocator.AllocatesFromBacking`). That covers AGC register-default blobs, AvPlayer
frames and the VideoOut label fallback, with no mapping per allocation. The memory is zeroed as
Expand Down
81 changes: 62 additions & 19 deletions src/SharpEmu.Core/Memory/PhysicalVirtualMemory.SplitLayout.cs
Original file line number Diff line number Diff line change
Expand Up @@ -96,42 +96,84 @@ public bool AllocatesFromBacking
// GuestMemoryLayout.AllocatorArenaAddress in every process started without MallocNanoZone=0
// (apps from Finder or the Dock, and a shell's children unless it sets that), and a private
// arena would hide VideoOut labels and HLE data from the GPU process. Nothing guest-visible
// depends on the address: the arena is handed out only as pointers.
// depends on the address: the arena is handed out only as pointers. The chosen range is held
// (a no-access reservation the arena's view later replaces) from here on, so nothing mapped
// before the first guest allocation (the nano zone growing, dyld, a host library) can land there.
private SplitBackingLayout PlaceSplitArena(SplitBackingLayout requested)
{
var preferred = requested.ArenaAddress;
var bytes = requested.ArenaBytes;
var limit = SplitBackingLayout.ArenaAddressLimit;
// The lowest free range at or above the preferred address: the address itself when it is free.
var found = _backedSpace!.FindUnmappedHostRange(preferred, bytes, Math.Max(limit, preferred + bytes));
if (found == preferred || found == 0)
for (var attempt = 0; attempt < ArenaPlacementAttempts; attempt++)
{
// Free, or the host cannot say: mapping it at first use answers (TryMapSplitArena, loud when it fails).
return requested;
// The lowest free range at or above the preferred address: the address itself when it is free.
var found = _backedSpace!.FindUnmappedHostRange(preferred, bytes, Math.Max(limit, preferred + bytes));
var hostCannotSay = found == 0;
var candidate = found == preferred || hostCannotSay ? preferred : FindRelocatedArena(preferred, bytes, limit);
if (candidate == 0)
{
Log.Error($"Split layout: 0x{preferred:X16}+0x{bytes:X} is taken and no other free range was found below " +
$"0x{limit:X}; the guest allocator arena will be private, and the GPU process cannot see the VideoOut labels " +
"or HLE data in it.");
return requested;
}

if (TryHoldRange(candidate, bytes))
{
if (candidate != preferred)
{
Log.Warn($"Split layout: 0x{preferred:X16} is taken (under Rosetta the malloc nano zone sits there unless " +
$"MallocNanoZone=0); the guest allocator arena is at 0x{candidate:X16} instead, and the GPU process replicates it there.");
}

return requested.WithArenaAddress(candidate);
}

// Taken since the probe; the next probe sees it. A host that cannot say where mappings are has nothing else to try.
if (hostCannotSay)
{
break;
}
}

Log.Error($"Split layout: no range for the guest allocator arena (0x{bytes:X} bytes, preferred 0x{preferred:X16}) " +
"could be held; mapping it at first use will be tried and is likely to fail, leaving it private, and the GPU process " +
"cannot see the VideoOut labels or HLE data in it then.");
return requested;
}

// Probe-then-hold races with other mappings; each attempt probes again.
private const int ArenaPlacementAttempts = 4;

// Another free range for an arena whose preferred address is taken: well above it (clear of the
// nano zone's upward growth), else below it; 0 when none is.
private ulong FindRelocatedArena(ulong preferred, ulong bytes, ulong limit)
{
var relocated = 0UL;
if (preferred <= ulong.MaxValue - SplitBackingLayout.ArenaRelocationGap)
{
relocated = FindFreeArenaRange(preferred + SplitBackingLayout.ArenaRelocationGap, bytes, limit);
}

if (relocated == 0)
return relocated != 0
? relocated
: FindFreeArenaRange(SplitBackingLayout.ArenaAddressFloor, bytes, Math.Min(limit, preferred));
}

// Caller holds _gate for writing. Clear released every owned range, the arena's hold with them;
// the GPU process still expects the arena at the layout's address, so it is held again.
private void HoldSplitArenaAfterClear()
{
if (_splitLayout is not { } layout || !HasBackingOwner())
{
relocated = FindFreeArenaRange(SplitBackingLayout.ArenaAddressFloor, bytes, Math.Min(limit, preferred));
return;
}

if (relocated == 0)
if (!TryReserveBackingRange(layout.ArenaAddress, layout.ArenaBytes))
{
Log.Error($"Split layout: 0x{preferred:X16}+0x{bytes:X} is taken and no other free range was found below " +
$"0x{limit:X}; the guest allocator arena will be private, and the GPU process cannot see the VideoOut labels " +
"or HLE data in it.");
return requested;
Log.Error($"Split layout: the guest allocator arena's range 0x{layout.ArenaAddress:X16}+0x{layout.ArenaBytes:X} " +
"could not be held again after the address space was cleared; mapping it at first use may fail, leaving it private.");
}

Log.Warn($"Split layout: 0x{preferred:X16} is taken (under Rosetta the malloc nano zone sits there unless " +
$"MallocNanoZone=0); the guest allocator arena is at 0x{relocated:X16} instead, and the GPU process replicates it there.");
return requested.WithArenaAddress(relocated);
}

// A guest-page-aligned range of bytes with nothing mapped, in [start, limit); 0 when none is.
Expand Down Expand Up @@ -159,8 +201,9 @@ private ulong FindFreeArenaRange(ulong start, ulong bytes, ulong limit)
return 0;
}

// The split layout's arena: one view of the backing at the layout's address. Caller holds
// _guestAllocationGate. False (nothing mapped) leaves the arena to the private path.
// The split layout's arena: one view of the backing at the layout's address, over the range
// PlaceSplitArena (or Clear) held. Caller holds _guestAllocationGate. False (nothing mapped)
// leaves the arena to the private path, loudly: the GPU process was told this address.
private bool TryMapSplitArena(out ulong arenaBase, ref ulong arenaSize)
{
arenaBase = 0;
Expand Down
12 changes: 10 additions & 2 deletions src/SharpEmu.Core/Memory/PhysicalVirtualMemory.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2134,7 +2134,10 @@ private static HostPageProtection ResolveProtection(GuestPageProtection protecti
: HostPageProtection.NoAccess;
}

public void Clear()
public void Clear() => Clear(holdSplitArena: true);

// Dispose clears without holding the split arena again: the backing's owner goes next.
private void Clear(bool holdSplitArena)
{
lock (_guestAllocationGate)
{
Expand Down Expand Up @@ -2174,6 +2177,11 @@ public void Clear()
if (_ownsStartupAddressReservations)
_fixedGranuleReservationBases.Add(WindowsGuestAddressReservation.ImageStart);
_backedSpace?.ReleaseAddressRanges();
if (holdSplitArena)
{
HoldSplitArenaAfterClear();
}

_regions.Clear();
_allocationGaps.Clear();
_pageProtections.Clear();
Expand Down Expand Up @@ -3763,7 +3771,7 @@ public void Dispose()
{
if (!_disposed)
{
Clear();
Clear(holdSplitArena: false);
_backedSpace?.Dispose();
_backedSpace = null;
if (_ownsStartupAddressReservations && !_hostMemory.Free(WindowsGuestAddressReservation.ImageStart))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -250,25 +250,42 @@ public void AnArenaWhoseAddressIsTakenIsPlacedElsewhereStillBacked()
}

[Fact]
public void AnArenaThatCannotBeMappedAtFirstUseIsCountedAndPrivate()
public void AnArenaTakenBetweenSelectionAndFirstUseStaysBacked()
{
if (!_shareable) return;
var host = HostViewMemory.Create();
var layout = Layout(ProbeGuestAddress(host, ArenaBytes));
using var memory = CreateMemory(host, layout);
Assert.Same(layout, memory.SplitLayout);
// Taken after the layout was selected (and the GPU process told): the arena cannot move any more.
Assert.Equal(layout.ArenaAddress, host.ReserveHole(layout.ArenaAddress, ArenaBytes));
try
{
Assert.True(memory.TryAllocateGuestMemory(0x100, 0x40, out var allocation));
Assert.Equal(1, memory.SplitArenaMapFailures);
Assert.False(memory.AllocatesFromBacking);
Assert.False(memory.IsBackedRange(allocation, 0x100));
}
finally
for (var load = 0; load < 2; load++)
{
Assert.True(host.FreeHole(layout.ArenaAddress, ArenaBytes));
if (load != 0)
{
// Clear (each load) releases every range; the arena's is held again at the same address.
memory.Clear();
}

// Something maps into the arena's range after the layout was selected (and the GPU process
// told) but before the first guest allocation, as the nano zone growing or a host library
// would: exact placement without overwriting, as mach_vm_allocate(VM_FLAGS_FIXED) does. The
// range is held from selection on, so it cannot land; before, it did and the arena went private.
var outsider = host.ReserveHole(layout.ArenaAddress, Page);
try
{
Assert.True(memory.TryAllocateGuestMemory(0x100, 0x40, out var allocation));
Assert.Equal(0, memory.SplitArenaMapFailures);
Assert.True(memory.AllocatesFromBacking);
Assert.InRange(allocation, layout.ArenaAddress, layout.ArenaAddress + ArenaBytes - 0x100);
Assert.True(memory.IsBackedRange(layout.ArenaAddress, ArenaBytes));
Assert.Equal(0UL, outsider);
}
finally
{
if (outsider != 0)
{
host.FreeHole(outsider, Page);
}
}
}
}

Expand Down
Loading