Buffer.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488
  1. using Ryujinx.Cpu.Tracking;
  2. using Ryujinx.Graphics.GAL;
  3. using Ryujinx.Memory.Range;
  4. using Ryujinx.Memory.Tracking;
  5. using System;
  6. using System.Collections.Generic;
  7. using System.Linq;
  8. namespace Ryujinx.Graphics.Gpu.Memory
  9. {
  10. /// <summary>
  11. /// Buffer, used to store vertex and index data, uniform and storage buffers, and others.
  12. /// </summary>
  13. class Buffer : IRange, IDisposable
  14. {
  15. private static ulong GranularBufferThreshold = 4096;
  16. private readonly GpuContext _context;
  17. /// <summary>
  18. /// Host buffer handle.
  19. /// </summary>
  20. public BufferHandle Handle { get; }
  21. /// <summary>
  22. /// Start address of the buffer in guest memory.
  23. /// </summary>
  24. public ulong Address { get; }
  25. /// <summary>
  26. /// Size of the buffer in bytes.
  27. /// </summary>
  28. public ulong Size { get; }
  29. /// <summary>
  30. /// End address of the buffer in guest memory.
  31. /// </summary>
  32. public ulong EndAddress => Address + Size;
  33. /// <summary>
  34. /// Increments when the buffer is (partially) unmapped or disposed.
  35. /// </summary>
  36. public int UnmappedSequence { get; private set; }
  37. /// <summary>
  38. /// Ranges of the buffer that have been modified on the GPU.
  39. /// Ranges defined here cannot be updated from CPU until a CPU waiting sync point is reached.
  40. /// Then, write tracking will signal, wait for GPU sync (generated at the syncpoint) and flush these regions.
  41. /// </summary>
  42. /// <remarks>
  43. /// This is null until at least one modification occurs.
  44. /// </remarks>
  45. private BufferModifiedRangeList _modifiedRanges = null;
  46. private readonly CpuMultiRegionHandle _memoryTrackingGranular;
  47. private readonly CpuRegionHandle _memoryTracking;
  48. private readonly RegionSignal _externalFlushDelegate;
  49. private readonly Action<ulong, ulong> _loadDelegate;
  50. private readonly Action<ulong, ulong> _modifiedDelegate;
  51. private int _sequenceNumber;
  52. private bool _useGranular;
  53. private bool _syncActionRegistered;
  54. /// <summary>
  55. /// Creates a new instance of the buffer.
  56. /// </summary>
  57. /// <param name="context">GPU context that the buffer belongs to</param>
  58. /// <param name="address">Start address of the buffer</param>
  59. /// <param name="size">Size of the buffer in bytes</param>
  60. /// <param name="baseBuffers">Buffers which this buffer contains, and will inherit tracking handles from</param>
  61. public Buffer(GpuContext context, ulong address, ulong size, IEnumerable<Buffer> baseBuffers = null)
  62. {
  63. _context = context;
  64. Address = address;
  65. Size = size;
  66. Handle = context.Renderer.CreateBuffer((int)size);
  67. _useGranular = size > GranularBufferThreshold;
  68. IEnumerable<IRegionHandle> baseHandles = null;
  69. if (baseBuffers != null)
  70. {
  71. baseHandles = baseBuffers.SelectMany(buffer =>
  72. {
  73. if (buffer._useGranular)
  74. {
  75. return buffer._memoryTrackingGranular.GetHandles();
  76. }
  77. else
  78. {
  79. return Enumerable.Repeat(buffer._memoryTracking.GetHandle(), 1);
  80. }
  81. });
  82. }
  83. if (_useGranular)
  84. {
  85. _memoryTrackingGranular = context.PhysicalMemory.BeginGranularTracking(address, size, baseHandles);
  86. }
  87. else
  88. {
  89. _memoryTracking = context.PhysicalMemory.BeginTracking(address, size);
  90. if (baseHandles != null)
  91. {
  92. _memoryTracking.Reprotect(false);
  93. foreach (IRegionHandle handle in baseHandles)
  94. {
  95. if (handle.Dirty)
  96. {
  97. _memoryTracking.Reprotect(true);
  98. }
  99. handle.Dispose();
  100. }
  101. }
  102. }
  103. _externalFlushDelegate = new RegionSignal(ExternalFlush);
  104. _loadDelegate = new Action<ulong, ulong>(LoadRegion);
  105. _modifiedDelegate = new Action<ulong, ulong>(RegionModified);
  106. }
  107. /// <summary>
  108. /// Gets a sub-range from the buffer, from a start address till the end of the buffer.
  109. /// </summary>
  110. /// <remarks>
  111. /// This can be used to bind and use sub-ranges of the buffer on the host API.
  112. /// </remarks>
  113. /// <param name="address">Start address of the sub-range, must be greater than or equal to the buffer address</param>
  114. /// <returns>The buffer sub-range</returns>
  115. public BufferRange GetRange(ulong address)
  116. {
  117. ulong offset = address - Address;
  118. return new BufferRange(Handle, (int)offset, (int)(Size - offset));
  119. }
  120. /// <summary>
  121. /// Gets a sub-range from the buffer.
  122. /// </summary>
  123. /// <remarks>
  124. /// This can be used to bind and use sub-ranges of the buffer on the host API.
  125. /// </remarks>
  126. /// <param name="address">Start address of the sub-range, must be greater than or equal to the buffer address</param>
  127. /// <param name="size">Size in bytes of the sub-range, must be less than or equal to the buffer size</param>
  128. /// <returns>The buffer sub-range</returns>
  129. public BufferRange GetRange(ulong address, ulong size)
  130. {
  131. int offset = (int)(address - Address);
  132. return new BufferRange(Handle, offset, (int)size);
  133. }
  134. /// <summary>
  135. /// Checks if a given range overlaps with the buffer.
  136. /// </summary>
  137. /// <param name="address">Start address of the range</param>
  138. /// <param name="size">Size in bytes of the range</param>
  139. /// <returns>True if the range overlaps, false otherwise</returns>
  140. public bool OverlapsWith(ulong address, ulong size)
  141. {
  142. return Address < address + size && address < EndAddress;
  143. }
  144. /// <summary>
  145. /// Checks if a given range is fully contained in the buffer.
  146. /// </summary>
  147. /// <param name="address">Start address of the range</param>
  148. /// <param name="size">Size in bytes of the range</param>
  149. /// <returns>True if the range is contained, false otherwise</returns>
  150. public bool FullyContains(ulong address, ulong size)
  151. {
  152. return address >= Address && address + size <= EndAddress;
  153. }
  154. /// <summary>
  155. /// Performs guest to host memory synchronization of the buffer data.
  156. /// </summary>
  157. /// <remarks>
  158. /// This causes the buffer data to be overwritten if a write was detected from the CPU,
  159. /// since the last call to this method.
  160. /// </remarks>
  161. /// <param name="address">Start address of the range to synchronize</param>
  162. /// <param name="size">Size in bytes of the range to synchronize</param>
  163. public void SynchronizeMemory(ulong address, ulong size)
  164. {
  165. if (_useGranular)
  166. {
  167. _memoryTrackingGranular.QueryModified(address, size, _modifiedDelegate, _context.SequenceNumber);
  168. }
  169. else
  170. {
  171. if (_context.SequenceNumber != _sequenceNumber && _memoryTracking.DirtyOrVolatile())
  172. {
  173. _memoryTracking.Reprotect();
  174. if (_modifiedRanges != null)
  175. {
  176. _modifiedRanges.ExcludeModifiedRegions(Address, Size, _loadDelegate);
  177. }
  178. else
  179. {
  180. _context.Renderer.SetBufferData(Handle, 0, _context.PhysicalMemory.GetSpan(Address, (int)Size));
  181. }
  182. _sequenceNumber = _context.SequenceNumber;
  183. }
  184. }
  185. }
  186. /// <summary>
  187. /// Ensure that the modified range list exists.
  188. /// </summary>
  189. private void EnsureRangeList()
  190. {
  191. if (_modifiedRanges == null)
  192. {
  193. _modifiedRanges = new BufferModifiedRangeList(_context);
  194. }
  195. }
  196. /// <summary>
  197. /// Signal that the given region of the buffer has been modified.
  198. /// </summary>
  199. /// <param name="address">The start address of the modified region</param>
  200. /// <param name="size">The size of the modified region</param>
  201. public void SignalModified(ulong address, ulong size)
  202. {
  203. EnsureRangeList();
  204. _modifiedRanges.SignalModified(address, size);
  205. if (!_syncActionRegistered)
  206. {
  207. _context.RegisterSyncAction(SyncAction);
  208. _syncActionRegistered = true;
  209. }
  210. }
  211. /// <summary>
  212. /// Indicate that mofifications in a given region of this buffer have been overwritten.
  213. /// </summary>
  214. /// <param name="address">The start address of the region</param>
  215. /// <param name="size">The size of the region</param>
  216. public void ClearModified(ulong address, ulong size)
  217. {
  218. if (_modifiedRanges != null)
  219. {
  220. _modifiedRanges.Clear(address, size);
  221. }
  222. }
  223. /// <summary>
  224. /// Action to be performed when a syncpoint is reached after modification.
  225. /// This will register read/write tracking to flush the buffer from GPU when its memory is used.
  226. /// </summary>
  227. private void SyncAction()
  228. {
  229. _syncActionRegistered = false;
  230. if (_useGranular)
  231. {
  232. _modifiedRanges.GetRanges(Address, Size, (address, size) =>
  233. {
  234. _memoryTrackingGranular.RegisterAction(address, size, _externalFlushDelegate);
  235. SynchronizeMemory(address, size);
  236. });
  237. }
  238. else
  239. {
  240. _memoryTracking.RegisterAction(_externalFlushDelegate);
  241. SynchronizeMemory(Address, Size);
  242. }
  243. }
  244. /// <summary>
  245. /// Inherit modified ranges from another buffer.
  246. /// </summary>
  247. /// <param name="from">The buffer to inherit from</param>
  248. public void InheritModifiedRanges(Buffer from)
  249. {
  250. if (from._modifiedRanges != null)
  251. {
  252. if (from._syncActionRegistered && !_syncActionRegistered)
  253. {
  254. _context.RegisterSyncAction(SyncAction);
  255. _syncActionRegistered = true;
  256. }
  257. EnsureRangeList();
  258. _modifiedRanges.InheritRanges(from._modifiedRanges, (ulong address, ulong size) =>
  259. {
  260. if (_useGranular)
  261. {
  262. _memoryTrackingGranular.RegisterAction(address, size, _externalFlushDelegate);
  263. }
  264. else
  265. {
  266. _memoryTracking.RegisterAction(_externalFlushDelegate);
  267. }
  268. });
  269. }
  270. }
  271. /// <summary>
  272. /// Determine if a given region of the buffer has been modified, and must be flushed.
  273. /// </summary>
  274. /// <param name="address">The start address of the region</param>
  275. /// <param name="size">The size of the region</param>
  276. /// <returns></returns>
  277. public bool IsModified(ulong address, ulong size)
  278. {
  279. if (_modifiedRanges != null)
  280. {
  281. return _modifiedRanges.HasRange(address, size);
  282. }
  283. return false;
  284. }
  285. /// <summary>
  286. /// Indicate that a region of the buffer was modified, and must be loaded from memory.
  287. /// </summary>
  288. /// <param name="mAddress">Start address of the modified region</param>
  289. /// <param name="mSize">Size of the modified region</param>
  290. private void RegionModified(ulong mAddress, ulong mSize)
  291. {
  292. if (mAddress < Address)
  293. {
  294. mAddress = Address;
  295. }
  296. ulong maxSize = Address + Size - mAddress;
  297. if (mSize > maxSize)
  298. {
  299. mSize = maxSize;
  300. }
  301. if (_modifiedRanges != null)
  302. {
  303. _modifiedRanges.ExcludeModifiedRegions(mAddress, mSize, _loadDelegate);
  304. }
  305. else
  306. {
  307. LoadRegion(mAddress, mSize);
  308. }
  309. }
  310. /// <summary>
  311. /// Load a region of the buffer from memory.
  312. /// </summary>
  313. /// <param name="mAddress">Start address of the modified region</param>
  314. /// <param name="mSize">Size of the modified region</param>
  315. private void LoadRegion(ulong mAddress, ulong mSize)
  316. {
  317. int offset = (int)(mAddress - Address);
  318. _context.Renderer.SetBufferData(Handle, offset, _context.PhysicalMemory.GetSpan(mAddress, (int)mSize));
  319. }
  320. /// <summary>
  321. /// Force a region of the buffer to be dirty. Avoids reprotection and nullifies sequence number check.
  322. /// </summary>
  323. /// <param name="mAddress">Start address of the modified region</param>
  324. /// <param name="mSize">Size of the region to force dirty</param>
  325. public void ForceDirty(ulong mAddress, ulong mSize)
  326. {
  327. if (_modifiedRanges != null)
  328. {
  329. _modifiedRanges.Clear(mAddress, mSize);
  330. }
  331. if (_useGranular)
  332. {
  333. _memoryTrackingGranular.ForceDirty(mAddress, mSize);
  334. }
  335. else
  336. {
  337. _memoryTracking.ForceDirty();
  338. _sequenceNumber--;
  339. }
  340. }
  341. /// <summary>
  342. /// Performs copy of all the buffer data from one buffer to another.
  343. /// </summary>
  344. /// <param name="destination">The destination buffer to copy the data into</param>
  345. /// <param name="dstOffset">The offset of the destination buffer to copy into</param>
  346. public void CopyTo(Buffer destination, int dstOffset)
  347. {
  348. _context.Renderer.Pipeline.CopyBuffer(Handle, destination.Handle, 0, dstOffset, (int)Size);
  349. }
  350. /// <summary>
  351. /// Flushes a range of the buffer.
  352. /// This writes the range data back into guest memory.
  353. /// </summary>
  354. /// <param name="address">Start address of the range</param>
  355. /// <param name="size">Size in bytes of the range</param>
  356. public void Flush(ulong address, ulong size)
  357. {
  358. int offset = (int)(address - Address);
  359. byte[] data = _context.Renderer.GetBufferData(Handle, offset, (int)size);
  360. // TODO: When write tracking shaders, they will need to be aware of changes in overlapping buffers.
  361. _context.PhysicalMemory.WriteUntracked(address, data);
  362. }
  363. /// <summary>
  364. /// Align a given address and size region to page boundaries.
  365. /// </summary>
  366. /// <param name="address">The start address of the region</param>
  367. /// <param name="size">The size of the region</param>
  368. /// <returns>The page aligned address and size</returns>
  369. private static (ulong address, ulong size) PageAlign(ulong address, ulong size)
  370. {
  371. ulong pageMask = MemoryManager.PageMask;
  372. ulong rA = address & ~pageMask;
  373. ulong rS = ((address + size + pageMask) & ~pageMask) - rA;
  374. return (rA, rS);
  375. }
  376. /// <summary>
  377. /// Flush modified ranges of the buffer from another thread.
  378. /// This will flush all modifications made before the active SyncNumber was set, and may block to wait for GPU sync.
  379. /// </summary>
  380. /// <param name="address">Address of the memory action</param>
  381. /// <param name="size">Size in bytes</param>
  382. public void ExternalFlush(ulong address, ulong size)
  383. {
  384. _context.Renderer.BackgroundContextAction(() =>
  385. {
  386. var ranges = _modifiedRanges;
  387. if (ranges != null)
  388. {
  389. (address, size) = PageAlign(address, size);
  390. ranges.WaitForAndGetRanges(address, size, Flush);
  391. }
  392. });
  393. }
  394. /// <summary>
  395. /// Called when part of the memory for this buffer has been unmapped.
  396. /// Calls are from non-GPU threads.
  397. /// </summary>
  398. /// <param name="address">Start address of the unmapped region</param>
  399. /// <param name="size">Size of the unmapped region</param>
  400. public void Unmapped(ulong address, ulong size)
  401. {
  402. _modifiedRanges?.Clear(address, size);
  403. UnmappedSequence++;
  404. }
  405. /// <summary>
  406. /// Disposes the host buffer's data, not its tracking handles.
  407. /// </summary>
  408. public void DisposeData()
  409. {
  410. _modifiedRanges?.Clear();
  411. _context.Renderer.DeleteBuffer(Handle);
  412. UnmappedSequence++;
  413. }
  414. /// <summary>
  415. /// Disposes the host buffer.
  416. /// </summary>
  417. public void Dispose()
  418. {
  419. _memoryTrackingGranular?.Dispose();
  420. _memoryTracking?.Dispose();
  421. DisposeData();
  422. }
  423. }
  424. }