BufferModifiedRangeList.cs 19 KB

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