BufferCache.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397
  1. using Ryujinx.Graphics.GAL;
  2. using Ryujinx.Graphics.Gpu.State;
  3. using Ryujinx.Memory.Range;
  4. using System;
  5. using System.Collections.Generic;
  6. using System.Linq;
  7. namespace Ryujinx.Graphics.Gpu.Memory
  8. {
  9. /// <summary>
  10. /// Buffer cache.
  11. /// </summary>
  12. class BufferCache : IDisposable
  13. {
  14. private const int OverlapsBufferInitialCapacity = 10;
  15. private const int OverlapsBufferMaxCapacity = 10000;
  16. private const ulong BufferAlignmentSize = 0x1000;
  17. private const ulong BufferAlignmentMask = BufferAlignmentSize - 1;
  18. private readonly GpuContext _context;
  19. private readonly PhysicalMemory _physicalMemory;
  20. private readonly RangeList<Buffer> _buffers;
  21. private Buffer[] _bufferOverlaps;
  22. private readonly Dictionary<ulong, BufferCacheEntry> _dirtyCache;
  23. public event Action NotifyBuffersModified;
  24. /// <summary>
  25. /// Creates a new instance of the buffer manager.
  26. /// </summary>
  27. /// <param name="context">The GPU context that the buffer manager belongs to</param>
  28. /// <param name="physicalMemory">Physical memory where the cached buffers are mapped</param>
  29. public BufferCache(GpuContext context, PhysicalMemory physicalMemory)
  30. {
  31. _context = context;
  32. _physicalMemory = physicalMemory;
  33. _buffers = new RangeList<Buffer>();
  34. _bufferOverlaps = new Buffer[OverlapsBufferInitialCapacity];
  35. _dirtyCache = new Dictionary<ulong, BufferCacheEntry>();
  36. }
  37. /// <summary>
  38. /// Handles removal of buffers written to a memory region being unmapped.
  39. /// </summary>
  40. /// <param name="sender">Sender object</param>
  41. /// <param name="e">Event arguments</param>
  42. public void MemoryUnmappedHandler(object sender, UnmapEventArgs e)
  43. {
  44. Buffer[] overlaps = new Buffer[10];
  45. int overlapCount;
  46. ulong address = ((MemoryManager)sender).Translate(e.Address);
  47. ulong size = e.Size;
  48. lock (_buffers)
  49. {
  50. overlapCount = _buffers.FindOverlaps(address, size, ref overlaps);
  51. }
  52. for (int i = 0; i < overlapCount; i++)
  53. {
  54. overlaps[i].Unmapped(address, size);
  55. }
  56. }
  57. /// <summary>
  58. /// Performs address translation of the GPU virtual address, and creates a
  59. /// new buffer, if needed, for the specified range.
  60. /// </summary>
  61. /// <param name="memoryManager">GPU memory manager where the buffer is mapped</param>
  62. /// <param name="gpuVa">Start GPU virtual address of the buffer</param>
  63. /// <param name="size">Size in bytes of the buffer</param>
  64. /// <returns>CPU virtual address of the buffer, after address translation</returns>
  65. public ulong TranslateAndCreateBuffer(MemoryManager memoryManager, ulong gpuVa, ulong size)
  66. {
  67. if (gpuVa == 0)
  68. {
  69. return 0;
  70. }
  71. ulong address = memoryManager.Translate(gpuVa);
  72. if (address == MemoryManager.PteUnmapped)
  73. {
  74. return 0;
  75. }
  76. CreateBuffer(address, size);
  77. return address;
  78. }
  79. /// <summary>
  80. /// Creates a new buffer for the specified range, if it does not yet exist.
  81. /// This can be used to ensure the existance of a buffer.
  82. /// </summary>
  83. /// <param name="address">Address of the buffer in memory</param>
  84. /// <param name="size">Size of the buffer in bytes</param>
  85. public void CreateBuffer(ulong address, ulong size)
  86. {
  87. ulong endAddress = address + size;
  88. ulong alignedAddress = address & ~BufferAlignmentMask;
  89. ulong alignedEndAddress = (endAddress + BufferAlignmentMask) & ~BufferAlignmentMask;
  90. // The buffer must have the size of at least one page.
  91. if (alignedEndAddress == alignedAddress)
  92. {
  93. alignedEndAddress += BufferAlignmentSize;
  94. }
  95. CreateBufferAligned(alignedAddress, alignedEndAddress - alignedAddress);
  96. }
  97. /// <summary>
  98. /// Performs address translation of the GPU virtual address, and attempts to force
  99. /// the buffer in the region as dirty.
  100. /// The buffer lookup for this function is cached in a dictionary for quick access, which
  101. /// accelerates common UBO updates.
  102. /// </summary>
  103. /// <param name="memoryManager">GPU memory manager where the buffer is mapped</param>
  104. /// <param name="gpuVa">Start GPU virtual address of the buffer</param>
  105. /// <param name="size">Size in bytes of the buffer</param>
  106. public void ForceDirty(MemoryManager memoryManager, ulong gpuVa, ulong size)
  107. {
  108. if (!_dirtyCache.TryGetValue(gpuVa, out BufferCacheEntry result) ||
  109. result.EndGpuAddress < gpuVa + size ||
  110. result.UnmappedSequence != result.Buffer.UnmappedSequence)
  111. {
  112. ulong address = TranslateAndCreateBuffer(memoryManager, gpuVa, size);
  113. result = new BufferCacheEntry(address, gpuVa, GetBuffer(address, size));
  114. _dirtyCache[gpuVa] = result;
  115. }
  116. result.Buffer.ForceDirty(result.Address, size);
  117. }
  118. /// <summary>
  119. /// Creates a new buffer for the specified range, if needed.
  120. /// If a buffer where this range can be fully contained already exists,
  121. /// then the creation of a new buffer is not necessary.
  122. /// </summary>
  123. /// <param name="address">Address of the buffer in guest memory</param>
  124. /// <param name="size">Size in bytes of the buffer</param>
  125. private void CreateBufferAligned(ulong address, ulong size)
  126. {
  127. int overlapsCount;
  128. lock (_buffers)
  129. {
  130. overlapsCount = _buffers.FindOverlapsNonOverlapping(address, size, ref _bufferOverlaps);
  131. }
  132. if (overlapsCount != 0)
  133. {
  134. // The buffer already exists. We can just return the existing buffer
  135. // if the buffer we need is fully contained inside the overlapping buffer.
  136. // Otherwise, we must delete the overlapping buffers and create a bigger buffer
  137. // that fits all the data we need. We also need to copy the contents from the
  138. // old buffer(s) to the new buffer.
  139. ulong endAddress = address + size;
  140. if (_bufferOverlaps[0].Address > address || _bufferOverlaps[0].EndAddress < endAddress)
  141. {
  142. for (int index = 0; index < overlapsCount; index++)
  143. {
  144. Buffer buffer = _bufferOverlaps[index];
  145. address = Math.Min(address, buffer.Address);
  146. endAddress = Math.Max(endAddress, buffer.EndAddress);
  147. lock (_buffers)
  148. {
  149. _buffers.Remove(buffer);
  150. }
  151. }
  152. Buffer newBuffer = new Buffer(_context, _physicalMemory, address, endAddress - address, _bufferOverlaps.Take(overlapsCount));
  153. lock (_buffers)
  154. {
  155. _buffers.Add(newBuffer);
  156. }
  157. for (int index = 0; index < overlapsCount; index++)
  158. {
  159. Buffer buffer = _bufferOverlaps[index];
  160. int dstOffset = (int)(buffer.Address - newBuffer.Address);
  161. buffer.CopyTo(newBuffer, dstOffset);
  162. newBuffer.InheritModifiedRanges(buffer);
  163. buffer.DisposeData();
  164. }
  165. newBuffer.SynchronizeMemory(address, endAddress - address);
  166. // Existing buffers were modified, we need to rebind everything.
  167. NotifyBuffersModified?.Invoke();
  168. }
  169. }
  170. else
  171. {
  172. // No overlap, just create a new buffer.
  173. Buffer buffer = new Buffer(_context, _physicalMemory, address, size);
  174. lock (_buffers)
  175. {
  176. _buffers.Add(buffer);
  177. }
  178. }
  179. ShrinkOverlapsBufferIfNeeded();
  180. }
  181. /// <summary>
  182. /// Resizes the temporary buffer used for range list intersection results, if it has grown too much.
  183. /// </summary>
  184. private void ShrinkOverlapsBufferIfNeeded()
  185. {
  186. if (_bufferOverlaps.Length > OverlapsBufferMaxCapacity)
  187. {
  188. Array.Resize(ref _bufferOverlaps, OverlapsBufferMaxCapacity);
  189. }
  190. }
  191. /// <summary>
  192. /// Copy a buffer data from a given address to another.
  193. /// </summary>
  194. /// <remarks>
  195. /// This does a GPU side copy.
  196. /// </remarks>
  197. /// <param name="memoryManager">GPU memory manager where the buffer is mapped</param>
  198. /// <param name="srcVa">GPU virtual address of the copy source</param>
  199. /// <param name="dstVa">GPU virtual address of the copy destination</param>
  200. /// <param name="size">Size in bytes of the copy</param>
  201. public void CopyBuffer(MemoryManager memoryManager, GpuVa srcVa, GpuVa dstVa, ulong size)
  202. {
  203. ulong srcAddress = TranslateAndCreateBuffer(memoryManager, srcVa.Pack(), size);
  204. ulong dstAddress = TranslateAndCreateBuffer(memoryManager, dstVa.Pack(), size);
  205. Buffer srcBuffer = GetBuffer(srcAddress, size);
  206. Buffer dstBuffer = GetBuffer(dstAddress, size);
  207. int srcOffset = (int)(srcAddress - srcBuffer.Address);
  208. int dstOffset = (int)(dstAddress - dstBuffer.Address);
  209. _context.Renderer.Pipeline.CopyBuffer(
  210. srcBuffer.Handle,
  211. dstBuffer.Handle,
  212. srcOffset,
  213. dstOffset,
  214. (int)size);
  215. if (srcBuffer.IsModified(srcAddress, size))
  216. {
  217. dstBuffer.SignalModified(dstAddress, size);
  218. }
  219. else
  220. {
  221. // Optimization: If the data being copied is already in memory, then copy it directly instead of flushing from GPU.
  222. dstBuffer.ClearModified(dstAddress, size);
  223. memoryManager.Physical.WriteUntracked(dstAddress, memoryManager.Physical.GetSpan(srcAddress, (int)size));
  224. }
  225. }
  226. /// <summary>
  227. /// Clears a buffer at a given address with the specified value.
  228. /// </summary>
  229. /// <remarks>
  230. /// Both the address and size must be aligned to 4 bytes.
  231. /// </remarks>
  232. /// <param name="memoryManager">GPU memory manager where the buffer is mapped</param>
  233. /// <param name="gpuVa">GPU virtual address of the region to clear</param>
  234. /// <param name="size">Number of bytes to clear</param>
  235. /// <param name="value">Value to be written into the buffer</param>
  236. public void ClearBuffer(MemoryManager memoryManager, GpuVa gpuVa, ulong size, uint value)
  237. {
  238. ulong address = TranslateAndCreateBuffer(memoryManager, gpuVa.Pack(), size);
  239. Buffer buffer = GetBuffer(address, size);
  240. int offset = (int)(address - buffer.Address);
  241. _context.Renderer.Pipeline.ClearBuffer(buffer.Handle, offset, (int)size, value);
  242. buffer.SignalModified(address, size);
  243. }
  244. /// <summary>
  245. /// Gets a buffer sub-range starting at a given memory address.
  246. /// </summary>
  247. /// <param name="address">Start address of the memory range</param>
  248. /// <param name="size">Size in bytes of the memory range</param>
  249. /// <param name="write">Whether the buffer will be written to by this use</param>
  250. /// <returns>The buffer sub-range starting at the given memory address</returns>
  251. public BufferRange GetBufferRangeTillEnd(ulong address, ulong size, bool write = false)
  252. {
  253. return GetBuffer(address, size, write).GetRange(address);
  254. }
  255. /// <summary>
  256. /// Gets a buffer sub-range for a given memory range.
  257. /// </summary>
  258. /// <param name="address">Start address of the memory range</param>
  259. /// <param name="size">Size in bytes of the memory range</param>
  260. /// <param name="write">Whether the buffer will be written to by this use</param>
  261. /// <returns>The buffer sub-range for the given range</returns>
  262. public BufferRange GetBufferRange(ulong address, ulong size, bool write = false)
  263. {
  264. return GetBuffer(address, size, write).GetRange(address, size);
  265. }
  266. /// <summary>
  267. /// Gets a buffer for a given memory range.
  268. /// A buffer overlapping with the specified range is assumed to already exist on the cache.
  269. /// </summary>
  270. /// <param name="address">Start address of the memory range</param>
  271. /// <param name="size">Size in bytes of the memory range</param>
  272. /// <param name="write">Whether the buffer will be written to by this use</param>
  273. /// <returns>The buffer where the range is fully contained</returns>
  274. private Buffer GetBuffer(ulong address, ulong size, bool write = false)
  275. {
  276. Buffer buffer;
  277. if (size != 0)
  278. {
  279. lock (_buffers)
  280. {
  281. buffer = _buffers.FindFirstOverlap(address, size);
  282. }
  283. buffer.SynchronizeMemory(address, size);
  284. if (write)
  285. {
  286. buffer.SignalModified(address, size);
  287. }
  288. }
  289. else
  290. {
  291. lock (_buffers)
  292. {
  293. buffer = _buffers.FindFirstOverlap(address, 1);
  294. }
  295. }
  296. return buffer;
  297. }
  298. /// <summary>
  299. /// Performs guest to host memory synchronization of a given memory range.
  300. /// </summary>
  301. /// <param name="address">Start address of the memory range</param>
  302. /// <param name="size">Size in bytes of the memory range</param>
  303. public void SynchronizeBufferRange(ulong address, ulong size)
  304. {
  305. if (size != 0)
  306. {
  307. Buffer buffer;
  308. lock (_buffers)
  309. {
  310. buffer = _buffers.FindFirstOverlap(address, size);
  311. }
  312. buffer.SynchronizeMemory(address, size);
  313. }
  314. }
  315. /// <summary>
  316. /// Disposes all buffers in the cache.
  317. /// It's an error to use the buffer manager after disposal.
  318. /// </summary>
  319. public void Dispose()
  320. {
  321. lock (_buffers)
  322. {
  323. foreach (Buffer buffer in _buffers)
  324. {
  325. buffer.Dispose();
  326. }
  327. }
  328. }
  329. }
  330. }