BufferModifiedRangeList.cs 21 KB

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