MemoryManager.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603
  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)
  195. {
  196. if (size == 0)
  197. {
  198. return new WritableRegion(null, va, Memory<byte>.Empty);
  199. }
  200. if (IsContiguousAndMapped(va, size))
  201. {
  202. return new WritableRegion(null, va, new NativeMemoryManager<byte>((byte*)GetHostAddress(va), size).Memory);
  203. }
  204. else
  205. {
  206. Memory<byte> memory = new byte[size];
  207. GetSpan(va, size).CopyTo(memory.Span);
  208. return new WritableRegion(this, va, memory);
  209. }
  210. }
  211. /// <inheritdoc/>
  212. public unsafe ref T GetRef<T>(ulong va) where T : unmanaged
  213. {
  214. if (!IsContiguous(va, Unsafe.SizeOf<T>()))
  215. {
  216. ThrowMemoryNotContiguous();
  217. }
  218. SignalMemoryTracking(va, (ulong)Unsafe.SizeOf<T>(), true);
  219. return ref *(T*)GetHostAddress(va);
  220. }
  221. /// <summary>
  222. /// Computes the number of pages in a virtual address range.
  223. /// </summary>
  224. /// <param name="va">Virtual address of the range</param>
  225. /// <param name="size">Size of the range</param>
  226. /// <param name="startVa">The virtual address of the beginning of the first page</param>
  227. /// <remarks>This function does not differentiate between allocated and unallocated pages.</remarks>
  228. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  229. private int GetPagesCount(ulong va, uint size, out ulong startVa)
  230. {
  231. // WARNING: Always check if ulong does not overflow during the operations.
  232. startVa = va & ~(ulong)PageMask;
  233. ulong vaSpan = (va - startVa + size + PageMask) & ~(ulong)PageMask;
  234. return (int)(vaSpan / PageSize);
  235. }
  236. private void ThrowMemoryNotContiguous() => throw new MemoryNotContiguousException();
  237. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  238. private bool IsContiguousAndMapped(ulong va, int size) => IsContiguous(va, size) && IsMapped(va);
  239. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  240. private bool IsContiguous(ulong va, int size)
  241. {
  242. if (!ValidateAddress(va) || !ValidateAddressAndSize(va, (ulong)size))
  243. {
  244. return false;
  245. }
  246. int pages = GetPagesCount(va, (uint)size, out va);
  247. for (int page = 0; page < pages - 1; page++)
  248. {
  249. if (!ValidateAddress(va + PageSize))
  250. {
  251. return false;
  252. }
  253. if (GetHostAddress(va) + PageSize != GetHostAddress(va + PageSize))
  254. {
  255. return false;
  256. }
  257. va += PageSize;
  258. }
  259. return true;
  260. }
  261. /// <inheritdoc/>
  262. public IEnumerable<HostMemoryRange> GetPhysicalRegions(ulong va, ulong size)
  263. {
  264. if (size == 0)
  265. {
  266. return Enumerable.Empty<HostMemoryRange>();
  267. }
  268. if (!ValidateAddress(va) || !ValidateAddressAndSize(va, size))
  269. {
  270. return null;
  271. }
  272. int pages = GetPagesCount(va, (uint)size, out va);
  273. var regions = new List<HostMemoryRange>();
  274. nuint regionStart = GetHostAddress(va);
  275. ulong regionSize = PageSize;
  276. for (int page = 0; page < pages - 1; page++)
  277. {
  278. if (!ValidateAddress(va + PageSize))
  279. {
  280. return null;
  281. }
  282. nuint newHostAddress = GetHostAddress(va + PageSize);
  283. if (GetHostAddress(va) + PageSize != newHostAddress)
  284. {
  285. regions.Add(new HostMemoryRange(regionStart, regionSize));
  286. regionStart = newHostAddress;
  287. regionSize = 0;
  288. }
  289. va += PageSize;
  290. regionSize += PageSize;
  291. }
  292. regions.Add(new HostMemoryRange(regionStart, regionSize));
  293. return regions;
  294. }
  295. private void ReadImpl(ulong va, Span<byte> data)
  296. {
  297. if (data.Length == 0)
  298. {
  299. return;
  300. }
  301. try
  302. {
  303. AssertValidAddressAndSize(va, (ulong)data.Length);
  304. int offset = 0, size;
  305. if ((va & PageMask) != 0)
  306. {
  307. size = Math.Min(data.Length, PageSize - (int)(va & PageMask));
  308. GetHostSpanContiguous(va, size).CopyTo(data.Slice(0, size));
  309. offset += size;
  310. }
  311. for (; offset < data.Length; offset += size)
  312. {
  313. size = Math.Min(data.Length - offset, PageSize);
  314. GetHostSpanContiguous(va + (ulong)offset, size).CopyTo(data.Slice(offset, size));
  315. }
  316. }
  317. catch (InvalidMemoryRegionException)
  318. {
  319. if (_invalidAccessHandler == null || !_invalidAccessHandler(va))
  320. {
  321. throw;
  322. }
  323. }
  324. }
  325. /// <inheritdoc/>
  326. public bool IsRangeMapped(ulong va, ulong size)
  327. {
  328. if (size == 0UL)
  329. {
  330. return true;
  331. }
  332. if (!ValidateAddressAndSize(va, size))
  333. {
  334. return false;
  335. }
  336. int pages = GetPagesCount(va, (uint)size, out va);
  337. for (int page = 0; page < pages; page++)
  338. {
  339. if (!IsMapped(va))
  340. {
  341. return false;
  342. }
  343. va += PageSize;
  344. }
  345. return true;
  346. }
  347. /// <inheritdoc/>
  348. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  349. public bool IsMapped(ulong va)
  350. {
  351. if (!ValidateAddress(va))
  352. {
  353. return false;
  354. }
  355. return _pageTable.Read<nuint>((va / PageSize) * PteSize) != 0;
  356. }
  357. private bool ValidateAddress(ulong va)
  358. {
  359. return va < _addressSpaceSize;
  360. }
  361. /// <summary>
  362. /// Checks if the combination of virtual address and size is part of the addressable space.
  363. /// </summary>
  364. /// <param name="va">Virtual address of the range</param>
  365. /// <param name="size">Size of the range in bytes</param>
  366. /// <returns>True if the combination of virtual address and size is part of the addressable space</returns>
  367. private bool ValidateAddressAndSize(ulong va, ulong size)
  368. {
  369. ulong endVa = va + size;
  370. return endVa >= va && endVa >= size && endVa <= _addressSpaceSize;
  371. }
  372. /// <summary>
  373. /// Ensures the combination of virtual address and size is part of the addressable space.
  374. /// </summary>
  375. /// <param name="va">Virtual address of the range</param>
  376. /// <param name="size">Size of the range in bytes</param>
  377. /// <exception cref="InvalidMemoryRegionException">Throw when the memory region specified outside the addressable space</exception>
  378. private void AssertValidAddressAndSize(ulong va, ulong size)
  379. {
  380. if (!ValidateAddressAndSize(va, size))
  381. {
  382. throw new InvalidMemoryRegionException($"va=0x{va:X16}, size=0x{size:X16}");
  383. }
  384. }
  385. /// <summary>
  386. /// Get a span representing the given virtual address and size range in host memory.
  387. /// This function assumes that the requested virtual memory region is contiguous.
  388. /// </summary>
  389. /// <param name="va">Virtual address of the range</param>
  390. /// <param name="size">Size of the range in bytes</param>
  391. /// <returns>A span representing the given virtual range in host memory</returns>
  392. /// <exception cref="InvalidMemoryRegionException">Throw when the base virtual address is not mapped</exception>
  393. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  394. private unsafe Span<byte> GetHostSpanContiguous(ulong va, int size)
  395. {
  396. return new Span<byte>((void*)GetHostAddress(va), size);
  397. }
  398. /// <summary>
  399. /// Get the host address for a given virtual address, using the page table.
  400. /// </summary>
  401. /// <param name="va">Virtual address</param>
  402. /// <returns>The corresponding host address for the given virtual address</returns>
  403. /// <exception cref="InvalidMemoryRegionException">Throw when the virtual address is not mapped</exception>
  404. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  405. private nuint GetHostAddress(ulong va)
  406. {
  407. nuint pageBase = _pageTable.Read<nuint>((va / PageSize) * PteSize) & unchecked((nuint)0xffff_ffff_ffffUL);
  408. if (pageBase == 0)
  409. {
  410. ThrowInvalidMemoryRegionException($"Not mapped: va=0x{va:X16}");
  411. }
  412. return pageBase + (nuint)(va & PageMask);
  413. }
  414. /// <inheritdoc/>
  415. public void TrackingReprotect(ulong va, ulong size, MemoryPermission protection)
  416. {
  417. AssertValidAddressAndSize(va, size);
  418. // Protection is inverted on software pages, since the default value is 0.
  419. protection = (~protection) & MemoryPermission.ReadAndWrite;
  420. long tag = protection switch
  421. {
  422. MemoryPermission.None => 0L,
  423. MemoryPermission.Write => 2L << PointerTagBit,
  424. _ => 3L << PointerTagBit
  425. };
  426. int pages = GetPagesCount(va, (uint)size, out va);
  427. ulong pageStart = va >> PageBits;
  428. long invTagMask = ~(0xffffL << 48);
  429. for (int page = 0; page < pages; page++)
  430. {
  431. ref long pageRef = ref _pageTable.GetRef<long>(pageStart * PteSize);
  432. long pte;
  433. do
  434. {
  435. pte = Volatile.Read(ref pageRef);
  436. }
  437. while (pte != 0 && Interlocked.CompareExchange(ref pageRef, (pte & invTagMask) | tag, pte) != pte);
  438. pageStart++;
  439. }
  440. }
  441. /// <inheritdoc/>
  442. public CpuRegionHandle BeginTracking(ulong address, ulong size)
  443. {
  444. return new CpuRegionHandle(Tracking.BeginTracking(address, size));
  445. }
  446. /// <inheritdoc/>
  447. public CpuMultiRegionHandle BeginGranularTracking(ulong address, ulong size, IEnumerable<IRegionHandle> handles, ulong granularity)
  448. {
  449. return new CpuMultiRegionHandle(Tracking.BeginGranularTracking(address, size, handles, granularity));
  450. }
  451. /// <inheritdoc/>
  452. public CpuSmartMultiRegionHandle BeginSmartGranularTracking(ulong address, ulong size, ulong granularity)
  453. {
  454. return new CpuSmartMultiRegionHandle(Tracking.BeginSmartGranularTracking(address, size, granularity));
  455. }
  456. /// <inheritdoc/>
  457. public void SignalMemoryTracking(ulong va, ulong size, bool write)
  458. {
  459. AssertValidAddressAndSize(va, size);
  460. // We emulate guard pages for software memory access. This makes for an easy transition to
  461. // tracking using host guard pages in future, but also supporting platforms where this is not possible.
  462. // Write tag includes read protection, since we don't have any read actions that aren't performed before write too.
  463. long tag = (write ? 3L : 1L) << PointerTagBit;
  464. int pages = GetPagesCount(va, (uint)size, out _);
  465. ulong pageStart = va >> PageBits;
  466. for (int page = 0; page < pages; page++)
  467. {
  468. ref long pageRef = ref _pageTable.GetRef<long>(pageStart * PteSize);
  469. long pte;
  470. pte = Volatile.Read(ref pageRef);
  471. if ((pte & tag) != 0)
  472. {
  473. Tracking.VirtualMemoryEvent(va, size, write);
  474. break;
  475. }
  476. pageStart++;
  477. }
  478. }
  479. /// <summary>
  480. /// Disposes of resources used by the memory manager.
  481. /// </summary>
  482. protected override void Destroy() => _pageTable.Dispose();
  483. private void ThrowInvalidMemoryRegionException(string message) => throw new InvalidMemoryRegionException(message);
  484. }
  485. }