HvAddressSpaceRange.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370
  1. using Ryujinx.Cpu.AppleHv.Arm;
  2. using System;
  3. using System.Diagnostics;
  4. using System.Runtime.InteropServices;
  5. using System.Threading;
  6. namespace Ryujinx.Cpu.AppleHv
  7. {
  8. class HvAddressSpaceRange : IDisposable
  9. {
  10. private const ulong AllocationGranule = 1UL << 14;
  11. private const ulong AttributesMask = (0x3ffUL << 2) | (0x3fffUL << 50);
  12. private const ulong BaseAttributes = (1UL << 10) | (3UL << 8); // Access flag set, inner shareable.
  13. private const int LevelBits = 9;
  14. private const int LevelCount = 1 << LevelBits;
  15. private const int LevelMask = LevelCount - 1;
  16. private const int PageBits = 12;
  17. private const int PageSize = 1 << PageBits;
  18. private const int PageMask = PageSize - 1;
  19. private const int AllLevelsMask = PageMask | (LevelMask << PageBits) | (LevelMask << (PageBits + LevelBits));
  20. private class PtLevel
  21. {
  22. public ulong Address => Allocation.Ipa + Allocation.Offset;
  23. public int EntriesCount;
  24. public readonly HvMemoryBlockAllocation Allocation;
  25. public readonly PtLevel[] Next;
  26. public PtLevel(HvMemoryBlockAllocator blockAllocator, int count, bool hasNext)
  27. {
  28. ulong size = (ulong)count * sizeof(ulong);
  29. Allocation = blockAllocator.Allocate(size, PageSize);
  30. AsSpan().Fill(0UL);
  31. if (hasNext)
  32. {
  33. Next = new PtLevel[count];
  34. }
  35. }
  36. public unsafe Span<ulong> AsSpan()
  37. {
  38. return MemoryMarshal.Cast<byte, ulong>(Allocation.Memory.GetSpan(Allocation.Offset, (int)Allocation.Size));
  39. }
  40. }
  41. private PtLevel _level0;
  42. private int _tlbInvalidationPending;
  43. private readonly HvIpaAllocator _ipaAllocator;
  44. private readonly HvMemoryBlockAllocator _blockAllocator;
  45. public HvAddressSpaceRange(HvIpaAllocator ipaAllocator)
  46. {
  47. _ipaAllocator = ipaAllocator;
  48. _blockAllocator = new HvMemoryBlockAllocator(ipaAllocator, (int)AllocationGranule);
  49. }
  50. public ulong GetIpaBase()
  51. {
  52. return EnsureLevel0().Address;
  53. }
  54. public bool GetAndClearTlbInvalidationPending()
  55. {
  56. return Interlocked.Exchange(ref _tlbInvalidationPending, 0) != 0;
  57. }
  58. public void Map(ulong va, ulong pa, ulong size, ApFlags accessPermission)
  59. {
  60. MapImpl(va, pa, size, (ulong)accessPermission | BaseAttributes);
  61. }
  62. public void Unmap(ulong va, ulong size)
  63. {
  64. UnmapImpl(EnsureLevel0(), 0, va, size);
  65. Interlocked.Exchange(ref _tlbInvalidationPending, 1);
  66. }
  67. public void Reprotect(ulong va, ulong size, ApFlags accessPermission)
  68. {
  69. UpdateAttributes(va, size, (ulong)accessPermission | BaseAttributes);
  70. }
  71. private void MapImpl(ulong va, ulong pa, ulong size, ulong attr)
  72. {
  73. PtLevel level0 = EnsureLevel0();
  74. ulong endVa = va + size;
  75. while (va < endVa)
  76. {
  77. (ulong mapSize, int depth) = GetMapSizeAndDepth(va, pa, endVa);
  78. PtLevel currentLevel = level0;
  79. for (int i = 0; i < depth; i++)
  80. {
  81. int l = (int)(va >> (PageBits + (2 - i) * LevelBits)) & LevelMask;
  82. EnsureTable(currentLevel, l, i == 0);
  83. currentLevel = currentLevel.Next[l];
  84. }
  85. (ulong blockSize, int blockShift) = GetBlockSizeAndShift(depth);
  86. for (ulong i = 0; i < mapSize; i += blockSize)
  87. {
  88. if ((va >> blockShift) << blockShift != va ||
  89. (pa >> blockShift) << blockShift != pa)
  90. {
  91. Debug.Fail($"Block size 0x{blockSize:X} (log2: {blockShift}) is invalid for VA 0x{va:X} or PA 0x{pa:X}.");
  92. }
  93. WriteBlock(currentLevel, (int)(va >> blockShift) & LevelMask, depth, pa, attr);
  94. va += blockSize;
  95. pa += blockSize;
  96. }
  97. }
  98. }
  99. private void UnmapImpl(PtLevel level, int depth, ulong va, ulong size)
  100. {
  101. ulong endVa = (va + size + PageMask) & ~((ulong)PageMask);
  102. va &= ~((ulong)PageMask);
  103. (ulong blockSize, int blockShift) = GetBlockSizeAndShift(depth);
  104. while (va < endVa)
  105. {
  106. ulong nextEntryVa = GetNextAddress(va, blockSize);
  107. ulong chunckSize = Math.Min(endVa - va, nextEntryVa - va);
  108. int l = (int)(va >> (PageBits + (2 - depth) * LevelBits)) & LevelMask;
  109. PtLevel nextTable = level.Next != null ? level.Next[l] : null;
  110. if (nextTable != null)
  111. {
  112. // Entry is a table, visit it and update attributes as required.
  113. UnmapImpl(nextTable, depth + 1, va, chunckSize);
  114. }
  115. else if (chunckSize != blockSize)
  116. {
  117. // Entry is a block but is not aligned, we need to turn it into a table.
  118. ref ulong pte = ref level.AsSpan()[l];
  119. nextTable = CreateTable(pte, depth + 1);
  120. level.Next[l] = nextTable;
  121. // Now that we have a table, we can handle it like the first case.
  122. UnmapImpl(nextTable, depth + 1, va, chunckSize);
  123. // Update PTE to point to the new table.
  124. pte = (nextTable.Address & ~(ulong)PageMask) | 3UL;
  125. }
  126. // If entry is a block, or if entry is a table but it is empty, we can remove it.
  127. if (nextTable == null || nextTable.EntriesCount == 0)
  128. {
  129. // Entry is a block and is fully aligned, so we can just set it to 0.
  130. if (nextTable != null)
  131. {
  132. nextTable.Allocation.Dispose();
  133. level.Next[l] = null;
  134. }
  135. level.AsSpan()[l] = 0UL;
  136. level.EntriesCount--;
  137. ValidateEntriesCount(level.EntriesCount);
  138. }
  139. va += chunckSize;
  140. }
  141. }
  142. private void UpdateAttributes(ulong va, ulong size, ulong newAttr)
  143. {
  144. UpdateAttributes(EnsureLevel0(), 0, va, size, newAttr);
  145. Interlocked.Exchange(ref _tlbInvalidationPending, 1);
  146. }
  147. private void UpdateAttributes(PtLevel level, int depth, ulong va, ulong size, ulong newAttr)
  148. {
  149. ulong endVa = (va + size + PageSize - 1) & ~((ulong)PageSize - 1);
  150. va &= ~((ulong)PageSize - 1);
  151. (ulong blockSize, int blockShift) = GetBlockSizeAndShift(depth);
  152. while (va < endVa)
  153. {
  154. ulong nextEntryVa = GetNextAddress(va, blockSize);
  155. ulong chunckSize = Math.Min(endVa - va, nextEntryVa - va);
  156. int l = (int)(va >> (PageBits + (2 - depth) * LevelBits)) & LevelMask;
  157. ref ulong pte = ref level.AsSpan()[l];
  158. // First check if the region is mapped.
  159. if ((pte & 3) != 0)
  160. {
  161. PtLevel nextTable = level.Next != null ? level.Next[l] : null;
  162. if (nextTable != null)
  163. {
  164. // Entry is a table, visit it and update attributes as required.
  165. UpdateAttributes(nextTable, depth + 1, va, chunckSize, newAttr);
  166. }
  167. else if (chunckSize != blockSize)
  168. {
  169. // Entry is a block but is not aligned, we need to turn it into a table.
  170. nextTable = CreateTable(pte, depth + 1);
  171. level.Next[l] = nextTable;
  172. // Now that we have a table, we can handle it like the first case.
  173. UpdateAttributes(nextTable, depth + 1, va, chunckSize, newAttr);
  174. // Update PTE to point to the new table.
  175. pte = (nextTable.Address & ~(ulong)PageMask) | 3UL;
  176. }
  177. else
  178. {
  179. // Entry is a block and is fully aligned, so we can just update the attributes.
  180. // Update PTE with the new attributes.
  181. pte = (pte & ~AttributesMask) | newAttr;
  182. }
  183. }
  184. va += chunckSize;
  185. }
  186. }
  187. private PtLevel CreateTable(ulong pte, int depth)
  188. {
  189. pte &= ~3UL;
  190. pte |= (depth == 2 ? 3UL : 1UL);
  191. PtLevel level = new PtLevel(_blockAllocator, LevelCount, depth < 2);
  192. Span<ulong> currentLevel = level.AsSpan();
  193. (ulong blockSize, int blockShift) = GetBlockSizeAndShift(depth);
  194. // Fill in the blocks.
  195. for (int i = 0; i < LevelCount; i++)
  196. {
  197. ulong offset = (ulong)i << blockShift;
  198. currentLevel[i] = pte + offset;
  199. }
  200. level.EntriesCount = LevelCount;
  201. return level;
  202. }
  203. private static (ulong, int) GetBlockSizeAndShift(int depth)
  204. {
  205. int blockShift = PageBits + (2 - depth) * LevelBits;
  206. ulong blockSize = 1UL << blockShift;
  207. return (blockSize, blockShift);
  208. }
  209. private static (ulong, int) GetMapSizeAndDepth(ulong va, ulong pa, ulong endVa)
  210. {
  211. // Both virtual and physical addresses must be aligned to the block size.
  212. ulong combinedAddress = va | pa;
  213. ulong l0Alignment = 1UL << (PageBits + LevelBits * 2);
  214. ulong l1Alignment = 1UL << (PageBits + LevelBits);
  215. if ((combinedAddress & (l0Alignment - 1)) == 0 && AlignDown(endVa, l0Alignment) > va)
  216. {
  217. return (AlignDown(endVa, l0Alignment) - va, 0);
  218. }
  219. else if ((combinedAddress & (l1Alignment - 1)) == 0 && AlignDown(endVa, l1Alignment) > va)
  220. {
  221. ulong nextOrderVa = GetNextAddress(va, l0Alignment);
  222. if (nextOrderVa <= endVa)
  223. {
  224. return (nextOrderVa - va, 1);
  225. }
  226. else
  227. {
  228. return (AlignDown(endVa, l1Alignment) - va, 1);
  229. }
  230. }
  231. else
  232. {
  233. ulong nextOrderVa = GetNextAddress(va, l1Alignment);
  234. if (nextOrderVa <= endVa)
  235. {
  236. return (nextOrderVa - va, 2);
  237. }
  238. else
  239. {
  240. return (endVa - va, 2);
  241. }
  242. }
  243. }
  244. private static ulong AlignDown(ulong va, ulong alignment)
  245. {
  246. return va & ~(alignment - 1);
  247. }
  248. private static ulong GetNextAddress(ulong va, ulong alignment)
  249. {
  250. return (va + alignment) & ~(alignment - 1);
  251. }
  252. private PtLevel EnsureLevel0()
  253. {
  254. PtLevel level0 = _level0;
  255. if (level0 == null)
  256. {
  257. level0 = new PtLevel(_blockAllocator, LevelCount, true);
  258. _level0 = level0;
  259. }
  260. return level0;
  261. }
  262. private void EnsureTable(PtLevel level, int index, bool hasNext)
  263. {
  264. Span<ulong> currentTable = level.AsSpan();
  265. if ((currentTable[index] & 1) == 0)
  266. {
  267. PtLevel nextLevel = new PtLevel(_blockAllocator, LevelCount, hasNext);
  268. currentTable[index] = (nextLevel.Address & ~(ulong)PageMask) | 3UL;
  269. level.Next[index] = nextLevel;
  270. level.EntriesCount++;
  271. ValidateEntriesCount(level.EntriesCount);
  272. }
  273. else if (level.Next[index] == null)
  274. {
  275. Debug.Fail($"Index {index} is block, expected a table.");
  276. }
  277. }
  278. private void WriteBlock(PtLevel level, int index, int depth, ulong pa, ulong attr)
  279. {
  280. Span<ulong> currentTable = level.AsSpan();
  281. currentTable[index] = (pa & ~((ulong)AllLevelsMask >> (depth * LevelBits))) | (depth == 2 ? 3UL : 1UL) | attr;
  282. level.EntriesCount++;
  283. ValidateEntriesCount(level.EntriesCount);
  284. }
  285. private static void ValidateEntriesCount(int count)
  286. {
  287. Debug.Assert(count >= 0 && count <= LevelCount, $"Entries count {count} is invalid.");
  288. }
  289. public void Dispose()
  290. {
  291. _blockAllocator.Dispose();
  292. }
  293. }
  294. }