Buffer.cs 19 KB

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