PartialUnmapState.cs 6.0 KB

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