MemoryManager.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466
  1. using ARMeilleure.Memory;
  2. using Ryujinx.Memory;
  3. using System;
  4. using System.Runtime.CompilerServices;
  5. using System.Runtime.InteropServices;
  6. using System.Threading;
  7. namespace Ryujinx.Cpu
  8. {
  9. /// <summary>
  10. /// Represents a CPU memory manager.
  11. /// </summary>
  12. public sealed class MemoryManager : IMemoryManager, IDisposable
  13. {
  14. public const int PageBits = 12;
  15. public const int PageSize = 1 << PageBits;
  16. public const int PageMask = PageSize - 1;
  17. private const int PteSize = 8;
  18. public int AddressSpaceBits { get; }
  19. private readonly ulong _addressSpaceSize;
  20. private readonly MemoryBlock _backingMemory;
  21. private readonly MemoryBlock _pageTable;
  22. public IntPtr PageTablePointer => _pageTable.Pointer;
  23. /// <summary>
  24. /// Creates a new instance of the memory manager.
  25. /// </summary>
  26. /// <param name="backingMemory">Physical backing memory where virtual memory will be mapped to</param>
  27. /// <param name="addressSpaceSize">Size of the address space</param>
  28. public MemoryManager(MemoryBlock backingMemory, ulong addressSpaceSize)
  29. {
  30. ulong asSize = PageSize;
  31. int asBits = PageBits;
  32. while (asSize < addressSpaceSize)
  33. {
  34. asSize <<= 1;
  35. asBits++;
  36. }
  37. AddressSpaceBits = asBits;
  38. _addressSpaceSize = asSize;
  39. _backingMemory = backingMemory;
  40. _pageTable = new MemoryBlock((asSize / PageSize) * PteSize);
  41. }
  42. /// <summary>
  43. /// Maps a virtual memory range into a physical memory range.
  44. /// </summary>
  45. /// <remarks>
  46. /// Addresses and size must be page aligned.
  47. /// </remarks>
  48. /// <param name="va">Virtual memory address</param>
  49. /// <param name="pa">Physical memory address</param>
  50. /// <param name="size">Size to be mapped</param>
  51. public void Map(ulong va, ulong pa, ulong size)
  52. {
  53. while (size != 0)
  54. {
  55. _pageTable.Write((va / PageSize) * PteSize, PaToPte(pa));
  56. va += PageSize;
  57. pa += PageSize;
  58. size -= PageSize;
  59. }
  60. }
  61. /// <summary>
  62. /// Unmaps a previously mapped range of virtual memory.
  63. /// </summary>
  64. /// <param name="va">Virtual address of the range to be unmapped</param>
  65. /// <param name="size">Size of the range to be unmapped</param>
  66. public void Unmap(ulong va, ulong size)
  67. {
  68. while (size != 0)
  69. {
  70. _pageTable.Write((va / PageSize) * PteSize, 0UL);
  71. va += PageSize;
  72. size -= PageSize;
  73. }
  74. }
  75. /// <summary>
  76. /// Reads data from CPU mapped memory.
  77. /// </summary>
  78. /// <typeparam name="T">Type of the data being read</typeparam>
  79. /// <param name="va">Virtual address of the data in memory</param>
  80. /// <returns>The data</returns>
  81. public T Read<T>(ulong va) where T : unmanaged
  82. {
  83. return MemoryMarshal.Cast<byte, T>(GetSpan(va, Unsafe.SizeOf<T>()))[0];
  84. }
  85. /// <summary>
  86. /// Reads data from CPU mapped memory.
  87. /// </summary>
  88. /// <param name="va">Virtual address of the data in memory</param>
  89. /// <param name="data">Span to store the data being read into</param>
  90. public void Read(ulong va, Span<byte> data)
  91. {
  92. ReadImpl(va, data);
  93. }
  94. /// <summary>
  95. /// Writes data to CPU mapped memory.
  96. /// </summary>
  97. /// <typeparam name="T">Type of the data being written</typeparam>
  98. /// <param name="va">Virtual address to write the data into</param>
  99. /// <param name="value">Data to be written</param>
  100. public void Write<T>(ulong va, T value) where T : unmanaged
  101. {
  102. Write(va, MemoryMarshal.Cast<T, byte>(MemoryMarshal.CreateSpan(ref value, 1)));
  103. }
  104. /// <summary>
  105. /// Writes data to CPU mapped memory.
  106. /// </summary>
  107. /// <param name="va">Virtual address to write the data into</param>
  108. /// <param name="data">Data to be written</param>
  109. public void Write(ulong va, ReadOnlySpan<byte> data)
  110. {
  111. if (data.Length == 0)
  112. {
  113. return;
  114. }
  115. MarkRegionAsModified(va, (ulong)data.Length);
  116. if (IsContiguous(va, data.Length))
  117. {
  118. data.CopyTo(_backingMemory.GetSpan(GetPhysicalAddressInternal(va), data.Length));
  119. }
  120. else
  121. {
  122. int offset = 0, size;
  123. if ((va & PageMask) != 0)
  124. {
  125. ulong pa = GetPhysicalAddressInternal(va);
  126. size = Math.Min(data.Length, PageSize - (int)(va & PageMask));
  127. data.Slice(0, size).CopyTo(_backingMemory.GetSpan(pa, size));
  128. offset += size;
  129. }
  130. for (; offset < data.Length; offset += size)
  131. {
  132. ulong pa = GetPhysicalAddressInternal(va + (ulong)offset);
  133. size = Math.Min(data.Length - offset, PageSize);
  134. data.Slice(offset, size).CopyTo(_backingMemory.GetSpan(pa, size));
  135. }
  136. }
  137. }
  138. /// <summary>
  139. /// Gets a read-only span of data from CPU mapped memory.
  140. /// </summary>
  141. /// <remarks>
  142. /// This may perform a allocation if the data is not contiguous in memory.
  143. /// For this reason, the span is read-only, you can't modify the data.
  144. /// </remarks>
  145. /// <param name="va">Virtual address of the data</param>
  146. /// <param name="size">Size of the data</param>
  147. /// <returns>A read-only span of the data</returns>
  148. public ReadOnlySpan<byte> GetSpan(ulong va, int size)
  149. {
  150. if (size == 0)
  151. {
  152. return ReadOnlySpan<byte>.Empty;
  153. }
  154. if (IsContiguous(va, size))
  155. {
  156. return _backingMemory.GetSpan(GetPhysicalAddressInternal(va), size);
  157. }
  158. else
  159. {
  160. Span<byte> data = new byte[size];
  161. ReadImpl(va, data);
  162. return data;
  163. }
  164. }
  165. /// <summary>
  166. /// Gets a reference for the given type at the specified virtual memory address.
  167. /// </summary>
  168. /// <remarks>
  169. /// The data must be located at a contiguous memory region.
  170. /// </remarks>
  171. /// <typeparam name="T">Type of the data to get the reference</typeparam>
  172. /// <param name="va">Virtual address of the data</param>
  173. /// <returns>A reference to the data in memory</returns>
  174. public ref T GetRef<T>(ulong va) where T : unmanaged
  175. {
  176. if (!IsContiguous(va, Unsafe.SizeOf<T>()))
  177. {
  178. ThrowMemoryNotContiguous();
  179. }
  180. MarkRegionAsModified(va, (ulong)Unsafe.SizeOf<T>());
  181. return ref _backingMemory.GetRef<T>(GetPhysicalAddressInternal(va));
  182. }
  183. private void ThrowMemoryNotContiguous() => throw new MemoryNotContiguousException();
  184. // TODO: Remove that once we have proper 8-bits and 16-bits CAS.
  185. public ref T GetRefNoChecks<T>(ulong va) where T : unmanaged
  186. {
  187. MarkRegionAsModified(va, (ulong)Unsafe.SizeOf<T>());
  188. return ref _backingMemory.GetRef<T>(GetPhysicalAddressInternal(va));
  189. }
  190. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  191. private bool IsContiguous(ulong va, int size)
  192. {
  193. if (!ValidateAddress(va))
  194. {
  195. return false;
  196. }
  197. ulong endVa = (va + (ulong)size + PageMask) & ~(ulong)PageMask;
  198. va &= ~(ulong)PageMask;
  199. int pages = (int)((endVa - va) / PageSize);
  200. for (int page = 0; page < pages - 1; page++)
  201. {
  202. if (!ValidateAddress(va + PageSize))
  203. {
  204. return false;
  205. }
  206. if (GetPhysicalAddressInternal(va) + PageSize != GetPhysicalAddressInternal(va + PageSize))
  207. {
  208. return false;
  209. }
  210. va += PageSize;
  211. }
  212. return true;
  213. }
  214. private void ReadImpl(ulong va, Span<byte> data)
  215. {
  216. if (data.Length == 0)
  217. {
  218. return;
  219. }
  220. int offset = 0, size;
  221. if ((va & PageMask) != 0)
  222. {
  223. ulong pa = GetPhysicalAddressInternal(va);
  224. size = Math.Min(data.Length, PageSize - (int)(va & PageMask));
  225. _backingMemory.GetSpan(pa, size).CopyTo(data.Slice(0, size));
  226. offset += size;
  227. }
  228. for (; offset < data.Length; offset += size)
  229. {
  230. ulong pa = GetPhysicalAddressInternal(va + (ulong)offset);
  231. size = Math.Min(data.Length - offset, PageSize);
  232. _backingMemory.GetSpan(pa, size).CopyTo(data.Slice(offset, size));
  233. }
  234. }
  235. /// <summary>
  236. /// Checks if a specified virtual memory region has been modified by the CPU since the last call.
  237. /// </summary>
  238. /// <param name="va">Virtual address of the region</param>
  239. /// <param name="size">Size of the region</param>
  240. /// <param name="id">Resource identifier number (maximum is 15)</param>
  241. /// <param name="modifiedRanges">Optional array where the modified ranges should be written</param>
  242. /// <returns>The number of modified ranges</returns>
  243. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  244. public int QueryModified(ulong va, ulong size, int id, (ulong, ulong)[] modifiedRanges = null)
  245. {
  246. if (!ValidateAddress(va))
  247. {
  248. return 0;
  249. }
  250. ulong maxSize = _addressSpaceSize - va;
  251. if (size > maxSize)
  252. {
  253. size = maxSize;
  254. }
  255. // We need to ensure that the tagged pointer value is negative,
  256. // JIT generated code checks that to take the slow paths and call the MemoryManager Read/Write methods.
  257. long tag = (0x8000L | (1L << id)) << 48;
  258. ulong endVa = (va + size + PageMask) & ~(ulong)PageMask;
  259. va &= ~(ulong)PageMask;
  260. ulong rgStart = va;
  261. ulong rgSize = 0;
  262. int rangeIndex = 0;
  263. for (; va < endVa; va += PageSize)
  264. {
  265. while (true)
  266. {
  267. ref long pte = ref _pageTable.GetRef<long>((va >> PageBits) * PteSize);
  268. long pteValue = pte;
  269. // If the PTE value is 0, that means that the page is unmapped.
  270. // We behave as if the page was not modified, since modifying a page
  271. // that is not even mapped is impossible.
  272. if ((pteValue & tag) == tag || pteValue == 0)
  273. {
  274. if (rgSize != 0)
  275. {
  276. if (modifiedRanges != null && rangeIndex < modifiedRanges.Length)
  277. {
  278. modifiedRanges[rangeIndex] = (rgStart, rgSize);
  279. }
  280. rangeIndex++;
  281. rgSize = 0;
  282. }
  283. break;
  284. }
  285. else
  286. {
  287. if (Interlocked.CompareExchange(ref pte, pteValue | tag, pteValue) == pteValue)
  288. {
  289. if (rgSize == 0)
  290. {
  291. rgStart = va;
  292. }
  293. rgSize += PageSize;
  294. break;
  295. }
  296. }
  297. }
  298. }
  299. if (rgSize != 0)
  300. {
  301. if (modifiedRanges != null && rangeIndex < modifiedRanges.Length)
  302. {
  303. modifiedRanges[rangeIndex] = (rgStart, rgSize);
  304. }
  305. rangeIndex++;
  306. }
  307. return rangeIndex;
  308. }
  309. /// <summary>
  310. /// Checks if the page at a given CPU virtual address.
  311. /// </summary>
  312. /// <param name="va">Virtual address to check</param>
  313. /// <returns>True if the address is mapped, false otherwise</returns>
  314. public bool IsMapped(ulong va)
  315. {
  316. if (!ValidateAddress(va))
  317. {
  318. return false;
  319. }
  320. return _pageTable.Read<ulong>((va / PageSize) * PteSize) != 0;
  321. }
  322. private bool ValidateAddress(ulong va)
  323. {
  324. return va < _addressSpaceSize;
  325. }
  326. /// <summary>
  327. /// Performs address translation of the address inside a CPU mapped memory range.
  328. /// </summary>
  329. /// <remarks>
  330. /// If the address is invalid or unmapped, -1 will be returned.
  331. /// </remarks>
  332. /// <param name="va">Virtual address to be translated</param>
  333. /// <returns>The physical address</returns>
  334. public ulong GetPhysicalAddress(ulong va)
  335. {
  336. // We return -1L if the virtual address is invalid or unmapped.
  337. if (!ValidateAddress(va) || !IsMapped(va))
  338. {
  339. return ulong.MaxValue;
  340. }
  341. return GetPhysicalAddressInternal(va);
  342. }
  343. private ulong GetPhysicalAddressInternal(ulong va)
  344. {
  345. return PteToPa(_pageTable.Read<ulong>((va / PageSize) * PteSize) & ~(0xffffUL << 48)) + (va & PageMask);
  346. }
  347. private void MarkRegionAsModified(ulong va, ulong size)
  348. {
  349. ulong endVa = (va + size + PageMask) & ~(ulong)PageMask;
  350. while (va < endVa)
  351. {
  352. ref long pageRef = ref _pageTable.GetRef<long>((va >> PageBits) * PteSize);
  353. long pte;
  354. do
  355. {
  356. pte = Volatile.Read(ref pageRef);
  357. if (pte >= 0)
  358. {
  359. break;
  360. }
  361. }
  362. while (Interlocked.CompareExchange(ref pageRef, pte & ~(0xffffL << 48), pte) != pte);
  363. va += PageSize;
  364. }
  365. }
  366. private ulong PaToPte(ulong pa)
  367. {
  368. return (ulong)_backingMemory.GetPointer(pa, PageSize).ToInt64();
  369. }
  370. private ulong PteToPa(ulong pte)
  371. {
  372. return (ulong)((long)pte - _backingMemory.Pointer.ToInt64());
  373. }
  374. public void Dispose()
  375. {
  376. _pageTable.Dispose();
  377. }
  378. }
  379. }