MemoryManager.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563
  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. MarkRegionAsModified(va, (ulong)data.Length);
  129. WriteImpl(va, data);
  130. }
  131. /// <summary>
  132. /// Writes data to CPU mapped memory, without tracking.
  133. /// </summary>
  134. /// <param name="va">Virtual address to write the data into</param>
  135. /// <param name="data">Data to be written</param>
  136. public void WriteUntracked(ulong va, ReadOnlySpan<byte> data)
  137. {
  138. if (data.Length == 0)
  139. {
  140. return;
  141. }
  142. WriteImpl(va, data);
  143. }
  144. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  145. /// <summary>
  146. /// Writes data to CPU mapped memory.
  147. /// </summary>
  148. /// <param name="va">Virtual address to write the data into</param>
  149. /// <param name="data">Data to be written</param>
  150. private void WriteImpl(ulong va, ReadOnlySpan<byte> data)
  151. {
  152. try
  153. {
  154. if (IsContiguousAndMapped(va, data.Length))
  155. {
  156. data.CopyTo(_backingMemory.GetSpan(GetPhysicalAddressInternal(va), data.Length));
  157. }
  158. else
  159. {
  160. int offset = 0, size;
  161. if ((va & PageMask) != 0)
  162. {
  163. ulong pa = GetPhysicalAddressInternal(va);
  164. size = Math.Min(data.Length, PageSize - (int)(va & PageMask));
  165. data.Slice(0, size).CopyTo(_backingMemory.GetSpan(pa, size));
  166. offset += size;
  167. }
  168. for (; offset < data.Length; offset += size)
  169. {
  170. ulong pa = GetPhysicalAddressInternal(va + (ulong)offset);
  171. size = Math.Min(data.Length - offset, PageSize);
  172. data.Slice(offset, size).CopyTo(_backingMemory.GetSpan(pa, size));
  173. }
  174. }
  175. }
  176. catch (InvalidMemoryRegionException)
  177. {
  178. if (_invalidAccessHandler == null || !_invalidAccessHandler(va))
  179. {
  180. throw;
  181. }
  182. }
  183. }
  184. /// <summary>
  185. /// Gets a read-only span of data from CPU mapped memory.
  186. /// </summary>
  187. /// <remarks>
  188. /// This may perform a allocation if the data is not contiguous in memory.
  189. /// For this reason, the span is read-only, you can't modify the data.
  190. /// </remarks>
  191. /// <param name="va">Virtual address of the data</param>
  192. /// <param name="size">Size of the data</param>
  193. /// <returns>A read-only span of the data</returns>
  194. /// <exception cref="InvalidMemoryRegionException">Throw for unhandled invalid or unmapped memory accesses</exception>
  195. public ReadOnlySpan<byte> GetSpan(ulong va, int size)
  196. {
  197. if (size == 0)
  198. {
  199. return ReadOnlySpan<byte>.Empty;
  200. }
  201. if (IsContiguousAndMapped(va, size))
  202. {
  203. return _backingMemory.GetSpan(GetPhysicalAddressInternal(va), size);
  204. }
  205. else
  206. {
  207. Span<byte> data = new byte[size];
  208. ReadImpl(va, data);
  209. return data;
  210. }
  211. }
  212. /// <summary>
  213. /// Gets a region of memory that can be written to.
  214. /// </summary>
  215. /// <remarks>
  216. /// If the requested region is not contiguous in physical memory,
  217. /// this will perform an allocation, and flush the data (writing it
  218. /// back to guest memory) on disposal.
  219. /// </remarks>
  220. /// <param name="va">Virtual address of the data</param>
  221. /// <param name="size">Size of the data</param>
  222. /// <returns>A writable region of memory containing the data</returns>
  223. /// <exception cref="InvalidMemoryRegionException">Throw for unhandled invalid or unmapped memory accesses</exception>
  224. public WritableRegion GetWritableRegion(ulong va, int size)
  225. {
  226. if (size == 0)
  227. {
  228. return new WritableRegion(null, va, Memory<byte>.Empty);
  229. }
  230. if (IsContiguousAndMapped(va, size))
  231. {
  232. return new WritableRegion(null, va, _backingMemory.GetMemory(GetPhysicalAddressInternal(va), size));
  233. }
  234. else
  235. {
  236. Memory<byte> memory = new byte[size];
  237. GetSpan(va, size).CopyTo(memory.Span);
  238. return new WritableRegion(this, va, memory);
  239. }
  240. }
  241. /// <summary>
  242. /// Gets a reference for the given type at the specified virtual memory address.
  243. /// </summary>
  244. /// <remarks>
  245. /// The data must be located at a contiguous memory region.
  246. /// </remarks>
  247. /// <typeparam name="T">Type of the data to get the reference</typeparam>
  248. /// <param name="va">Virtual address of the data</param>
  249. /// <returns>A reference to the data in memory</returns>
  250. /// <exception cref="MemoryNotContiguousException">Throw if the specified memory region is not contiguous in physical memory</exception>
  251. public ref T GetRef<T>(ulong va) where T : unmanaged
  252. {
  253. if (!IsContiguous(va, Unsafe.SizeOf<T>()))
  254. {
  255. ThrowMemoryNotContiguous();
  256. }
  257. MarkRegionAsModified(va, (ulong)Unsafe.SizeOf<T>());
  258. return ref _backingMemory.GetRef<T>(GetPhysicalAddressInternal(va));
  259. }
  260. private void ThrowMemoryNotContiguous() => throw new MemoryNotContiguousException();
  261. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  262. private bool IsContiguousAndMapped(ulong va, int size) => IsContiguous(va, size) && IsMapped(va);
  263. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  264. private bool IsContiguous(ulong va, int size)
  265. {
  266. if (!ValidateAddress(va))
  267. {
  268. return false;
  269. }
  270. ulong endVa = (va + (ulong)size + PageMask) & ~(ulong)PageMask;
  271. va &= ~(ulong)PageMask;
  272. int pages = (int)((endVa - va) / PageSize);
  273. for (int page = 0; page < pages - 1; page++)
  274. {
  275. if (!ValidateAddress(va + PageSize))
  276. {
  277. return false;
  278. }
  279. if (GetPhysicalAddressInternal(va) + PageSize != GetPhysicalAddressInternal(va + PageSize))
  280. {
  281. return false;
  282. }
  283. va += PageSize;
  284. }
  285. return true;
  286. }
  287. private void ReadImpl(ulong va, Span<byte> data)
  288. {
  289. if (data.Length == 0)
  290. {
  291. return;
  292. }
  293. try
  294. {
  295. int offset = 0, size;
  296. if ((va & PageMask) != 0)
  297. {
  298. ulong pa = GetPhysicalAddressInternal(va);
  299. size = Math.Min(data.Length, PageSize - (int)(va & PageMask));
  300. _backingMemory.GetSpan(pa, size).CopyTo(data.Slice(0, size));
  301. offset += size;
  302. }
  303. for (; offset < data.Length; offset += size)
  304. {
  305. ulong pa = GetPhysicalAddressInternal(va + (ulong)offset);
  306. size = Math.Min(data.Length - offset, PageSize);
  307. _backingMemory.GetSpan(pa, size).CopyTo(data.Slice(offset, size));
  308. }
  309. }
  310. catch (InvalidMemoryRegionException)
  311. {
  312. if (_invalidAccessHandler == null || !_invalidAccessHandler(va))
  313. {
  314. throw;
  315. }
  316. }
  317. }
  318. /// <summary>
  319. /// Checks if a specified virtual memory region has been modified by the CPU since the last call.
  320. /// </summary>
  321. /// <param name="va">Virtual address of the region</param>
  322. /// <param name="size">Size of the region</param>
  323. /// <param name="id">Resource identifier number (maximum is 15)</param>
  324. /// <param name="modifiedRanges">Optional array where the modified ranges should be written</param>
  325. /// <returns>The number of modified ranges</returns>
  326. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  327. public int QueryModified(ulong va, ulong size, int id, (ulong, ulong)[] modifiedRanges = null)
  328. {
  329. if (!ValidateAddress(va))
  330. {
  331. return 0;
  332. }
  333. ulong maxSize = _addressSpaceSize - va;
  334. if (size > maxSize)
  335. {
  336. size = maxSize;
  337. }
  338. // We need to ensure that the tagged pointer value is negative,
  339. // JIT generated code checks that to take the slow paths and call the MemoryManager Read/Write methods.
  340. long tag = (0x8000L | (1L << id)) << 48;
  341. ulong endVa = (va + size + PageMask) & ~(ulong)PageMask;
  342. va &= ~(ulong)PageMask;
  343. ulong rgStart = va;
  344. ulong rgSize = 0;
  345. int rangeIndex = 0;
  346. for (; va < endVa; va += PageSize)
  347. {
  348. while (true)
  349. {
  350. ref long pte = ref _pageTable.GetRef<long>((va >> PageBits) * PteSize);
  351. long pteValue = pte;
  352. // If the PTE value is 0, that means that the page is unmapped.
  353. // We behave as if the page was not modified, since modifying a page
  354. // that is not even mapped is impossible.
  355. if ((pteValue & tag) == tag || pteValue == 0)
  356. {
  357. if (rgSize != 0)
  358. {
  359. if (modifiedRanges != null && rangeIndex < modifiedRanges.Length)
  360. {
  361. modifiedRanges[rangeIndex] = (rgStart, rgSize);
  362. }
  363. rangeIndex++;
  364. rgSize = 0;
  365. }
  366. break;
  367. }
  368. else
  369. {
  370. if (Interlocked.CompareExchange(ref pte, pteValue | tag, pteValue) == pteValue)
  371. {
  372. if (rgSize == 0)
  373. {
  374. rgStart = va;
  375. }
  376. rgSize += PageSize;
  377. break;
  378. }
  379. }
  380. }
  381. }
  382. if (rgSize != 0)
  383. {
  384. if (modifiedRanges != null && rangeIndex < modifiedRanges.Length)
  385. {
  386. modifiedRanges[rangeIndex] = (rgStart, rgSize);
  387. }
  388. rangeIndex++;
  389. }
  390. return rangeIndex;
  391. }
  392. /// <summary>
  393. /// Checks if the page at a given CPU virtual address.
  394. /// </summary>
  395. /// <param name="va">Virtual address to check</param>
  396. /// <returns>True if the address is mapped, false otherwise</returns>
  397. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  398. public bool IsMapped(ulong va)
  399. {
  400. if (!ValidateAddress(va))
  401. {
  402. return false;
  403. }
  404. return _pageTable.Read<ulong>((va / PageSize) * PteSize) != 0;
  405. }
  406. private bool ValidateAddress(ulong va)
  407. {
  408. return va < _addressSpaceSize;
  409. }
  410. /// <summary>
  411. /// Performs address translation of the address inside a CPU mapped memory range.
  412. /// </summary>
  413. /// <remarks>
  414. /// If the address is invalid or unmapped, -1 will be returned.
  415. /// </remarks>
  416. /// <param name="va">Virtual address to be translated</param>
  417. /// <returns>The physical address</returns>
  418. public ulong GetPhysicalAddress(ulong va)
  419. {
  420. // We return -1L if the virtual address is invalid or unmapped.
  421. if (!ValidateAddress(va) || !IsMapped(va))
  422. {
  423. return ulong.MaxValue;
  424. }
  425. return GetPhysicalAddressInternal(va);
  426. }
  427. private ulong GetPhysicalAddressInternal(ulong va)
  428. {
  429. return PteToPa(_pageTable.Read<ulong>((va / PageSize) * PteSize) & ~(0xffffUL << 48)) + (va & PageMask);
  430. }
  431. /// <summary>
  432. /// Marks a region of memory as modified by the CPU.
  433. /// </summary>
  434. /// <param name="va">Virtual address of the region</param>
  435. /// <param name="size">Size of the region</param>
  436. public void MarkRegionAsModified(ulong va, ulong size)
  437. {
  438. ulong endVa = (va + size + PageMask) & ~(ulong)PageMask;
  439. while (va < endVa)
  440. {
  441. ref long pageRef = ref _pageTable.GetRef<long>((va >> PageBits) * PteSize);
  442. long pte;
  443. do
  444. {
  445. pte = Volatile.Read(ref pageRef);
  446. if (pte >= 0)
  447. {
  448. break;
  449. }
  450. }
  451. while (Interlocked.CompareExchange(ref pageRef, pte & ~(0xffffL << 48), pte) != pte);
  452. va += PageSize;
  453. }
  454. }
  455. private ulong PaToPte(ulong pa)
  456. {
  457. return (ulong)_backingMemory.GetPointer(pa, PageSize).ToInt64();
  458. }
  459. private ulong PteToPa(ulong pte)
  460. {
  461. return (ulong)((long)pte - _backingMemory.Pointer.ToInt64());
  462. }
  463. /// <summary>
  464. /// Disposes of resources used by the memory manager.
  465. /// </summary>
  466. public void Dispose() => _pageTable.Dispose();
  467. }
  468. }