PartialUnmapState.cs 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160
  1. using System;
  2. using System.Runtime.CompilerServices;
  3. using System.Runtime.InteropServices;
  4. using System.Runtime.Versioning;
  5. using System.Threading;
  6. using static Ryujinx.Common.Memory.PartialUnmaps.PartialUnmapHelpers;
  7. namespace Ryujinx.Common.Memory.PartialUnmaps
  8. {
  9. /// <summary>
  10. /// State for partial unmaps. Intended to be used on Windows.
  11. /// </summary>
  12. [StructLayout(LayoutKind.Sequential, Pack = 1)]
  13. public struct PartialUnmapState
  14. {
  15. public NativeReaderWriterLock PartialUnmapLock;
  16. public int PartialUnmapsCount;
  17. public ThreadLocalMap<int> LocalCounts;
  18. public readonly static int PartialUnmapLockOffset;
  19. public readonly static int PartialUnmapsCountOffset;
  20. public readonly static int LocalCountsOffset;
  21. public readonly static IntPtr GlobalState;
  22. [SupportedOSPlatform("windows")]
  23. [DllImport("kernel32.dll")]
  24. public static extern int GetCurrentThreadId();
  25. [SupportedOSPlatform("windows")]
  26. [DllImport("kernel32.dll", SetLastError = true)]
  27. static extern IntPtr OpenThread(int dwDesiredAccess, bool bInheritHandle, uint dwThreadId);
  28. [SupportedOSPlatform("windows")]
  29. [DllImport("kernel32.dll", SetLastError = true)]
  30. public static extern bool CloseHandle(IntPtr hObject);
  31. [SupportedOSPlatform("windows")]
  32. [DllImport("kernel32.dll", SetLastError = true)]
  33. static extern bool GetExitCodeThread(IntPtr hThread, out uint lpExitCode);
  34. /// <summary>
  35. /// Creates a global static PartialUnmapState and populates the field offsets.
  36. /// </summary>
  37. static unsafe PartialUnmapState()
  38. {
  39. PartialUnmapState instance = new PartialUnmapState();
  40. PartialUnmapLockOffset = OffsetOf(ref instance, ref instance.PartialUnmapLock);
  41. PartialUnmapsCountOffset = OffsetOf(ref instance, ref instance.PartialUnmapsCount);
  42. LocalCountsOffset = OffsetOf(ref instance, ref instance.LocalCounts);
  43. int size = Unsafe.SizeOf<PartialUnmapState>();
  44. GlobalState = Marshal.AllocHGlobal(size);
  45. Unsafe.InitBlockUnaligned((void*)GlobalState, 0, (uint)size);
  46. }
  47. /// <summary>
  48. /// Resets the global state.
  49. /// </summary>
  50. public static unsafe void Reset()
  51. {
  52. int size = Unsafe.SizeOf<PartialUnmapState>();
  53. Unsafe.InitBlockUnaligned((void*)GlobalState, 0, (uint)size);
  54. }
  55. /// <summary>
  56. /// Gets a reference to the global state.
  57. /// </summary>
  58. /// <returns>A reference to the global state</returns>
  59. public static unsafe ref PartialUnmapState GetRef()
  60. {
  61. return ref Unsafe.AsRef<PartialUnmapState>((void*)GlobalState);
  62. }
  63. /// <summary>
  64. /// Checks if an access violation handler should retry execution due to a fault caused by partial unmap.
  65. /// </summary>
  66. /// <remarks>
  67. /// Due to Windows limitations, <see cref="UnmapView"/> might need to unmap more memory than requested.
  68. /// The additional memory that was unmapped is later remapped, however this leaves a time gap where the
  69. /// memory might be accessed but is unmapped. Users of the API must compensate for that by catching the
  70. /// access violation and retrying if it happened between the unmap and remap operation.
  71. /// This method can be used to decide if retrying in such cases is necessary or not.
  72. ///
  73. /// This version of the function is not used, but serves as a reference for the native
  74. /// implementation in ARMeilleure.
  75. /// </remarks>
  76. /// <returns>True if execution should be retried, false otherwise</returns>
  77. [SupportedOSPlatform("windows")]
  78. public bool RetryFromAccessViolation()
  79. {
  80. PartialUnmapLock.AcquireReaderLock();
  81. int threadID = GetCurrentThreadId();
  82. int threadIndex = LocalCounts.GetOrReserve(threadID, 0);
  83. if (threadIndex == -1)
  84. {
  85. // Out of thread local space... try again later.
  86. PartialUnmapLock.ReleaseReaderLock();
  87. return true;
  88. }
  89. ref int threadLocalPartialUnmapsCount = ref LocalCounts.GetValue(threadIndex);
  90. bool retry = threadLocalPartialUnmapsCount != PartialUnmapsCount;
  91. if (retry)
  92. {
  93. threadLocalPartialUnmapsCount = PartialUnmapsCount;
  94. }
  95. PartialUnmapLock.ReleaseReaderLock();
  96. return retry;
  97. }
  98. /// <summary>
  99. /// Iterates and trims threads in the thread -> count map that
  100. /// are no longer active.
  101. /// </summary>
  102. [SupportedOSPlatform("windows")]
  103. public void TrimThreads()
  104. {
  105. const uint ExitCodeStillActive = 259;
  106. const int ThreadQueryInformation = 0x40;
  107. Span<int> ids = LocalCounts.ThreadIds.ToSpan();
  108. for (int i = 0; i < ids.Length; i++)
  109. {
  110. int id = ids[i];
  111. if (id != 0)
  112. {
  113. IntPtr handle = OpenThread(ThreadQueryInformation, false, (uint)id);
  114. if (handle == IntPtr.Zero)
  115. {
  116. Interlocked.CompareExchange(ref ids[i], 0, id);
  117. }
  118. else
  119. {
  120. GetExitCodeThread(handle, out uint exitCode);
  121. if (exitCode != ExitCodeStillActive)
  122. {
  123. Interlocked.CompareExchange(ref ids[i], 0, id);
  124. }
  125. CloseHandle(handle);
  126. }
  127. }
  128. }
  129. }
  130. }
  131. }