Ryujinx/Ryujinx.Memory/Tracking/SmartMultiRegionHandle.cs

237 lines
8.1 KiB
C#
Raw Normal View History

Memory Read/Write Tracking using Region Handles (#1272) * WIP Range Tracking - Texture invalidation seems to have large problems - Buffer/Pool invalidation may have problems - Mirror memory tracking puts an additional `add` in compiled code, we likely just want to make HLE access slower if this is the final solution. - Native project is in the messiest possible location. - [HACK] JIT memory access always uses native "fast" path - [HACK] Trying some things with texture invalidation and views. It works :) Still a few hacks, messy things, slow things More work in progress stuff (also move to memory project) Quite a bit faster now. - Unmapping GPU VA and CPU VA will now correctly update write tracking regions, and invalidate textures for the former. - The Virtual range list is now non-overlapping like the physical one. - Fixed some bugs where regions could leak. - Introduced a weird bug that I still need to track down (consistent invalid buffer in MK8 ribbon road) Move some stuff. I think we'll eventually just put the dll and so for this in a nuget package. Fix rebase. [WIP] MultiRegionHandle variable size ranges - Avoid reprotecting regions that change often (needs some tweaking) - There's still a bug in buffers, somehow. - Might want different api for minimum granularity Fix rebase issue Commit everything needed for software only tracking. Remove native components. Remove more native stuff. Cleanup Use a separate window for the background context, update opentk. (fixes linux) Some experimental changes Should get things working up to scratch - still need to try some things with flush/modification and res scale. Include address with the region action. Initial work to make range tracking work Still a ton of bugs Fix some issues with the new stuff. * Fix texture flush instability There's still some weird behaviour, but it's much improved without this. (textures with cpu modified data were flushing over it) * Find the destination texture for Buffer->Texture full copy Greatly improves performance for nvdec videos (with range tracking) * Further improve texture tracking * Disable Memory Tracking for view parents This is a temporary approach to better match behaviour on master (where invalidations would be soaked up by views, rather than trigger twice) The assumption is that when views are created to a texture, they will cover all of its data anyways. Of course, this can easily be improved in future. * Introduce some tracking tests. WIP * Complete base tests. * Add more tests for multiregion, fix existing test. * Cleanup Part 1 * Remove unnecessary code from memory tracking * Fix some inconsistencies with 3D texture rule. * Add dispose tests. * Use a background thread for the background context. Rather than setting and unsetting a context as current, doing the work on a dedicated thread with signals seems to be a bit faster. Also nerf the multithreading test a bit. * Copy to texture with matching alignment This extends the copy to work for some videos with unusual size, such as tutorial videos in SMO. It will only occur if the destination texture already exists at XCount size. * Track reads for buffer copies. Synchronize new buffers before copying overlaps. * Remove old texture flushing mechanisms. Range tracking all the way, baby. * Wake the background thread when disposing. Avoids a deadlock when games are closed. * Address Feedback 1 * Separate TextureCopy instance for background thread Also `BackgroundContextWorker.InBackground` for a more sensible idenfifier for if we're in a background thread. * Add missing XML docs. * Address Feedback * Maybe I should start drinking coffee. * Some more feedback. * Remove flush warning, Refocus window after making background context
2020-10-16 22:18:35 +02:00
using System;
using System.Runtime.CompilerServices;
namespace Ryujinx.Memory.Tracking
{
/// <summary>
/// A MultiRegionHandle that attempts to segment a region's handles into the regions requested
/// to avoid iterating over granular chunks for canonically large regions.
/// If minimum granularity is to be expected, use MultiRegionHandle.
/// </summary>
public class SmartMultiRegionHandle : IMultiRegionHandle
{
/// <summary>
/// A list of region handles starting at each granularity size increment.
/// </summary>
private readonly RegionHandle[] _handles;
private readonly ulong _address;
private readonly ulong _granularity;
private readonly ulong _size;
private MemoryTracking _tracking;
public bool Dirty { get; private set; } = true;
internal SmartMultiRegionHandle(MemoryTracking tracking, ulong address, ulong size, ulong granularity)
{
// For this multi-region handle, the handle list starts empty.
// As regions are queried, they are added to the _handles array at their start index.
// When a region being added overlaps another, the existing region is split.
// A query can therefore scan multiple regions, though with no overlaps they can cover a large area.
_tracking = tracking;
_handles = new RegionHandle[size / granularity];
_granularity = granularity;
_address = address;
_size = size;
}
public void SignalWrite()
{
Dirty = true;
}
public void QueryModified(Action<ulong, ulong> modifiedAction)
{
if (!Dirty)
{
return;
}
Dirty = false;
QueryModified(_address, _size, modifiedAction);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private ulong HandlesToBytes(int handles)
{
return (ulong)handles * _granularity;
}
private void SplitHandle(int handleIndex, int splitIndex)
{
RegionHandle handle = _handles[handleIndex];
ulong address = _address + HandlesToBytes(handleIndex);
ulong size = HandlesToBytes(splitIndex - handleIndex);
// First, the target handle must be removed. Its data can still be used to determine the new handles.
handle.Dispose();
RegionHandle splitLow = _tracking.BeginTracking(address, size);
splitLow.Parent = this;
_handles[handleIndex] = splitLow;
RegionHandle splitHigh = _tracking.BeginTracking(address + size, handle.Size - size);
splitHigh.Parent = this;
_handles[splitIndex] = splitHigh;
}
private void CreateHandle(int startHandle, int lastHandle)
{
ulong startAddress = _address + HandlesToBytes(startHandle);
// Scan for the first handle before us. If it's overlapping us, it must be split.
for (int i = startHandle - 1; i >= 0; i--)
{
RegionHandle handle = _handles[i];
if (handle != null)
{
if (handle.EndAddress > startAddress)
{
SplitHandle(i, startHandle);
return; // The remainer of this handle should be filled in later on.
}
break;
}
}
// Scan for handles after us. We should create a handle that goes up to this handle's start point, if present.
for (int i = startHandle + 1; i <= lastHandle; i++)
{
RegionHandle handle = _handles[i];
if (handle != null)
{
// Fill up to the found handle.
handle = _tracking.BeginTracking(startAddress, HandlesToBytes(i - startHandle));
handle.Parent = this;
_handles[startHandle] = handle;
return;
}
}
// Can fill the whole range.
_handles[startHandle] = _tracking.BeginTracking(startAddress, HandlesToBytes(1 + lastHandle - startHandle));
_handles[startHandle].Parent = this;
}
public void QueryModified(ulong address, ulong size, Action<ulong, ulong> modifiedAction)
{
int startHandle = (int)((address - _address) / _granularity);
int lastHandle = (int)((address + (size - 1) - _address) / _granularity);
ulong rgStart = _address + (ulong)startHandle * _granularity;
ulong rgSize = 0;
ulong endAddress = _address + ((ulong)lastHandle + 1) * _granularity;
int i = startHandle;
while (i <= lastHandle)
{
RegionHandle handle = _handles[i];
if (handle == null)
{
// Missing handle. A new handle must be created.
CreateHandle(i, lastHandle);
handle = _handles[i];
}
if (handle.EndAddress > endAddress)
{
// End address of handle is beyond the end of the search. Force a split.
SplitHandle(i, lastHandle + 1);
handle = _handles[i];
}
if (handle.Dirty)
{
rgSize += handle.Size;
handle.Reprotect();
}
else
{
// Submit the region scanned so far as dirty
if (rgSize != 0)
{
modifiedAction(rgStart, rgSize);
rgSize = 0;
}
rgStart = handle.EndAddress;
}
i += (int)(handle.Size / _granularity);
}
if (rgSize != 0)
{
modifiedAction(rgStart, rgSize);
}
}
public void QueryModified(ulong address, ulong size, Action<ulong, ulong> modifiedAction, int sequenceNumber)
{
int startHandle = (int)((address - _address) / _granularity);
int lastHandle = (int)((address + (size - 1) - _address) / _granularity);
ulong rgStart = _address + (ulong)startHandle * _granularity;
ulong rgSize = 0;
ulong endAddress = _address + ((ulong)lastHandle + 1) * _granularity;
int i = startHandle;
while (i <= lastHandle)
{
RegionHandle handle = _handles[i];
if (handle == null)
{
// Missing handle. A new handle must be created.
CreateHandle(i, lastHandle);
handle = _handles[i];
}
if (handle.EndAddress > endAddress)
{
// End address of handle is beyond the end of the search. Force a split.
SplitHandle(i, lastHandle + 1);
handle = _handles[i];
}
if (handle.Dirty && sequenceNumber != handle.SequenceNumber)
{
rgSize += handle.Size;
handle.Reprotect();
}
else
{
// Submit the region scanned so far as dirty
if (rgSize != 0)
{
modifiedAction(rgStart, rgSize);
rgSize = 0;
}
rgStart = handle.EndAddress;
}
handle.SequenceNumber = sequenceNumber;
i += (int)(handle.Size / _granularity);
}
if (rgSize != 0)
{
modifiedAction(rgStart, rgSize);
}
}
public void Dispose()
{
foreach (var handle in _handles)
{
handle?.Dispose();
}
}
}
}