Buffer.cs 17 KB

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