MemoryManager.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608
  1. using ARMeilleure.Memory;
  2. using Ryujinx.Cpu.Tracking;
  3. using Ryujinx.Memory;
  4. using Ryujinx.Memory.Range;
  5. using Ryujinx.Memory.Tracking;
  6. using System;
  7. using System.Collections.Generic;
  8. using System.Linq;
  9. using System.Runtime.CompilerServices;
  10. using System.Runtime.InteropServices;
  11. using System.Threading;
  12. namespace Ryujinx.Cpu
  13. {
  14. /// <summary>
  15. /// Represents a CPU memory manager.
  16. /// </summary>
  17. public sealed class MemoryManager : MemoryManagerBase, IMemoryManager, IVirtualMemoryManagerTracked, IWritableBlock
  18. {
  19. public const int PageBits = 12;
  20. public const int PageSize = 1 << PageBits;
  21. public const int PageMask = PageSize - 1;
  22. private const int PteSize = 8;
  23. private const int PointerTagBit = 62;
  24. private readonly InvalidAccessHandler _invalidAccessHandler;
  25. /// <summary>
  26. /// Address space width in bits.
  27. /// </summary>
  28. public int AddressSpaceBits { get; }
  29. private readonly ulong _addressSpaceSize;
  30. private readonly MemoryBlock _pageTable;
  31. /// <summary>
  32. /// Page table base pointer.
  33. /// </summary>
  34. public IntPtr PageTablePointer => _pageTable.Pointer;
  35. public MemoryManagerType Type => MemoryManagerType.SoftwarePageTable;
  36. public MemoryTracking Tracking { get; }
  37. public event Action<ulong, ulong> UnmapEvent;
  38. /// <summary>
  39. /// Creates a new instance of the memory manager.
  40. /// </summary>
  41. /// <param name="addressSpaceSize">Size of the address space</param>
  42. /// <param name="invalidAccessHandler">Optional function to handle invalid memory accesses</param>
  43. public MemoryManager(ulong addressSpaceSize, InvalidAccessHandler invalidAccessHandler = null)
  44. {
  45. _invalidAccessHandler = invalidAccessHandler;
  46. ulong asSize = PageSize;
  47. int asBits = PageBits;
  48. while (asSize < addressSpaceSize)
  49. {
  50. asSize <<= 1;
  51. asBits++;
  52. }
  53. AddressSpaceBits = asBits;
  54. _addressSpaceSize = asSize;
  55. _pageTable = new MemoryBlock((asSize / PageSize) * PteSize);
  56. Tracking = new MemoryTracking(this, PageSize);
  57. }
  58. /// <inheritdoc/>
  59. public void Map(ulong va, nuint hostAddress, ulong size)
  60. {
  61. AssertValidAddressAndSize(va, size);
  62. ulong remainingSize = size;
  63. ulong oVa = va;
  64. while (remainingSize != 0)
  65. {
  66. _pageTable.Write((va / PageSize) * PteSize, hostAddress);
  67. va += PageSize;
  68. hostAddress += PageSize;
  69. remainingSize -= PageSize;
  70. }
  71. Tracking.Map(oVa, size);
  72. }
  73. /// <inheritdoc/>
  74. public void Unmap(ulong va, ulong size)
  75. {
  76. // If size is 0, there's nothing to unmap, just exit early.
  77. if (size == 0)
  78. {
  79. return;
  80. }
  81. AssertValidAddressAndSize(va, size);
  82. UnmapEvent?.Invoke(va, size);
  83. Tracking.Unmap(va, size);
  84. ulong remainingSize = size;
  85. while (remainingSize != 0)
  86. {
  87. _pageTable.Write((va / PageSize) * PteSize, (nuint)0);
  88. va += PageSize;
  89. remainingSize -= PageSize;
  90. }
  91. }
  92. /// <inheritdoc/>
  93. public T Read<T>(ulong va) where T : unmanaged
  94. {
  95. return MemoryMarshal.Cast<byte, T>(GetSpan(va, Unsafe.SizeOf<T>(), true))[0];
  96. }
  97. /// <inheritdoc/>
  98. public T ReadTracked<T>(ulong va) where T : unmanaged
  99. {
  100. SignalMemoryTracking(va, (ulong)Unsafe.SizeOf<T>(), false);
  101. return MemoryMarshal.Cast<byte, T>(GetSpan(va, Unsafe.SizeOf<T>()))[0];
  102. }
  103. /// <inheritdoc/>
  104. public void Read(ulong va, Span<byte> data)
  105. {
  106. ReadImpl(va, data);
  107. }
  108. /// <inheritdoc/>
  109. public void Write<T>(ulong va, T value) where T : unmanaged
  110. {
  111. Write(va, MemoryMarshal.Cast<T, byte>(MemoryMarshal.CreateSpan(ref value, 1)));
  112. }
  113. /// <inheritdoc/>
  114. public void Write(ulong va, ReadOnlySpan<byte> data)
  115. {
  116. if (data.Length == 0)
  117. {
  118. return;
  119. }
  120. SignalMemoryTracking(va, (ulong)data.Length, true);
  121. WriteImpl(va, data);
  122. }
  123. /// <inheritdoc/>
  124. public void WriteUntracked(ulong va, ReadOnlySpan<byte> data)
  125. {
  126. if (data.Length == 0)
  127. {
  128. return;
  129. }
  130. WriteImpl(va, data);
  131. }
  132. /// <summary>
  133. /// Writes data to CPU mapped memory.
  134. /// </summary>
  135. /// <param name="va">Virtual address to write the data into</param>
  136. /// <param name="data">Data to be written</param>
  137. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  138. private void WriteImpl(ulong va, ReadOnlySpan<byte> data)
  139. {
  140. try
  141. {
  142. AssertValidAddressAndSize(va, (ulong)data.Length);
  143. if (IsContiguousAndMapped(va, data.Length))
  144. {
  145. data.CopyTo(GetHostSpanContiguous(va, data.Length));
  146. }
  147. else
  148. {
  149. int offset = 0, size;
  150. if ((va & PageMask) != 0)
  151. {
  152. size = Math.Min(data.Length, PageSize - (int)(va & PageMask));
  153. data.Slice(0, size).CopyTo(GetHostSpanContiguous(va, size));
  154. offset += size;
  155. }
  156. for (; offset < data.Length; offset += size)
  157. {
  158. size = Math.Min(data.Length - offset, PageSize);
  159. data.Slice(offset, size).CopyTo(GetHostSpanContiguous(va + (ulong)offset, size));
  160. }
  161. }
  162. }
  163. catch (InvalidMemoryRegionException)
  164. {
  165. if (_invalidAccessHandler == null || !_invalidAccessHandler(va))
  166. {
  167. throw;
  168. }
  169. }
  170. }
  171. /// <inheritdoc/>
  172. public ReadOnlySpan<byte> GetSpan(ulong va, int size, bool tracked = false)
  173. {
  174. if (size == 0)
  175. {
  176. return ReadOnlySpan<byte>.Empty;
  177. }
  178. if (tracked)
  179. {
  180. SignalMemoryTracking(va, (ulong)size, false);
  181. }
  182. if (IsContiguousAndMapped(va, size))
  183. {
  184. return GetHostSpanContiguous(va, size);
  185. }
  186. else
  187. {
  188. Span<byte> data = new byte[size];
  189. ReadImpl(va, data);
  190. return data;
  191. }
  192. }
  193. /// <inheritdoc/>
  194. public unsafe WritableRegion GetWritableRegion(ulong va, int size, bool tracked = false)
  195. {
  196. if (size == 0)
  197. {
  198. return new WritableRegion(null, va, Memory<byte>.Empty);
  199. }
  200. if (IsContiguousAndMapped(va, size))
  201. {
  202. if (tracked)
  203. {
  204. SignalMemoryTracking(va, (ulong)size, true);
  205. }
  206. return new WritableRegion(null, va, new NativeMemoryManager<byte>((byte*)GetHostAddress(va), size).Memory);
  207. }
  208. else
  209. {
  210. Memory<byte> memory = new byte[size];
  211. GetSpan(va, size).CopyTo(memory.Span);
  212. return new WritableRegion(this, va, memory, tracked);
  213. }
  214. }
  215. /// <inheritdoc/>
  216. public unsafe ref T GetRef<T>(ulong va) where T : unmanaged
  217. {
  218. if (!IsContiguous(va, Unsafe.SizeOf<T>()))
  219. {
  220. ThrowMemoryNotContiguous();
  221. }
  222. SignalMemoryTracking(va, (ulong)Unsafe.SizeOf<T>(), true);
  223. return ref *(T*)GetHostAddress(va);
  224. }
  225. /// <summary>
  226. /// Computes the number of pages in a virtual address range.
  227. /// </summary>
  228. /// <param name="va">Virtual address of the range</param>
  229. /// <param name="size">Size of the range</param>
  230. /// <param name="startVa">The virtual address of the beginning of the first page</param>
  231. /// <remarks>This function does not differentiate between allocated and unallocated pages.</remarks>
  232. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  233. private int GetPagesCount(ulong va, uint size, out ulong startVa)
  234. {
  235. // WARNING: Always check if ulong does not overflow during the operations.
  236. startVa = va & ~(ulong)PageMask;
  237. ulong vaSpan = (va - startVa + size + PageMask) & ~(ulong)PageMask;
  238. return (int)(vaSpan / PageSize);
  239. }
  240. private void ThrowMemoryNotContiguous() => throw new MemoryNotContiguousException();
  241. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  242. private bool IsContiguousAndMapped(ulong va, int size) => IsContiguous(va, size) && IsMapped(va);
  243. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  244. private bool IsContiguous(ulong va, int size)
  245. {
  246. if (!ValidateAddress(va) || !ValidateAddressAndSize(va, (ulong)size))
  247. {
  248. return false;
  249. }
  250. int pages = GetPagesCount(va, (uint)size, out va);
  251. for (int page = 0; page < pages - 1; page++)
  252. {
  253. if (!ValidateAddress(va + PageSize))
  254. {
  255. return false;
  256. }
  257. if (GetHostAddress(va) + PageSize != GetHostAddress(va + PageSize))
  258. {
  259. return false;
  260. }
  261. va += PageSize;
  262. }
  263. return true;
  264. }
  265. /// <inheritdoc/>
  266. public IEnumerable<HostMemoryRange> GetPhysicalRegions(ulong va, ulong size)
  267. {
  268. if (size == 0)
  269. {
  270. return Enumerable.Empty<HostMemoryRange>();
  271. }
  272. if (!ValidateAddress(va) || !ValidateAddressAndSize(va, size))
  273. {
  274. return null;
  275. }
  276. int pages = GetPagesCount(va, (uint)size, out va);
  277. var regions = new List<HostMemoryRange>();
  278. nuint regionStart = GetHostAddress(va);
  279. ulong regionSize = PageSize;
  280. for (int page = 0; page < pages - 1; page++)
  281. {
  282. if (!ValidateAddress(va + PageSize))
  283. {
  284. return null;
  285. }
  286. nuint newHostAddress = GetHostAddress(va + PageSize);
  287. if (GetHostAddress(va) + PageSize != newHostAddress)
  288. {
  289. regions.Add(new HostMemoryRange(regionStart, regionSize));
  290. regionStart = newHostAddress;
  291. regionSize = 0;
  292. }
  293. va += PageSize;
  294. regionSize += PageSize;
  295. }
  296. regions.Add(new HostMemoryRange(regionStart, regionSize));
  297. return regions;
  298. }
  299. private void ReadImpl(ulong va, Span<byte> data)
  300. {
  301. if (data.Length == 0)
  302. {
  303. return;
  304. }
  305. try
  306. {
  307. AssertValidAddressAndSize(va, (ulong)data.Length);
  308. int offset = 0, size;
  309. if ((va & PageMask) != 0)
  310. {
  311. size = Math.Min(data.Length, PageSize - (int)(va & PageMask));
  312. GetHostSpanContiguous(va, size).CopyTo(data.Slice(0, size));
  313. offset += size;
  314. }
  315. for (; offset < data.Length; offset += size)
  316. {
  317. size = Math.Min(data.Length - offset, PageSize);
  318. GetHostSpanContiguous(va + (ulong)offset, size).CopyTo(data.Slice(offset, size));
  319. }
  320. }
  321. catch (InvalidMemoryRegionException)
  322. {
  323. if (_invalidAccessHandler == null || !_invalidAccessHandler(va))
  324. {
  325. throw;
  326. }
  327. }
  328. }
  329. /// <inheritdoc/>
  330. public bool IsRangeMapped(ulong va, ulong size)
  331. {
  332. if (size == 0UL)
  333. {
  334. return true;
  335. }
  336. if (!ValidateAddressAndSize(va, size))
  337. {
  338. return false;
  339. }
  340. int pages = GetPagesCount(va, (uint)size, out va);
  341. for (int page = 0; page < pages; page++)
  342. {
  343. if (!IsMapped(va))
  344. {
  345. return false;
  346. }
  347. va += PageSize;
  348. }
  349. return true;
  350. }
  351. /// <inheritdoc/>
  352. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  353. public bool IsMapped(ulong va)
  354. {
  355. if (!ValidateAddress(va))
  356. {
  357. return false;
  358. }
  359. return _pageTable.Read<nuint>((va / PageSize) * PteSize) != 0;
  360. }
  361. private bool ValidateAddress(ulong va)
  362. {
  363. return va < _addressSpaceSize;
  364. }
  365. /// <summary>
  366. /// Checks if the combination of virtual address and size is part of the addressable space.
  367. /// </summary>
  368. /// <param name="va">Virtual address of the range</param>
  369. /// <param name="size">Size of the range in bytes</param>
  370. /// <returns>True if the combination of virtual address and size is part of the addressable space</returns>
  371. private bool ValidateAddressAndSize(ulong va, ulong size)
  372. {
  373. ulong endVa = va + size;
  374. return endVa >= va && endVa >= size && endVa <= _addressSpaceSize;
  375. }
  376. /// <summary>
  377. /// Ensures the combination of virtual address and size is part of the addressable space.
  378. /// </summary>
  379. /// <param name="va">Virtual address of the range</param>
  380. /// <param name="size">Size of the range in bytes</param>
  381. /// <exception cref="InvalidMemoryRegionException">Throw when the memory region specified outside the addressable space</exception>
  382. private void AssertValidAddressAndSize(ulong va, ulong size)
  383. {
  384. if (!ValidateAddressAndSize(va, size))
  385. {
  386. throw new InvalidMemoryRegionException($"va=0x{va:X16}, size=0x{size:X16}");
  387. }
  388. }
  389. /// <summary>
  390. /// Get a span representing the given virtual address and size range in host memory.
  391. /// This function assumes that the requested virtual memory region is contiguous.
  392. /// </summary>
  393. /// <param name="va">Virtual address of the range</param>
  394. /// <param name="size">Size of the range in bytes</param>
  395. /// <returns>A span representing the given virtual range in host memory</returns>
  396. /// <exception cref="InvalidMemoryRegionException">Throw when the base virtual address is not mapped</exception>
  397. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  398. private unsafe Span<byte> GetHostSpanContiguous(ulong va, int size)
  399. {
  400. return new Span<byte>((void*)GetHostAddress(va), size);
  401. }
  402. /// <summary>
  403. /// Get the host address for a given virtual address, using the page table.
  404. /// </summary>
  405. /// <param name="va">Virtual address</param>
  406. /// <returns>The corresponding host address for the given virtual address</returns>
  407. /// <exception cref="InvalidMemoryRegionException">Throw when the virtual address is not mapped</exception>
  408. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  409. private nuint GetHostAddress(ulong va)
  410. {
  411. nuint pageBase = _pageTable.Read<nuint>((va / PageSize) * PteSize) & unchecked((nuint)0xffff_ffff_ffffUL);
  412. if (pageBase == 0)
  413. {
  414. ThrowInvalidMemoryRegionException($"Not mapped: va=0x{va:X16}");
  415. }
  416. return pageBase + (nuint)(va & PageMask);
  417. }
  418. /// <inheritdoc/>
  419. public void TrackingReprotect(ulong va, ulong size, MemoryPermission protection)
  420. {
  421. AssertValidAddressAndSize(va, size);
  422. // Protection is inverted on software pages, since the default value is 0.
  423. protection = (~protection) & MemoryPermission.ReadAndWrite;
  424. long tag = protection switch
  425. {
  426. MemoryPermission.None => 0L,
  427. MemoryPermission.Write => 2L << PointerTagBit,
  428. _ => 3L << PointerTagBit
  429. };
  430. int pages = GetPagesCount(va, (uint)size, out va);
  431. ulong pageStart = va >> PageBits;
  432. long invTagMask = ~(0xffffL << 48);
  433. for (int page = 0; page < pages; page++)
  434. {
  435. ref long pageRef = ref _pageTable.GetRef<long>(pageStart * PteSize);
  436. long pte;
  437. do
  438. {
  439. pte = Volatile.Read(ref pageRef);
  440. }
  441. while (pte != 0 && Interlocked.CompareExchange(ref pageRef, (pte & invTagMask) | tag, pte) != pte);
  442. pageStart++;
  443. }
  444. }
  445. /// <inheritdoc/>
  446. public CpuRegionHandle BeginTracking(ulong address, ulong size)
  447. {
  448. return new CpuRegionHandle(Tracking.BeginTracking(address, size));
  449. }
  450. /// <inheritdoc/>
  451. public CpuMultiRegionHandle BeginGranularTracking(ulong address, ulong size, IEnumerable<IRegionHandle> handles, ulong granularity)
  452. {
  453. return new CpuMultiRegionHandle(Tracking.BeginGranularTracking(address, size, handles, granularity));
  454. }
  455. /// <inheritdoc/>
  456. public CpuSmartMultiRegionHandle BeginSmartGranularTracking(ulong address, ulong size, ulong granularity)
  457. {
  458. return new CpuSmartMultiRegionHandle(Tracking.BeginSmartGranularTracking(address, size, granularity));
  459. }
  460. /// <inheritdoc/>
  461. public void SignalMemoryTracking(ulong va, ulong size, bool write)
  462. {
  463. AssertValidAddressAndSize(va, size);
  464. // We emulate guard pages for software memory access. This makes for an easy transition to
  465. // tracking using host guard pages in future, but also supporting platforms where this is not possible.
  466. // Write tag includes read protection, since we don't have any read actions that aren't performed before write too.
  467. long tag = (write ? 3L : 1L) << PointerTagBit;
  468. int pages = GetPagesCount(va, (uint)size, out _);
  469. ulong pageStart = va >> PageBits;
  470. for (int page = 0; page < pages; page++)
  471. {
  472. ref long pageRef = ref _pageTable.GetRef<long>(pageStart * PteSize);
  473. long pte;
  474. pte = Volatile.Read(ref pageRef);
  475. if ((pte & tag) != 0)
  476. {
  477. Tracking.VirtualMemoryEvent(va, size, write);
  478. break;
  479. }
  480. pageStart++;
  481. }
  482. }
  483. /// <summary>
  484. /// Disposes of resources used by the memory manager.
  485. /// </summary>
  486. protected override void Destroy() => _pageTable.Dispose();
  487. private void ThrowInvalidMemoryRegionException(string message) => throw new InvalidMemoryRegionException(message);
  488. }
  489. }