using Ryujinx.Cpu.Tracking;
using Ryujinx.Graphics.GAL;
using Ryujinx.Memory.Range;
using Ryujinx.Memory.Tracking;
using System;
namespace Ryujinx.Graphics.Gpu.Memory
{
///
/// Buffer, used to store vertex and index data, uniform and storage buffers, and others.
///
class Buffer : IRange, IDisposable
{
private static ulong GranularBufferThreshold = 4096;
private readonly GpuContext _context;
///
/// Host buffer handle.
///
public BufferHandle Handle { get; }
///
/// Start address of the buffer in guest memory.
///
public ulong Address { get; }
///
/// Size of the buffer in bytes.
///
public ulong Size { get; }
///
/// End address of the buffer in guest memory.
///
public ulong EndAddress => Address + Size;
///
/// Ranges of the buffer that have been modified on the GPU.
/// Ranges defined here cannot be updated from CPU until a CPU waiting sync point is reached.
/// Then, write tracking will signal, wait for GPU sync (generated at the syncpoint) and flush these regions.
///
///
/// This is null until at least one modification occurs.
///
private BufferModifiedRangeList _modifiedRanges = null;
private CpuMultiRegionHandle _memoryTrackingGranular;
private CpuRegionHandle _memoryTracking;
private readonly RegionSignal _externalFlushDelegate;
private readonly Action _loadDelegate;
private readonly Action _modifiedDelegate;
private int _sequenceNumber;
private bool _useGranular;
private bool _syncActionRegistered;
///
/// Creates a new instance of the buffer.
///
/// GPU context that the buffer belongs to
/// Start address of the buffer
/// Size of the buffer in bytes
public Buffer(GpuContext context, ulong address, ulong size)
{
_context = context;
Address = address;
Size = size;
Handle = context.Renderer.CreateBuffer((int)size);
_useGranular = size > GranularBufferThreshold;
if (_useGranular)
{
_memoryTrackingGranular = context.PhysicalMemory.BeginGranularTracking(address, size);
}
else
{
_memoryTracking = context.PhysicalMemory.BeginTracking(address, size);
}
_externalFlushDelegate = new RegionSignal(ExternalFlush);
_loadDelegate = new Action(LoadRegion);
_modifiedDelegate = new Action(RegionModified);
}
///
/// Gets a sub-range from the buffer.
///
///
/// This can be used to bind and use sub-ranges of the buffer on the host API.
///
/// Start address of the sub-range, must be greater than or equal to the buffer address
/// Size in bytes of the sub-range, must be less than or equal to the buffer size
/// The buffer sub-range
public BufferRange GetRange(ulong address, ulong size)
{
int offset = (int)(address - Address);
return new BufferRange(Handle, offset, (int)size);
}
///
/// Checks if a given range overlaps with the buffer.
///
/// Start address of the range
/// Size in bytes of the range
/// True if the range overlaps, false otherwise
public bool OverlapsWith(ulong address, ulong size)
{
return Address < address + size && address < EndAddress;
}
///
/// Performs guest to host memory synchronization of the buffer data.
///
///
/// This causes the buffer data to be overwritten if a write was detected from the CPU,
/// since the last call to this method.
///
/// Start address of the range to synchronize
/// Size in bytes of the range to synchronize
public void SynchronizeMemory(ulong address, ulong size)
{
if (_useGranular)
{
_memoryTrackingGranular.QueryModified(address, size, _modifiedDelegate, _context.SequenceNumber);
}
else
{
if (_memoryTracking.Dirty && _context.SequenceNumber != _sequenceNumber)
{
_memoryTracking.Reprotect();
if (_modifiedRanges != null)
{
_modifiedRanges.ExcludeModifiedRegions(Address, Size, _loadDelegate);
}
else
{
_context.Renderer.SetBufferData(Handle, 0, _context.PhysicalMemory.GetSpan(Address, (int)Size));
}
_sequenceNumber = _context.SequenceNumber;
}
}
}
///
/// Ensure that the modified range list exists.
///
private void EnsureRangeList()
{
if (_modifiedRanges == null)
{
_modifiedRanges = new BufferModifiedRangeList(_context);
}
}
///
/// Signal that the given region of the buffer has been modified.
///
/// The start address of the modified region
/// The size of the modified region
public void SignalModified(ulong address, ulong size)
{
EnsureRangeList();
_modifiedRanges.SignalModified(address, size);
if (!_syncActionRegistered)
{
_context.RegisterSyncAction(SyncAction);
_syncActionRegistered = true;
}
}
///
/// Indicate that mofifications in a given region of this buffer have been overwritten.
///
/// The start address of the region
/// The size of the region
public void ClearModified(ulong address, ulong size)
{
if (_modifiedRanges != null)
{
_modifiedRanges.Clear(address, size);
}
}
///
/// Action to be performed when a syncpoint is reached after modification.
/// This will register read/write tracking to flush the buffer from GPU when its memory is used.
///
private void SyncAction()
{
_syncActionRegistered = false;
if (_useGranular)
{
_modifiedRanges.GetRanges(Address, Size, (address, size) =>
{
_memoryTrackingGranular.RegisterAction(address, size, _externalFlushDelegate);
SynchronizeMemory(address, size);
});
}
else
{
_memoryTracking.RegisterAction(_externalFlushDelegate);
SynchronizeMemory(Address, Size);
}
}
///
/// Inherit modified ranges from another buffer.
///
/// The buffer to inherit from
public void InheritModifiedRanges(Buffer from)
{
if (from._modifiedRanges != null)
{
if (from._syncActionRegistered && !_syncActionRegistered)
{
_context.RegisterSyncAction(SyncAction);
_syncActionRegistered = true;
}
EnsureRangeList();
_modifiedRanges.InheritRanges(from._modifiedRanges, (ulong address, ulong size) =>
{
if (_useGranular)
{
_memoryTrackingGranular.RegisterAction(address, size, _externalFlushDelegate);
}
else
{
_memoryTracking.RegisterAction(_externalFlushDelegate);
}
});
}
}
///
/// Determine if a given region of the buffer has been modified, and must be flushed.
///
/// The start address of the region
/// The size of the region
///
public bool IsModified(ulong address, ulong size)
{
if (_modifiedRanges != null)
{
return _modifiedRanges.HasRange(address, size);
}
return false;
}
///
/// Indicate that a region of the buffer was modified, and must be loaded from memory.
///
/// Start address of the modified region
/// Size of the modified region
private void RegionModified(ulong mAddress, ulong mSize)
{
if (mAddress < Address)
{
mAddress = Address;
}
ulong maxSize = Address + Size - mAddress;
if (mSize > maxSize)
{
mSize = maxSize;
}
if (_modifiedRanges != null)
{
_modifiedRanges.ExcludeModifiedRegions(mAddress, mSize, _loadDelegate);
}
else
{
LoadRegion(mAddress, mSize);
}
}
///
/// Load a region of the buffer from memory.
///
/// Start address of the modified region
/// Size of the modified region
private void LoadRegion(ulong mAddress, ulong mSize)
{
int offset = (int)(mAddress - Address);
_context.Renderer.SetBufferData(Handle, offset, _context.PhysicalMemory.GetSpan(mAddress, (int)mSize));
}
///
/// Performs copy of all the buffer data from one buffer to another.
///
/// The destination buffer to copy the data into
/// The offset of the destination buffer to copy into
public void CopyTo(Buffer destination, int dstOffset)
{
_context.Renderer.Pipeline.CopyBuffer(Handle, destination.Handle, 0, dstOffset, (int)Size);
}
///
/// Flushes a range of the buffer.
/// This writes the range data back into guest memory.
///
/// Start address of the range
/// Size in bytes of the range
public void Flush(ulong address, ulong size)
{
int offset = (int)(address - Address);
byte[] data = _context.Renderer.GetBufferData(Handle, offset, (int)size);
// TODO: When write tracking shaders, they will need to be aware of changes in overlapping buffers.
_context.PhysicalMemory.WriteUntracked(address, data);
}
///
/// Align a given address and size region to page boundaries.
///
/// The start address of the region
/// The size of the region
/// The page aligned address and size
private static (ulong address, ulong size) PageAlign(ulong address, ulong size)
{
ulong pageMask = MemoryManager.PageMask;
ulong rA = address & ~pageMask;
ulong rS = ((address + size + pageMask) & ~pageMask) - rA;
return (rA, rS);
}
///
/// Flush modified ranges of the buffer from another thread.
/// This will flush all modifications made before the active SyncNumber was set, and may block to wait for GPU sync.
///
/// Address of the memory action
/// Size in bytes
public void ExternalFlush(ulong address, ulong size)
{
_context.Renderer.BackgroundContextAction(() =>
{
var ranges = _modifiedRanges;
if (ranges != null)
{
(address, size) = PageAlign(address, size);
ranges.WaitForAndGetRanges(address, size, Flush);
}
});
}
///
/// Called when part of the memory for this buffer has been unmapped.
/// Calls are from non-GPU threads.
///
/// Start address of the unmapped region
/// Size of the unmapped region
public void Unmapped(ulong address, ulong size)
{
_modifiedRanges?.Clear(address, size);
}
///
/// Disposes the host buffer.
///
public void Dispose()
{
_modifiedRanges?.Clear();
_memoryTrackingGranular?.Dispose();
_memoryTracking?.Dispose();
_context.Renderer.DeleteBuffer(Handle);
}
}
}