Buffer.cs 19 KB

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