BufferModifiedRangeList.cs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557
  1. using Ryujinx.Common.Pools;
  2. using Ryujinx.Memory.Range;
  3. using System;
  4. using System.Linq;
  5. namespace Ryujinx.Graphics.Gpu.Memory
  6. {
  7. /// <summary>
  8. /// A range within a buffer that has been modified by the GPU.
  9. /// </summary>
  10. class BufferModifiedRange : IRange
  11. {
  12. /// <summary>
  13. /// Start address of the range in guest memory.
  14. /// </summary>
  15. public ulong Address { get; }
  16. /// <summary>
  17. /// Size of the range in bytes.
  18. /// </summary>
  19. public ulong Size { get; }
  20. /// <summary>
  21. /// End address of the range in guest memory.
  22. /// </summary>
  23. public ulong EndAddress => Address + Size;
  24. /// <summary>
  25. /// The GPU sync number at the time of the last modification.
  26. /// </summary>
  27. public ulong SyncNumber { get; internal set; }
  28. /// <summary>
  29. /// The range list that originally owned this range.
  30. /// </summary>
  31. public BufferModifiedRangeList Parent { get; internal set; }
  32. /// <summary>
  33. /// Creates a new instance of a modified range.
  34. /// </summary>
  35. /// <param name="address">Start address of the range</param>
  36. /// <param name="size">Size of the range in bytes</param>
  37. /// <param name="syncNumber">The GPU sync number at the time of creation</param>
  38. /// <param name="parent">The range list that owns this range</param>
  39. public BufferModifiedRange(ulong address, ulong size, ulong syncNumber, BufferModifiedRangeList parent)
  40. {
  41. Address = address;
  42. Size = size;
  43. SyncNumber = syncNumber;
  44. Parent = parent;
  45. }
  46. /// <summary>
  47. /// Checks if a given range overlaps with the modified range.
  48. /// </summary>
  49. /// <param name="address">Start address of the range</param>
  50. /// <param name="size">Size in bytes of the range</param>
  51. /// <returns>True if the range overlaps, false otherwise</returns>
  52. public bool OverlapsWith(ulong address, ulong size)
  53. {
  54. return Address < address + size && address < EndAddress;
  55. }
  56. }
  57. /// <summary>
  58. /// A structure used to track GPU modified ranges within a buffer.
  59. /// </summary>
  60. class BufferModifiedRangeList : RangeList<BufferModifiedRange>
  61. {
  62. private const int BackingInitialSize = 8;
  63. private readonly GpuContext _context;
  64. private readonly Buffer _parent;
  65. private readonly BufferFlushAction _flushAction;
  66. private BufferMigration _source;
  67. private BufferModifiedRangeList _migrationTarget;
  68. private readonly object _lock = new();
  69. /// <summary>
  70. /// Whether the modified range list has any entries or not.
  71. /// </summary>
  72. public bool HasRanges
  73. {
  74. get
  75. {
  76. lock (_lock)
  77. {
  78. return Count > 0;
  79. }
  80. }
  81. }
  82. /// <summary>
  83. /// Creates a new instance of a modified range list.
  84. /// </summary>
  85. /// <param name="context">GPU context that the buffer range list belongs to</param>
  86. /// <param name="parent">The parent buffer that owns this range list</param>
  87. /// <param name="flushAction">The flush action for the parent buffer</param>
  88. public BufferModifiedRangeList(GpuContext context, Buffer parent, BufferFlushAction flushAction) : base(BackingInitialSize)
  89. {
  90. _context = context;
  91. _parent = parent;
  92. _flushAction = flushAction;
  93. }
  94. /// <summary>
  95. /// Given an input range, calls the given action with sub-ranges which exclude any of the modified regions.
  96. /// </summary>
  97. /// <param name="address">Start address of the query range</param>
  98. /// <param name="size">Size of the query range in bytes</param>
  99. /// <param name="action">Action to perform for each remaining sub-range of the input range</param>
  100. public void ExcludeModifiedRegions(ulong address, ulong size, Action<ulong, ulong> action)
  101. {
  102. lock (_lock)
  103. {
  104. // Slices a given region using the modified regions in the list. Calls the action for the new slices.
  105. ref var overlaps = ref ThreadStaticArray<BufferModifiedRange>.Get();
  106. int count = FindOverlapsNonOverlapping(address, size, ref overlaps);
  107. for (int i = 0; i < count; i++)
  108. {
  109. BufferModifiedRange overlap = overlaps[i];
  110. if (overlap.Address > address)
  111. {
  112. // The start of the remaining region is uncovered by this overlap. Call the action for it.
  113. action(address, overlap.Address - address);
  114. }
  115. // Remaining region is after this overlap.
  116. size -= overlap.EndAddress - address;
  117. address = overlap.EndAddress;
  118. }
  119. if ((long)size > 0)
  120. {
  121. // If there is any region left after removing the overlaps, signal it.
  122. action(address, size);
  123. }
  124. }
  125. }
  126. /// <summary>
  127. /// Signal that a region of the buffer has been modified, and add the new region to the range list.
  128. /// Any overlapping ranges will be (partially) removed.
  129. /// </summary>
  130. /// <param name="address">Start address of the modified region</param>
  131. /// <param name="size">Size of the modified region in bytes</param>
  132. public void SignalModified(ulong address, ulong size)
  133. {
  134. // Must lock, as this can affect flushes from the background thread.
  135. lock (_lock)
  136. {
  137. // We may overlap with some existing modified regions. They must be cut into by the new entry.
  138. ref var overlaps = ref ThreadStaticArray<BufferModifiedRange>.Get();
  139. int count = FindOverlapsNonOverlapping(address, size, ref overlaps);
  140. ulong endAddress = address + size;
  141. ulong syncNumber = _context.SyncNumber;
  142. for (int i = 0; i < count; i++)
  143. {
  144. // The overlaps must be removed or split.
  145. BufferModifiedRange overlap = overlaps[i];
  146. if (overlap.Address == address && overlap.Size == size)
  147. {
  148. // Region already exists. Just update the existing sync number.
  149. overlap.SyncNumber = syncNumber;
  150. overlap.Parent = this;
  151. return;
  152. }
  153. Remove(overlap);
  154. if (overlap.Address < address && overlap.EndAddress > address)
  155. {
  156. // A split item must be created behind this overlap.
  157. Add(new BufferModifiedRange(overlap.Address, address - overlap.Address, overlap.SyncNumber, overlap.Parent));
  158. }
  159. if (overlap.Address < endAddress && overlap.EndAddress > endAddress)
  160. {
  161. // A split item must be created after this overlap.
  162. Add(new BufferModifiedRange(endAddress, overlap.EndAddress - endAddress, overlap.SyncNumber, overlap.Parent));
  163. }
  164. }
  165. Add(new BufferModifiedRange(address, size, syncNumber, this));
  166. }
  167. }
  168. /// <summary>
  169. /// Gets modified ranges within the specified region, and then fires the given action for each range individually.
  170. /// </summary>
  171. /// <param name="address">Start address to query</param>
  172. /// <param name="size">Size to query</param>
  173. /// <param name="syncNumber">Sync number required for a range to be signalled</param>
  174. /// <param name="rangeAction">The action to call for each modified range</param>
  175. public void GetRangesAtSync(ulong address, ulong size, ulong syncNumber, Action<ulong, ulong> rangeAction)
  176. {
  177. int count = 0;
  178. ref var overlaps = ref ThreadStaticArray<BufferModifiedRange>.Get();
  179. // Range list must be consistent for this operation.
  180. lock (_lock)
  181. {
  182. count = FindOverlapsNonOverlapping(address, size, ref overlaps);
  183. }
  184. for (int i = 0; i < count; i++)
  185. {
  186. BufferModifiedRange overlap = overlaps[i];
  187. if (overlap.SyncNumber == syncNumber)
  188. {
  189. rangeAction(overlap.Address, overlap.Size);
  190. }
  191. }
  192. }
  193. /// <summary>
  194. /// Gets modified ranges within the specified region, and then fires the given action for each range individually.
  195. /// </summary>
  196. /// <param name="address">Start address to query</param>
  197. /// <param name="size">Size to query</param>
  198. /// <param name="rangeAction">The action to call for each modified range</param>
  199. public void GetRanges(ulong address, ulong size, Action<ulong, ulong> rangeAction)
  200. {
  201. int count = 0;
  202. ref var overlaps = ref ThreadStaticArray<BufferModifiedRange>.Get();
  203. // Range list must be consistent for this operation.
  204. lock (_lock)
  205. {
  206. count = FindOverlapsNonOverlapping(address, size, ref overlaps);
  207. }
  208. for (int i = 0; i < count; i++)
  209. {
  210. BufferModifiedRange overlap = overlaps[i];
  211. rangeAction(overlap.Address, overlap.Size);
  212. }
  213. }
  214. /// <summary>
  215. /// Queries if a range exists within the specified region.
  216. /// </summary>
  217. /// <param name="address">Start address to query</param>
  218. /// <param name="size">Size to query</param>
  219. /// <returns>True if a range exists in the specified region, false otherwise</returns>
  220. public bool HasRange(ulong address, ulong size)
  221. {
  222. // Range list must be consistent for this operation.
  223. lock (_lock)
  224. {
  225. return FindOverlapsNonOverlapping(address, size, ref ThreadStaticArray<BufferModifiedRange>.Get()) > 0;
  226. }
  227. }
  228. /// <summary>
  229. /// Performs the given range action, or one from a migration that overlaps and has not synced yet.
  230. /// </summary>
  231. /// <param name="offset">The offset to pass to the action</param>
  232. /// <param name="size">The size to pass to the action</param>
  233. /// <param name="syncNumber">The sync number that has been reached</param>
  234. /// <param name="rangeAction">The action to perform</param>
  235. public void RangeActionWithMigration(ulong offset, ulong size, ulong syncNumber, BufferFlushAction rangeAction)
  236. {
  237. if (_source != null)
  238. {
  239. _source.RangeActionWithMigration(offset, size, syncNumber, rangeAction);
  240. }
  241. else
  242. {
  243. rangeAction(offset, size, syncNumber);
  244. }
  245. }
  246. /// <summary>
  247. /// Removes modified ranges ready by the sync number from the list, and flushes their buffer data within a given address range.
  248. /// </summary>
  249. /// <param name="overlaps">Overlapping ranges to check</param>
  250. /// <param name="rangeCount">Number of overlapping ranges</param>
  251. /// <param name="highestDiff">The highest difference between an overlapping range's sync number and the current one</param>
  252. /// <param name="currentSync">The current sync number</param>
  253. /// <param name="address">The start address of the flush range</param>
  254. /// <param name="endAddress">The end address of the flush range</param>
  255. private void RemoveRangesAndFlush(
  256. BufferModifiedRange[] overlaps,
  257. int rangeCount,
  258. long highestDiff,
  259. ulong currentSync,
  260. ulong address,
  261. ulong endAddress)
  262. {
  263. lock (_lock)
  264. {
  265. if (_migrationTarget == null)
  266. {
  267. ulong waitSync = currentSync + (ulong)highestDiff;
  268. for (int i = 0; i < rangeCount; i++)
  269. {
  270. BufferModifiedRange overlap = overlaps[i];
  271. long diff = (long)(overlap.SyncNumber - currentSync);
  272. if (diff <= highestDiff)
  273. {
  274. ulong clampAddress = Math.Max(address, overlap.Address);
  275. ulong clampEnd = Math.Min(endAddress, overlap.EndAddress);
  276. ClearPart(overlap, clampAddress, clampEnd);
  277. RangeActionWithMigration(clampAddress, clampEnd - clampAddress, waitSync, _flushAction);
  278. }
  279. }
  280. return;
  281. }
  282. }
  283. // There is a migration target to call instead. This can't be changed after set so accessing it outside the lock is fine.
  284. _migrationTarget.RemoveRangesAndFlush(overlaps, rangeCount, highestDiff, currentSync, address, endAddress);
  285. }
  286. /// <summary>
  287. /// Gets modified ranges within the specified region, waits on ones from a previous sync number,
  288. /// and then fires the flush action for each range individually.
  289. /// </summary>
  290. /// <remarks>
  291. /// This function assumes it is called from the background thread.
  292. /// Modifications from the current sync number are ignored because the guest should not expect them to be available yet.
  293. /// They will remain reserved, so that any data sync prioritizes the data in the GPU.
  294. /// </remarks>
  295. /// <param name="address">Start address to query</param>
  296. /// <param name="size">Size to query</param>
  297. public void WaitForAndFlushRanges(ulong address, ulong size)
  298. {
  299. ulong endAddress = address + size;
  300. ulong currentSync = _context.SyncNumber;
  301. int rangeCount = 0;
  302. ref var overlaps = ref ThreadStaticArray<BufferModifiedRange>.Get();
  303. // Range list must be consistent for this operation
  304. lock (_lock)
  305. {
  306. if (_migrationTarget != null)
  307. {
  308. rangeCount = -1;
  309. }
  310. else
  311. {
  312. rangeCount = FindOverlapsNonOverlapping(address, size, ref overlaps);
  313. }
  314. }
  315. if (rangeCount == -1)
  316. {
  317. _migrationTarget.WaitForAndFlushRanges(address, size);
  318. return;
  319. }
  320. else if (rangeCount == 0)
  321. {
  322. return;
  323. }
  324. // First, determine which syncpoint to wait on.
  325. // This is the latest syncpoint that is not equal to the current sync.
  326. long highestDiff = long.MinValue;
  327. for (int i = 0; i < rangeCount; i++)
  328. {
  329. BufferModifiedRange overlap = overlaps[i];
  330. long diff = (long)(overlap.SyncNumber - currentSync);
  331. if (diff < 0 && diff > highestDiff)
  332. {
  333. highestDiff = diff;
  334. }
  335. }
  336. if (highestDiff == long.MinValue)
  337. {
  338. return;
  339. }
  340. // Wait for the syncpoint.
  341. _context.Renderer.WaitSync(currentSync + (ulong)highestDiff);
  342. RemoveRangesAndFlush(overlaps, rangeCount, highestDiff, currentSync, address, endAddress);
  343. }
  344. /// <summary>
  345. /// Inherit ranges from another modified range list.
  346. /// </summary>
  347. /// <remarks>
  348. /// Assumes that ranges will be inherited in address ascending order.
  349. /// </remarks>
  350. /// <param name="ranges">The range list to inherit from</param>
  351. /// <param name="registerRangeAction">The action to call for each modified range</param>
  352. public void InheritRanges(BufferModifiedRangeList ranges, Action<ulong, ulong> registerRangeAction)
  353. {
  354. BufferModifiedRange[] inheritRanges;
  355. lock (ranges._lock)
  356. {
  357. inheritRanges = ranges.ToArray();
  358. lock (_lock)
  359. {
  360. // Copy over the migration from the previous range list
  361. BufferMigration oldMigration = ranges._source;
  362. BufferMigrationSpan span = new BufferMigrationSpan(ranges._parent, ranges._flushAction, oldMigration);
  363. ranges._parent.IncrementReferenceCount();
  364. if (_source == null)
  365. {
  366. // Create a new migration.
  367. _source = new BufferMigration(new BufferMigrationSpan[] { span }, this, _context.SyncNumber);
  368. _context.RegisterBufferMigration(_source);
  369. }
  370. else
  371. {
  372. // Extend the migration
  373. _source.AddSpanToEnd(span);
  374. }
  375. ranges._migrationTarget = this;
  376. foreach (BufferModifiedRange range in inheritRanges)
  377. {
  378. Add(range);
  379. }
  380. }
  381. }
  382. ulong currentSync = _context.SyncNumber;
  383. foreach (BufferModifiedRange range in inheritRanges)
  384. {
  385. if (range.SyncNumber != currentSync)
  386. {
  387. registerRangeAction(range.Address, range.Size);
  388. }
  389. }
  390. }
  391. /// <summary>
  392. /// Register a migration from previous buffer storage. This migration is from a snapshot of the buffer's
  393. /// current handle to its handle in the future, and is assumed to be complete when the sync action completes.
  394. /// When the migration completes, the handle is disposed.
  395. /// </summary>
  396. public void SelfMigration()
  397. {
  398. lock (_lock)
  399. {
  400. BufferMigrationSpan span = new(_parent, _parent.GetSnapshotDisposeAction(), _parent.GetSnapshotFlushAction(), _source);
  401. BufferMigration migration = new(new BufferMigrationSpan[] { span }, this, _context.SyncNumber);
  402. // Migration target is used to redirect flush actions to the latest range list,
  403. // so we don't need to set it here. (this range list is still the latest)
  404. _context.RegisterBufferMigration(migration);
  405. _source = migration;
  406. }
  407. }
  408. /// <summary>
  409. /// Removes a source buffer migration, indicating its copy has completed.
  410. /// </summary>
  411. /// <param name="migration">The migration to remove</param>
  412. public void RemoveMigration(BufferMigration migration)
  413. {
  414. lock (_lock)
  415. {
  416. if (_source == migration)
  417. {
  418. _source = null;
  419. }
  420. }
  421. }
  422. private void ClearPart(BufferModifiedRange overlap, ulong address, ulong endAddress)
  423. {
  424. Remove(overlap);
  425. // If the overlap extends outside of the clear range, make sure those parts still exist.
  426. if (overlap.Address < address)
  427. {
  428. Add(new BufferModifiedRange(overlap.Address, address - overlap.Address, overlap.SyncNumber, overlap.Parent));
  429. }
  430. if (overlap.EndAddress > endAddress)
  431. {
  432. Add(new BufferModifiedRange(endAddress, overlap.EndAddress - endAddress, overlap.SyncNumber, overlap.Parent));
  433. }
  434. }
  435. /// <summary>
  436. /// Clear modified ranges within the specified area.
  437. /// </summary>
  438. /// <param name="address">Start address to clear</param>
  439. /// <param name="size">Size to clear</param>
  440. public void Clear(ulong address, ulong size)
  441. {
  442. lock (_lock)
  443. {
  444. // This function can be called from any thread, so it cannot use the arrays for background or foreground.
  445. BufferModifiedRange[] toClear = new BufferModifiedRange[1];
  446. int rangeCount = FindOverlapsNonOverlapping(address, size, ref toClear);
  447. ulong endAddress = address + size;
  448. for (int i = 0; i < rangeCount; i++)
  449. {
  450. BufferModifiedRange overlap = toClear[i];
  451. ClearPart(overlap, address, endAddress);
  452. }
  453. }
  454. }
  455. /// <summary>
  456. /// Clear all modified ranges.
  457. /// </summary>
  458. public void Clear()
  459. {
  460. lock (_lock)
  461. {
  462. Count = 0;
  463. }
  464. }
  465. }
  466. }