TrackingTests.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425
  1. using NUnit.Framework;
  2. using Ryujinx.Memory.Tracking;
  3. using System;
  4. using System.Collections.Generic;
  5. using System.Diagnostics;
  6. using System.Threading;
  7. namespace Ryujinx.Memory.Tests
  8. {
  9. public class TrackingTests
  10. {
  11. private const int RndCnt = 3;
  12. private const ulong MemorySize = 0x8000;
  13. private const int PageSize = 4096;
  14. private MemoryBlock _memoryBlock;
  15. private MemoryTracking _tracking;
  16. private MockVirtualMemoryManager _memoryManager;
  17. [SetUp]
  18. public void Setup()
  19. {
  20. _memoryBlock = new MemoryBlock(MemorySize);
  21. _memoryManager = new MockVirtualMemoryManager(MemorySize, PageSize);
  22. _tracking = new MemoryTracking(_memoryManager, _memoryBlock, PageSize);
  23. }
  24. [TearDown]
  25. public void Teardown()
  26. {
  27. _memoryBlock.Dispose();
  28. }
  29. private bool TestSingleWrite(RegionHandle handle, ulong address, ulong size, bool physical = false)
  30. {
  31. handle.Reprotect();
  32. if (physical)
  33. {
  34. _tracking.PhysicalMemoryEvent(address, true);
  35. }
  36. else
  37. {
  38. _tracking.VirtualMemoryEvent(address, size, true);
  39. }
  40. return handle.Dirty;
  41. }
  42. [Test]
  43. public void SingleRegion()
  44. {
  45. RegionHandle handle = _tracking.BeginTracking(0, PageSize);
  46. (ulong address, ulong size)? readTrackingTriggered = null;
  47. handle.RegisterAction((address, size) =>
  48. {
  49. readTrackingTriggered = (address, size);
  50. });
  51. bool dirtyInitial = handle.Dirty;
  52. Assert.True(dirtyInitial); // Handle starts dirty.
  53. handle.Reprotect();
  54. bool dirtyAfterReprotect = handle.Dirty;
  55. Assert.False(dirtyAfterReprotect); // Handle is no longer dirty.
  56. _tracking.VirtualMemoryEvent(PageSize * 2, 4, true);
  57. _tracking.VirtualMemoryEvent(PageSize * 2, 4, false);
  58. bool dirtyAfterUnrelatedReadWrite = handle.Dirty;
  59. Assert.False(dirtyAfterUnrelatedReadWrite); // Not dirtied, as the write was to an unrelated address.
  60. Assert.IsNull(readTrackingTriggered); // Hasn't been triggered yet
  61. _tracking.VirtualMemoryEvent(0, 4, false);
  62. bool dirtyAfterRelatedRead = handle.Dirty;
  63. Assert.False(dirtyAfterRelatedRead); // Only triggers on write.
  64. Assert.AreEqual(readTrackingTriggered, (0UL, 4UL)); // Read action was triggered.
  65. readTrackingTriggered = null;
  66. _tracking.VirtualMemoryEvent(0, 4, true);
  67. bool dirtyAfterRelatedWrite = handle.Dirty;
  68. Assert.True(dirtyAfterRelatedWrite); // Dirty flag should now be set.
  69. _tracking.VirtualMemoryEvent(4, 4, true);
  70. bool dirtyAfterRelatedWrite2 = handle.Dirty;
  71. Assert.True(dirtyAfterRelatedWrite2); // Dirty flag should still be set.
  72. handle.Reprotect();
  73. bool dirtyAfterReprotect2 = handle.Dirty;
  74. Assert.False(dirtyAfterReprotect2); // Handle is no longer dirty.
  75. handle.Dispose();
  76. bool dirtyAfterDispose = TestSingleWrite(handle, 0, 4);
  77. Assert.False(dirtyAfterDispose); // Handle cannot be triggered when disposed
  78. bool dirtyAfterDispose2 = TestSingleWrite(handle, 0, 4, true);
  79. Assert.False(dirtyAfterDispose2);
  80. }
  81. [Test]
  82. public void OverlappingRegions()
  83. {
  84. RegionHandle allHandle = _tracking.BeginTracking(0, PageSize * 16);
  85. allHandle.Reprotect();
  86. (ulong address, ulong size)? readTrackingTriggeredAll = null;
  87. Action registerReadAction = () =>
  88. {
  89. readTrackingTriggeredAll = null;
  90. allHandle.RegisterAction((address, size) =>
  91. {
  92. readTrackingTriggeredAll = (address, size);
  93. });
  94. };
  95. registerReadAction();
  96. // Create 16 page sized handles contained within the allHandle.
  97. RegionHandle[] containedHandles = new RegionHandle[16];
  98. for (int i = 0; i < 16; i++)
  99. {
  100. containedHandles[i] = _tracking.BeginTracking((ulong)i * PageSize, PageSize);
  101. containedHandles[i].Reprotect();
  102. }
  103. for (int i = 0; i < 16; i++)
  104. {
  105. // No handles are dirty.
  106. Assert.False(allHandle.Dirty);
  107. Assert.IsNull(readTrackingTriggeredAll);
  108. for (int j = 0; j < 16; j++)
  109. {
  110. Assert.False(containedHandles[j].Dirty);
  111. }
  112. _tracking.VirtualMemoryEvent((ulong)i * PageSize, 1, true);
  113. // Only the handle covering the entire range and the relevant contained handle are dirty.
  114. Assert.True(allHandle.Dirty);
  115. Assert.AreEqual(readTrackingTriggeredAll, ((ulong)i * PageSize, 1UL)); // Triggered read tracking
  116. for (int j = 0; j < 16; j++)
  117. {
  118. if (j == i)
  119. {
  120. Assert.True(containedHandles[j].Dirty);
  121. }
  122. else
  123. {
  124. Assert.False(containedHandles[j].Dirty);
  125. }
  126. }
  127. // Clear flags and reset read action.
  128. registerReadAction();
  129. allHandle.Reprotect();
  130. containedHandles[i].Reprotect();
  131. }
  132. }
  133. [Test]
  134. public void PageAlignment(
  135. [Values(1ul, 512ul, 2048ul, 4096ul, 65536ul)] [Random(1ul, 65536ul, RndCnt)] ulong address,
  136. [Values(1ul, 4ul, 1024ul, 4096ul, 65536ul)] [Random(1ul, 65536ul, RndCnt)] ulong size)
  137. {
  138. ulong alignedStart = (address / PageSize) * PageSize;
  139. ulong alignedEnd = ((address + size + PageSize - 1) / PageSize) * PageSize;
  140. ulong alignedSize = alignedEnd - alignedStart;
  141. RegionHandle handle = _tracking.BeginTracking(address, size);
  142. // Anywhere inside the pages the region is contained on should trigger.
  143. bool originalRangeTriggers = TestSingleWrite(handle, address, size);
  144. Assert.True(originalRangeTriggers);
  145. bool alignedRangeTriggers = TestSingleWrite(handle, alignedStart, alignedSize);
  146. Assert.True(alignedRangeTriggers);
  147. bool alignedStartTriggers = TestSingleWrite(handle, alignedStart, 1);
  148. Assert.True(alignedStartTriggers);
  149. bool alignedEndTriggers = TestSingleWrite(handle, alignedEnd - 1, 1);
  150. Assert.True(alignedEndTriggers);
  151. // Outside the tracked range should not trigger.
  152. bool alignedBeforeTriggers = TestSingleWrite(handle, alignedStart - 1, 1);
  153. Assert.False(alignedBeforeTriggers);
  154. bool alignedAfterTriggers = TestSingleWrite(handle, alignedEnd, 1);
  155. Assert.False(alignedAfterTriggers);
  156. }
  157. [Test, Timeout(1000)]
  158. public void Multithreading()
  159. {
  160. // Multithreading sanity test
  161. // Multiple threads can easily read/write memory regions from any existing handle.
  162. // Handles can also be owned by different threads, though they should have one owner thread.
  163. // Handles can be created and disposed at any time, by any thread.
  164. // This test should not throw or deadlock due to invalid state.
  165. const int threadCount = 1;
  166. const int handlesPerThread = 16;
  167. long finishedTime = 0;
  168. RegionHandle[] handles = new RegionHandle[threadCount * handlesPerThread];
  169. Random globalRand = new Random();
  170. for (int i = 0; i < handles.Length; i++)
  171. {
  172. handles[i] = _tracking.BeginTracking((ulong)i * PageSize, PageSize);
  173. handles[i].Reprotect();
  174. }
  175. List<Thread> testThreads = new List<Thread>();
  176. // Dirty flag consumer threads
  177. int dirtyFlagReprotects = 0;
  178. for (int i = 0; i < threadCount; i++)
  179. {
  180. int randSeed = i;
  181. testThreads.Add(new Thread(() =>
  182. {
  183. int handleBase = randSeed * handlesPerThread;
  184. while (Stopwatch.GetTimestamp() < finishedTime)
  185. {
  186. Random random = new Random(randSeed);
  187. RegionHandle handle = handles[handleBase + random.Next(handlesPerThread)];
  188. if (handle.Dirty)
  189. {
  190. handle.Reprotect();
  191. Interlocked.Increment(ref dirtyFlagReprotects);
  192. }
  193. }
  194. }));
  195. }
  196. // Write trigger threads
  197. int writeTriggers = 0;
  198. for (int i = 0; i < threadCount; i++)
  199. {
  200. int randSeed = i;
  201. testThreads.Add(new Thread(() =>
  202. {
  203. Random random = new Random(randSeed);
  204. ulong handleBase = (ulong)(randSeed * handlesPerThread * PageSize);
  205. while (Stopwatch.GetTimestamp() < finishedTime)
  206. {
  207. _tracking.VirtualMemoryEvent(handleBase + (ulong)random.Next(PageSize * handlesPerThread), PageSize / 2, true);
  208. Interlocked.Increment(ref writeTriggers);
  209. }
  210. }));
  211. }
  212. // Handle create/delete threads
  213. int handleLifecycles = 0;
  214. for (int i = 0; i < threadCount; i++)
  215. {
  216. int randSeed = i;
  217. testThreads.Add(new Thread(() =>
  218. {
  219. int maxAddress = threadCount * handlesPerThread * PageSize;
  220. Random random = new Random(randSeed + 512);
  221. while (Stopwatch.GetTimestamp() < finishedTime)
  222. {
  223. RegionHandle handle = _tracking.BeginTracking((ulong)random.Next(maxAddress), (ulong)random.Next(65536));
  224. handle.Dispose();
  225. Interlocked.Increment(ref handleLifecycles);
  226. }
  227. }));
  228. }
  229. finishedTime = Stopwatch.GetTimestamp() + Stopwatch.Frequency / 2; // Run for 500ms;
  230. foreach (Thread thread in testThreads)
  231. {
  232. thread.Start();
  233. }
  234. foreach (Thread thread in testThreads)
  235. {
  236. thread.Join();
  237. }
  238. Assert.Greater(dirtyFlagReprotects, 10);
  239. Assert.Greater(writeTriggers, 10);
  240. Assert.Greater(handleLifecycles, 10);
  241. }
  242. [Test]
  243. public void ReadActionThreadConsumption()
  244. {
  245. // Read actions should only be triggered once for each registration.
  246. // The implementation should use an interlocked exchange to make sure other threads can't get the action.
  247. RegionHandle handle = _tracking.BeginTracking(0, PageSize);
  248. int triggeredCount = 0;
  249. int registeredCount = 0;
  250. int signalThreadsDone = 0;
  251. bool isRegistered = false;
  252. Action registerReadAction = () =>
  253. {
  254. registeredCount++;
  255. handle.RegisterAction((address, size) =>
  256. {
  257. isRegistered = false;
  258. Interlocked.Increment(ref triggeredCount);
  259. });
  260. };
  261. const int threadCount = 16;
  262. const int iterationCount = 10000;
  263. Thread[] signalThreads = new Thread[threadCount];
  264. for (int i = 0; i < threadCount; i++)
  265. {
  266. int randSeed = i;
  267. signalThreads[i] = new Thread(() =>
  268. {
  269. Random random = new Random(randSeed);
  270. for (int j = 0; j < iterationCount; j++)
  271. {
  272. _tracking.VirtualMemoryEvent((ulong)random.Next(PageSize), 4, false);
  273. }
  274. Interlocked.Increment(ref signalThreadsDone);
  275. });
  276. }
  277. for (int i = 0; i < threadCount; i++)
  278. {
  279. signalThreads[i].Start();
  280. }
  281. while (signalThreadsDone != -1)
  282. {
  283. if (signalThreadsDone == threadCount)
  284. {
  285. signalThreadsDone = -1;
  286. }
  287. if (!isRegistered)
  288. {
  289. isRegistered = true;
  290. registerReadAction();
  291. }
  292. }
  293. // The action should trigger exactly once for every registration,
  294. // then we register once after all the threads signalling it cease.
  295. Assert.AreEqual(registeredCount, triggeredCount + 1);
  296. }
  297. [Test]
  298. public void PhysicalMemoryMapping()
  299. {
  300. // Tracking is done in the virtual space usually, but we also support tracking on physical regions.
  301. // The physical regions that make up a virtual region are determined when the region is created,
  302. // or when a mapping changes.
  303. // These tests verify that the region cannot be signalled after unmapping, and can after remapping.
  304. RegionHandle handle = _tracking.BeginTracking(PageSize, PageSize);
  305. Assert.True(handle.Dirty);
  306. bool trackedWriteTriggers = TestSingleWrite(handle, PageSize, 1, true);
  307. Assert.True(trackedWriteTriggers);
  308. _memoryManager.NoMappings = true;
  309. _tracking.Unmap(PageSize, PageSize);
  310. bool unmappedWriteTriggers = TestSingleWrite(handle, PageSize, 1, true);
  311. Assert.False(unmappedWriteTriggers);
  312. _memoryManager.NoMappings = false;
  313. _tracking.Map(PageSize, PageSize, PageSize);
  314. bool remappedWriteTriggers = TestSingleWrite(handle, PageSize, 1, true);
  315. Assert.True(remappedWriteTriggers);
  316. }
  317. [Test]
  318. public void DisposeHandles()
  319. {
  320. // Ensure that disposed handles correctly remove their virtual and physical regions.
  321. RegionHandle handle = _tracking.BeginTracking(0, PageSize);
  322. handle.Reprotect();
  323. Assert.AreEqual((1, 1), _tracking.GetRegionCounts());
  324. handle.Dispose();
  325. Assert.AreEqual((0, 0), _tracking.GetRegionCounts());
  326. // Two handles, small entirely contains big.
  327. // We expect there to be three regions after creating both, one for the small region and two covering the big one around it.
  328. // Regions are always split to avoid overlapping, which is why there are three instead of two.
  329. RegionHandle handleSmall = _tracking.BeginTracking(PageSize, PageSize);
  330. RegionHandle handleBig = _tracking.BeginTracking(0, PageSize * 4);
  331. Assert.AreEqual((3, 3), _tracking.GetRegionCounts());
  332. // After disposing the big region, only the small one will remain.
  333. handleBig.Dispose();
  334. Assert.AreEqual((1, 1), _tracking.GetRegionCounts());
  335. handleSmall.Dispose();
  336. Assert.AreEqual((0, 0), _tracking.GetRegionCounts());
  337. }
  338. }
  339. }