JitCache.cs 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250
  1. using ARMeilleure.CodeGen;
  2. using ARMeilleure.CodeGen.Unwinding;
  3. using ARMeilleure.Memory;
  4. using ARMeilleure.Native;
  5. using Humanizer;
  6. using Ryujinx.Common.Logging;
  7. using Ryujinx.Memory;
  8. using System;
  9. using System.Collections.Generic;
  10. using System.Diagnostics;
  11. using System.Runtime.InteropServices;
  12. using System.Runtime.Versioning;
  13. using System.Threading;
  14. namespace ARMeilleure.Translation.Cache
  15. {
  16. static partial class JitCache
  17. {
  18. private static readonly int _pageSize = (int)MemoryBlock.GetPageSize();
  19. private static readonly int _pageMask = _pageSize - 1;
  20. private const int CodeAlignment = 4; // Bytes.
  21. private const int CacheSize = 256 * 1024 * 1024;
  22. private static JitCacheInvalidation _jitCacheInvalidator;
  23. private static CacheMemoryAllocator _cacheAllocator;
  24. private static readonly List<CacheEntry> _cacheEntries = [];
  25. private static readonly Lock _lock = new();
  26. private static bool _initialized;
  27. private static readonly List<ReservedRegion> _jitRegions = new();
  28. private static int _activeRegionIndex = 0;
  29. [SupportedOSPlatform("windows")]
  30. [LibraryImport("kernel32.dll", SetLastError = true)]
  31. public static partial nint FlushInstructionCache(nint hProcess, nint lpAddress, nuint dwSize);
  32. public static void Initialize(IJitMemoryAllocator allocator)
  33. {
  34. if (_initialized)
  35. {
  36. return;
  37. }
  38. lock (_lock)
  39. {
  40. if (_initialized)
  41. {
  42. return;
  43. }
  44. ReservedRegion firstRegion = new(allocator, CacheSize);
  45. _jitRegions.Add(firstRegion);
  46. _activeRegionIndex = 0;
  47. if (!OperatingSystem.IsWindows() && !OperatingSystem.IsMacOS())
  48. {
  49. _jitCacheInvalidator = new JitCacheInvalidation(allocator);
  50. }
  51. _cacheAllocator = new CacheMemoryAllocator(CacheSize);
  52. if (OperatingSystem.IsWindows())
  53. {
  54. JitUnwindWindows.InstallFunctionTableHandler(
  55. firstRegion.Pointer, CacheSize, firstRegion.Pointer + Allocate(_pageSize)
  56. );
  57. }
  58. _initialized = true;
  59. }
  60. }
  61. public static nint Map(CompiledFunction func)
  62. {
  63. byte[] code = func.Code;
  64. lock (_lock)
  65. {
  66. Debug.Assert(_initialized);
  67. int funcOffset = Allocate(code.Length);
  68. ReservedRegion targetRegion = _jitRegions[_activeRegionIndex];
  69. nint funcPtr = targetRegion.Pointer + funcOffset;
  70. if (OperatingSystem.IsMacOS() && RuntimeInformation.ProcessArchitecture == Architecture.Arm64)
  71. {
  72. unsafe
  73. {
  74. fixed (byte* codePtr = code)
  75. {
  76. JitSupportDarwin.Copy(funcPtr, (nint)codePtr, (ulong)code.Length);
  77. }
  78. }
  79. }
  80. else
  81. {
  82. ReprotectAsWritable(targetRegion, funcOffset, code.Length);
  83. Marshal.Copy(code, 0, funcPtr, code.Length);
  84. ReprotectAsExecutable(targetRegion, funcOffset, code.Length);
  85. if (OperatingSystem.IsWindows() && RuntimeInformation.ProcessArchitecture == Architecture.Arm64)
  86. {
  87. FlushInstructionCache(Process.GetCurrentProcess().Handle, funcPtr, (nuint)code.Length);
  88. }
  89. else
  90. {
  91. _jitCacheInvalidator?.Invalidate(funcPtr, (ulong)code.Length);
  92. }
  93. }
  94. Add(funcOffset, code.Length, func.UnwindInfo);
  95. return funcPtr;
  96. }
  97. }
  98. public static void Unmap(nint pointer)
  99. {
  100. lock (_lock)
  101. {
  102. Debug.Assert(_initialized);
  103. foreach (ReservedRegion region in _jitRegions)
  104. {
  105. if (pointer.ToInt64() < region.Pointer.ToInt64() ||
  106. pointer.ToInt64() >= (region.Pointer + CacheSize).ToInt64())
  107. {
  108. continue;
  109. }
  110. int funcOffset = (int)(pointer.ToInt64() - region.Pointer.ToInt64());
  111. if (TryFind(funcOffset, out CacheEntry entry, out int entryIndex) && entry.Offset == funcOffset)
  112. {
  113. _cacheAllocator.Free(funcOffset, AlignCodeSize(entry.Size));
  114. _cacheEntries.RemoveAt(entryIndex);
  115. }
  116. return;
  117. }
  118. }
  119. }
  120. private static void ReprotectAsWritable(ReservedRegion region, int offset, int size)
  121. {
  122. int endOffs = offset + size;
  123. int regionStart = offset & ~_pageMask;
  124. int regionEnd = (endOffs + _pageMask) & ~_pageMask;
  125. region.Block.MapAsRwx((ulong)regionStart, (ulong)(regionEnd - regionStart));
  126. }
  127. private static void ReprotectAsExecutable(ReservedRegion region, int offset, int size)
  128. {
  129. int endOffs = offset + size;
  130. int regionStart = offset & ~_pageMask;
  131. int regionEnd = (endOffs + _pageMask) & ~_pageMask;
  132. region.Block.MapAsRx((ulong)regionStart, (ulong)(regionEnd - regionStart));
  133. }
  134. private static int Allocate(int codeSize)
  135. {
  136. codeSize = AlignCodeSize(codeSize);
  137. for (int i = _activeRegionIndex; i < _jitRegions.Count; i++)
  138. {
  139. int allocOffset = _cacheAllocator.Allocate(codeSize);
  140. if (allocOffset >= 0)
  141. {
  142. _jitRegions[i].ExpandIfNeeded((ulong)allocOffset + (ulong)codeSize);
  143. _activeRegionIndex = i;
  144. return allocOffset;
  145. }
  146. }
  147. int exhaustedRegion = _activeRegionIndex;
  148. var newRegion = new ReservedRegion(_jitRegions[0].Allocator, CacheSize);
  149. _jitRegions.Add(newRegion);
  150. _activeRegionIndex = _jitRegions.Count - 1;
  151. int newRegionNumber = _activeRegionIndex;
  152. Logger.Warning?.Print(LogClass.Cpu, $"JIT Cache Region {exhaustedRegion} exhausted, creating new Cache Region {newRegionNumber} ({((long)(newRegionNumber + 1) * CacheSize).Bytes()} Total Allocation).");
  153. _cacheAllocator = new CacheMemoryAllocator(CacheSize);
  154. int allocOffsetNew = _cacheAllocator.Allocate(codeSize);
  155. if (allocOffsetNew < 0)
  156. {
  157. throw new OutOfMemoryException("Failed to allocate in new Cache Region!");
  158. }
  159. newRegion.ExpandIfNeeded((ulong)allocOffsetNew + (ulong)codeSize);
  160. return allocOffsetNew;
  161. }
  162. private static int AlignCodeSize(int codeSize)
  163. {
  164. return checked(codeSize + (CodeAlignment - 1)) & ~(CodeAlignment - 1);
  165. }
  166. private static void Add(int offset, int size, UnwindInfo unwindInfo)
  167. {
  168. CacheEntry entry = new(offset, size, unwindInfo);
  169. int index = _cacheEntries.BinarySearch(entry);
  170. if (index < 0)
  171. {
  172. index = ~index;
  173. }
  174. _cacheEntries.Insert(index, entry);
  175. }
  176. public static bool TryFind(int offset, out CacheEntry entry, out int entryIndex)
  177. {
  178. lock (_lock)
  179. {
  180. foreach (ReservedRegion _ in _jitRegions)
  181. {
  182. int index = _cacheEntries.BinarySearch(new CacheEntry(offset, 0, default));
  183. if (index < 0)
  184. {
  185. index = ~index - 1;
  186. }
  187. if (index >= 0)
  188. {
  189. entry = _cacheEntries[index];
  190. entryIndex = index;
  191. return true;
  192. }
  193. }
  194. }
  195. entry = default;
  196. entryIndex = 0;
  197. return false;
  198. }
  199. }
  200. }