MemoryManager.cs 19 KB

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