MemoryManager.cs 18 KB

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