TrackingTests.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509
  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, PageSize);
  23. }
  24. [TearDown]
  25. public void Teardown()
  26. {
  27. _memoryBlock.Dispose();
  28. }
  29. private bool TestSingleWrite(RegionHandle handle, ulong address, ulong size)
  30. {
  31. handle.Reprotect();
  32. _tracking.VirtualMemoryEvent(address, size, true);
  33. return handle.Dirty;
  34. }
  35. [Test]
  36. public void SingleRegion()
  37. {
  38. RegionHandle handle = _tracking.BeginTracking(0, PageSize);
  39. (ulong address, ulong size)? readTrackingTriggered = null;
  40. handle.RegisterAction((address, size) =>
  41. {
  42. readTrackingTriggered = (address, size);
  43. });
  44. bool dirtyInitial = handle.Dirty;
  45. Assert.True(dirtyInitial); // Handle starts dirty.
  46. handle.Reprotect();
  47. bool dirtyAfterReprotect = handle.Dirty;
  48. Assert.False(dirtyAfterReprotect); // Handle is no longer dirty.
  49. _tracking.VirtualMemoryEvent(PageSize * 2, 4, true);
  50. _tracking.VirtualMemoryEvent(PageSize * 2, 4, false);
  51. bool dirtyAfterUnrelatedReadWrite = handle.Dirty;
  52. Assert.False(dirtyAfterUnrelatedReadWrite); // Not dirtied, as the write was to an unrelated address.
  53. Assert.IsNull(readTrackingTriggered); // Hasn't been triggered yet
  54. _tracking.VirtualMemoryEvent(0, 4, false);
  55. bool dirtyAfterRelatedRead = handle.Dirty;
  56. Assert.False(dirtyAfterRelatedRead); // Only triggers on write.
  57. Assert.AreEqual(readTrackingTriggered, (0UL, 4UL)); // Read action was triggered.
  58. readTrackingTriggered = null;
  59. _tracking.VirtualMemoryEvent(0, 4, true);
  60. bool dirtyAfterRelatedWrite = handle.Dirty;
  61. Assert.True(dirtyAfterRelatedWrite); // Dirty flag should now be set.
  62. _tracking.VirtualMemoryEvent(4, 4, true);
  63. bool dirtyAfterRelatedWrite2 = handle.Dirty;
  64. Assert.True(dirtyAfterRelatedWrite2); // Dirty flag should still be set.
  65. handle.Reprotect();
  66. bool dirtyAfterReprotect2 = handle.Dirty;
  67. Assert.False(dirtyAfterReprotect2); // Handle is no longer dirty.
  68. handle.Dispose();
  69. bool dirtyAfterDispose = TestSingleWrite(handle, 0, 4);
  70. Assert.False(dirtyAfterDispose); // Handle cannot be triggered when disposed
  71. }
  72. [Test]
  73. public void OverlappingRegions()
  74. {
  75. RegionHandle allHandle = _tracking.BeginTracking(0, PageSize * 16);
  76. allHandle.Reprotect();
  77. (ulong address, ulong size)? readTrackingTriggeredAll = null;
  78. Action registerReadAction = () =>
  79. {
  80. readTrackingTriggeredAll = null;
  81. allHandle.RegisterAction((address, size) =>
  82. {
  83. readTrackingTriggeredAll = (address, size);
  84. });
  85. };
  86. registerReadAction();
  87. // Create 16 page sized handles contained within the allHandle.
  88. RegionHandle[] containedHandles = new RegionHandle[16];
  89. for (int i = 0; i < 16; i++)
  90. {
  91. containedHandles[i] = _tracking.BeginTracking((ulong)i * PageSize, PageSize);
  92. containedHandles[i].Reprotect();
  93. }
  94. for (int i = 0; i < 16; i++)
  95. {
  96. // No handles are dirty.
  97. Assert.False(allHandle.Dirty);
  98. Assert.IsNull(readTrackingTriggeredAll);
  99. for (int j = 0; j < 16; j++)
  100. {
  101. Assert.False(containedHandles[j].Dirty);
  102. }
  103. _tracking.VirtualMemoryEvent((ulong)i * PageSize, 1, true);
  104. // Only the handle covering the entire range and the relevant contained handle are dirty.
  105. Assert.True(allHandle.Dirty);
  106. Assert.AreEqual(readTrackingTriggeredAll, ((ulong)i * PageSize, 1UL)); // Triggered read tracking
  107. for (int j = 0; j < 16; j++)
  108. {
  109. if (j == i)
  110. {
  111. Assert.True(containedHandles[j].Dirty);
  112. }
  113. else
  114. {
  115. Assert.False(containedHandles[j].Dirty);
  116. }
  117. }
  118. // Clear flags and reset read action.
  119. registerReadAction();
  120. allHandle.Reprotect();
  121. containedHandles[i].Reprotect();
  122. }
  123. }
  124. [Test]
  125. public void PageAlignment(
  126. [Values(1ul, 512ul, 2048ul, 4096ul, 65536ul)] [Random(1ul, 65536ul, RndCnt)] ulong address,
  127. [Values(1ul, 4ul, 1024ul, 4096ul, 65536ul)] [Random(1ul, 65536ul, RndCnt)] ulong size)
  128. {
  129. ulong alignedStart = (address / PageSize) * PageSize;
  130. ulong alignedEnd = ((address + size + PageSize - 1) / PageSize) * PageSize;
  131. ulong alignedSize = alignedEnd - alignedStart;
  132. RegionHandle handle = _tracking.BeginTracking(address, size);
  133. // Anywhere inside the pages the region is contained on should trigger.
  134. bool originalRangeTriggers = TestSingleWrite(handle, address, size);
  135. Assert.True(originalRangeTriggers);
  136. bool alignedRangeTriggers = TestSingleWrite(handle, alignedStart, alignedSize);
  137. Assert.True(alignedRangeTriggers);
  138. bool alignedStartTriggers = TestSingleWrite(handle, alignedStart, 1);
  139. Assert.True(alignedStartTriggers);
  140. bool alignedEndTriggers = TestSingleWrite(handle, alignedEnd - 1, 1);
  141. Assert.True(alignedEndTriggers);
  142. // Outside the tracked range should not trigger.
  143. bool alignedBeforeTriggers = TestSingleWrite(handle, alignedStart - 1, 1);
  144. Assert.False(alignedBeforeTriggers);
  145. bool alignedAfterTriggers = TestSingleWrite(handle, alignedEnd, 1);
  146. Assert.False(alignedAfterTriggers);
  147. }
  148. [Test, Explicit, Timeout(1000)]
  149. public void Multithreading()
  150. {
  151. // Multithreading sanity test
  152. // Multiple threads can easily read/write memory regions from any existing handle.
  153. // Handles can also be owned by different threads, though they should have one owner thread.
  154. // Handles can be created and disposed at any time, by any thread.
  155. // This test should not throw or deadlock due to invalid state.
  156. const int threadCount = 1;
  157. const int handlesPerThread = 16;
  158. long finishedTime = 0;
  159. RegionHandle[] handles = new RegionHandle[threadCount * handlesPerThread];
  160. Random globalRand = new Random();
  161. for (int i = 0; i < handles.Length; i++)
  162. {
  163. handles[i] = _tracking.BeginTracking((ulong)i * PageSize, PageSize);
  164. handles[i].Reprotect();
  165. }
  166. List<Thread> testThreads = new List<Thread>();
  167. // Dirty flag consumer threads
  168. int dirtyFlagReprotects = 0;
  169. for (int i = 0; i < threadCount; i++)
  170. {
  171. int randSeed = i;
  172. testThreads.Add(new Thread(() =>
  173. {
  174. int handleBase = randSeed * handlesPerThread;
  175. while (Stopwatch.GetTimestamp() < finishedTime)
  176. {
  177. Random random = new Random(randSeed);
  178. RegionHandle handle = handles[handleBase + random.Next(handlesPerThread)];
  179. if (handle.Dirty)
  180. {
  181. handle.Reprotect();
  182. Interlocked.Increment(ref dirtyFlagReprotects);
  183. }
  184. }
  185. }));
  186. }
  187. // Write trigger threads
  188. int writeTriggers = 0;
  189. for (int i = 0; i < threadCount; i++)
  190. {
  191. int randSeed = i;
  192. testThreads.Add(new Thread(() =>
  193. {
  194. Random random = new Random(randSeed);
  195. ulong handleBase = (ulong)(randSeed * handlesPerThread * PageSize);
  196. while (Stopwatch.GetTimestamp() < finishedTime)
  197. {
  198. _tracking.VirtualMemoryEvent(handleBase + (ulong)random.Next(PageSize * handlesPerThread), PageSize / 2, true);
  199. Interlocked.Increment(ref writeTriggers);
  200. }
  201. }));
  202. }
  203. // Handle create/delete threads
  204. int handleLifecycles = 0;
  205. for (int i = 0; i < threadCount; i++)
  206. {
  207. int randSeed = i;
  208. testThreads.Add(new Thread(() =>
  209. {
  210. int maxAddress = threadCount * handlesPerThread * PageSize;
  211. Random random = new Random(randSeed + 512);
  212. while (Stopwatch.GetTimestamp() < finishedTime)
  213. {
  214. RegionHandle handle = _tracking.BeginTracking((ulong)random.Next(maxAddress), (ulong)random.Next(65536));
  215. handle.Dispose();
  216. Interlocked.Increment(ref handleLifecycles);
  217. }
  218. }));
  219. }
  220. finishedTime = Stopwatch.GetTimestamp() + Stopwatch.Frequency / 2; // Run for 500ms;
  221. foreach (Thread thread in testThreads)
  222. {
  223. thread.Start();
  224. }
  225. foreach (Thread thread in testThreads)
  226. {
  227. thread.Join();
  228. }
  229. Assert.Greater(dirtyFlagReprotects, 10);
  230. Assert.Greater(writeTriggers, 10);
  231. Assert.Greater(handleLifecycles, 10);
  232. }
  233. [Test]
  234. public void ReadActionThreadConsumption()
  235. {
  236. // Read actions should only be triggered once for each registration.
  237. // The implementation should use an interlocked exchange to make sure other threads can't get the action.
  238. RegionHandle handle = _tracking.BeginTracking(0, PageSize);
  239. int triggeredCount = 0;
  240. int registeredCount = 0;
  241. int signalThreadsDone = 0;
  242. bool isRegistered = false;
  243. Action registerReadAction = () =>
  244. {
  245. registeredCount++;
  246. handle.RegisterAction((address, size) =>
  247. {
  248. isRegistered = false;
  249. Interlocked.Increment(ref triggeredCount);
  250. });
  251. };
  252. const int threadCount = 16;
  253. const int iterationCount = 10000;
  254. Thread[] signalThreads = new Thread[threadCount];
  255. for (int i = 0; i < threadCount; i++)
  256. {
  257. int randSeed = i;
  258. signalThreads[i] = new Thread(() =>
  259. {
  260. Random random = new Random(randSeed);
  261. for (int j = 0; j < iterationCount; j++)
  262. {
  263. _tracking.VirtualMemoryEvent((ulong)random.Next(PageSize), 4, false);
  264. }
  265. Interlocked.Increment(ref signalThreadsDone);
  266. });
  267. }
  268. for (int i = 0; i < threadCount; i++)
  269. {
  270. signalThreads[i].Start();
  271. }
  272. while (signalThreadsDone != -1)
  273. {
  274. if (signalThreadsDone == threadCount)
  275. {
  276. signalThreadsDone = -1;
  277. }
  278. if (!isRegistered)
  279. {
  280. isRegistered = true;
  281. registerReadAction();
  282. }
  283. }
  284. // The action should trigger exactly once for every registration,
  285. // then we register once after all the threads signalling it cease.
  286. Assert.AreEqual(registeredCount, triggeredCount + 1);
  287. }
  288. [Test]
  289. public void DisposeHandles()
  290. {
  291. // Ensure that disposed handles correctly remove their virtual and physical regions.
  292. RegionHandle handle = _tracking.BeginTracking(0, PageSize);
  293. handle.Reprotect();
  294. Assert.AreEqual(1, _tracking.GetRegionCount());
  295. handle.Dispose();
  296. Assert.AreEqual(0, _tracking.GetRegionCount());
  297. // Two handles, small entirely contains big.
  298. // We expect there to be three regions after creating both, one for the small region and two covering the big one around it.
  299. // Regions are always split to avoid overlapping, which is why there are three instead of two.
  300. RegionHandle handleSmall = _tracking.BeginTracking(PageSize, PageSize);
  301. RegionHandle handleBig = _tracking.BeginTracking(0, PageSize * 4);
  302. Assert.AreEqual(3, _tracking.GetRegionCount());
  303. // After disposing the big region, only the small one will remain.
  304. handleBig.Dispose();
  305. Assert.AreEqual(1, _tracking.GetRegionCount());
  306. handleSmall.Dispose();
  307. Assert.AreEqual(0, _tracking.GetRegionCount());
  308. }
  309. [Test]
  310. public void ReadAndWriteProtection()
  311. {
  312. MemoryPermission protection = MemoryPermission.ReadAndWrite;
  313. _memoryManager.OnProtect += (va, size, newProtection) =>
  314. {
  315. Assert.AreEqual((0, PageSize), (va, size)); // Should protect the exact region all the operations use.
  316. protection = newProtection;
  317. };
  318. RegionHandle handle = _tracking.BeginTracking(0, PageSize);
  319. // After creating the handle, there is no protection yet.
  320. Assert.AreEqual(MemoryPermission.ReadAndWrite, protection);
  321. bool dirtyInitial = handle.Dirty;
  322. Assert.True(dirtyInitial); // Handle starts dirty.
  323. handle.Reprotect();
  324. // After a reprotect, there is write protection, which will set a dirty flag when any write happens.
  325. Assert.AreEqual(MemoryPermission.Read, protection);
  326. (ulong address, ulong size)? readTrackingTriggered = null;
  327. handle.RegisterAction((address, size) =>
  328. {
  329. readTrackingTriggered = (address, size);
  330. });
  331. // Registering an action adds read/write protection.
  332. Assert.AreEqual(MemoryPermission.None, protection);
  333. bool dirtyAfterReprotect = handle.Dirty;
  334. Assert.False(dirtyAfterReprotect); // Handle is no longer dirty.
  335. // First we should read, which will trigger the action. This _should not_ remove write protection on the memory.
  336. _tracking.VirtualMemoryEvent(0, 4, false);
  337. bool dirtyAfterRead = handle.Dirty;
  338. Assert.False(dirtyAfterRead); // Not dirtied, as this was a read.
  339. Assert.AreEqual(readTrackingTriggered, (0UL, 4UL)); // Read action was triggered.
  340. Assert.AreEqual(MemoryPermission.Read, protection); // Write protection is still present.
  341. readTrackingTriggered = null;
  342. // Now, perform a write.
  343. _tracking.VirtualMemoryEvent(0, 4, true);
  344. bool dirtyAfterWriteAfterRead = handle.Dirty;
  345. Assert.True(dirtyAfterWriteAfterRead); // Should be dirty.
  346. Assert.AreEqual(MemoryPermission.ReadAndWrite, protection); // All protection is now be removed from the memory.
  347. Assert.IsNull(readTrackingTriggered); // Read tracking was removed when the action fired, as it can only fire once.
  348. handle.Dispose();
  349. }
  350. [Test]
  351. public void PreciseAction()
  352. {
  353. RegionHandle handle = _tracking.BeginTracking(0, PageSize);
  354. (ulong address, ulong size, bool write)? preciseTriggered = null;
  355. handle.RegisterPreciseAction((address, size, write) =>
  356. {
  357. preciseTriggered = (address, size, write);
  358. return true;
  359. });
  360. (ulong address, ulong size)? readTrackingTriggered = null;
  361. handle.RegisterAction((address, size) =>
  362. {
  363. readTrackingTriggered = (address, size);
  364. });
  365. handle.Reprotect();
  366. _tracking.VirtualMemoryEvent(0, 4, false, precise: true);
  367. Assert.IsNull(readTrackingTriggered); // Hasn't been triggered - precise action returned true.
  368. Assert.AreEqual(preciseTriggered, (0UL, 4UL, false)); // Precise action was triggered.
  369. _tracking.VirtualMemoryEvent(0, 4, true, precise: true);
  370. Assert.IsNull(readTrackingTriggered); // Still hasn't been triggered.
  371. bool dirtyAfterPreciseActionTrue = handle.Dirty;
  372. Assert.False(dirtyAfterPreciseActionTrue); // Not dirtied - precise action returned true.
  373. Assert.AreEqual(preciseTriggered, (0UL, 4UL, true)); // Precise action was triggered.
  374. // Handle is now dirty.
  375. handle.Reprotect(true);
  376. preciseTriggered = null;
  377. _tracking.VirtualMemoryEvent(4, 4, true, precise: true);
  378. Assert.AreEqual(preciseTriggered, (4UL, 4UL, true)); // Precise action was triggered even though handle was dirty.
  379. handle.Reprotect();
  380. handle.RegisterPreciseAction((address, size, write) =>
  381. {
  382. preciseTriggered = (address, size, write);
  383. return false; // Now, we return false, which indicates that the regular read/write behaviours should trigger.
  384. });
  385. _tracking.VirtualMemoryEvent(8, 4, true, precise: true);
  386. Assert.AreEqual(readTrackingTriggered, (8UL, 4UL)); // Read action triggered, as precise action returned false.
  387. bool dirtyAfterPreciseActionFalse = handle.Dirty;
  388. Assert.True(dirtyAfterPreciseActionFalse); // Dirtied, as precise action returned false.
  389. Assert.AreEqual(preciseTriggered, (8UL, 4UL, true)); // Precise action was triggered.
  390. }
  391. }
  392. }