MemoryManager.cs 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671
  1. using ARMeilleure.Memory;
  2. using Ryujinx.Cpu.Tracking;
  3. using Ryujinx.Memory;
  4. using Ryujinx.Memory.Tracking;
  5. using System;
  6. using System.Collections.Generic;
  7. using System.Runtime.CompilerServices;
  8. using System.Runtime.InteropServices;
  9. using System.Threading;
  10. namespace Ryujinx.Cpu
  11. {
  12. /// <summary>
  13. /// Represents a CPU memory manager.
  14. /// </summary>
  15. public sealed class MemoryManager : IMemoryManager, IVirtualMemoryManager, IWritableBlock, IDisposable
  16. {
  17. public const int PageBits = 12;
  18. public const int PageSize = 1 << PageBits;
  19. public const int PageMask = PageSize - 1;
  20. private const int PteSize = 8;
  21. private const int PointerTagBit = 62;
  22. private readonly InvalidAccessHandler _invalidAccessHandler;
  23. /// <summary>
  24. /// Address space width in bits.
  25. /// </summary>
  26. public int AddressSpaceBits { get; }
  27. private readonly ulong _addressSpaceSize;
  28. private readonly MemoryBlock _backingMemory;
  29. private readonly MemoryBlock _pageTable;
  30. /// <summary>
  31. /// Page table base pointer.
  32. /// </summary>
  33. public IntPtr PageTablePointer => _pageTable.Pointer;
  34. public MemoryTracking Tracking { get; }
  35. internal event Action<ulong, ulong> UnmapEvent;
  36. /// <summary>
  37. /// Creates a new instance of the memory manager.
  38. /// </summary>
  39. /// <param name="backingMemory">Physical backing memory where virtual memory will be mapped to</param>
  40. /// <param name="addressSpaceSize">Size of the address space</param>
  41. /// <param name="invalidAccessHandler">Optional function to handle invalid memory accesses</param>
  42. public MemoryManager(MemoryBlock backingMemory, ulong addressSpaceSize, InvalidAccessHandler invalidAccessHandler = null)
  43. {
  44. _invalidAccessHandler = invalidAccessHandler;
  45. ulong asSize = PageSize;
  46. int asBits = PageBits;
  47. while (asSize < addressSpaceSize)
  48. {
  49. asSize <<= 1;
  50. asBits++;
  51. }
  52. AddressSpaceBits = asBits;
  53. _addressSpaceSize = asSize;
  54. _backingMemory = backingMemory;
  55. _pageTable = new MemoryBlock((asSize / PageSize) * PteSize);
  56. Tracking = new MemoryTracking(this, backingMemory, PageSize);
  57. Tracking.EnablePhysicalProtection = false; // Disabled for now, as protection is done in software.
  58. }
  59. /// <summary>
  60. /// Maps a virtual memory range into a physical memory range.
  61. /// </summary>
  62. /// <remarks>
  63. /// Addresses and size must be page aligned.
  64. /// </remarks>
  65. /// <param name="va">Virtual memory address</param>
  66. /// <param name="pa">Physical memory address</param>
  67. /// <param name="size">Size to be mapped</param>
  68. public void Map(ulong va, ulong pa, ulong size)
  69. {
  70. ulong remainingSize = size;
  71. ulong oVa = va;
  72. ulong oPa = pa;
  73. while (remainingSize != 0)
  74. {
  75. _pageTable.Write((va / PageSize) * PteSize, PaToPte(pa));
  76. va += PageSize;
  77. pa += PageSize;
  78. remainingSize -= PageSize;
  79. }
  80. Tracking.Map(oVa, oPa, size);
  81. }
  82. /// <summary>
  83. /// Unmaps a previously mapped range of virtual memory.
  84. /// </summary>
  85. /// <param name="va">Virtual address of the range to be unmapped</param>
  86. /// <param name="size">Size of the range to be unmapped</param>
  87. public void Unmap(ulong va, ulong size)
  88. {
  89. // If size is 0, there's nothing to unmap, just exit early.
  90. if (size == 0)
  91. {
  92. return;
  93. }
  94. UnmapEvent?.Invoke(va, size);
  95. ulong remainingSize = size;
  96. ulong oVa = va;
  97. while (remainingSize != 0)
  98. {
  99. _pageTable.Write((va / PageSize) * PteSize, 0UL);
  100. va += PageSize;
  101. remainingSize -= PageSize;
  102. }
  103. Tracking.Unmap(oVa, size);
  104. }
  105. /// <summary>
  106. /// Reads data from CPU mapped memory.
  107. /// </summary>
  108. /// <typeparam name="T">Type of the data being read</typeparam>
  109. /// <param name="va">Virtual address of the data in memory</param>
  110. /// <returns>The data</returns>
  111. /// <exception cref="InvalidMemoryRegionException">Throw for unhandled invalid or unmapped memory accesses</exception>
  112. public T Read<T>(ulong va) where T : unmanaged
  113. {
  114. return MemoryMarshal.Cast<byte, T>(GetSpan(va, Unsafe.SizeOf<T>(), true))[0];
  115. }
  116. /// <summary>
  117. /// Reads data from CPU mapped memory, with read tracking
  118. /// </summary>
  119. /// <typeparam name="T">Type of the data being read</typeparam>
  120. /// <param name="va">Virtual address of the data in memory</param>
  121. /// <returns>The data</returns>
  122. public T ReadTracked<T>(ulong va) where T : unmanaged
  123. {
  124. SignalMemoryTracking(va, (ulong)Unsafe.SizeOf<T>(), false);
  125. return MemoryMarshal.Cast<byte, T>(GetSpan(va, Unsafe.SizeOf<T>()))[0];
  126. }
  127. /// <summary>
  128. /// Reads data from CPU mapped memory.
  129. /// </summary>
  130. /// <param name="va">Virtual address of the data in memory</param>
  131. /// <param name="data">Span to store the data being read into</param>
  132. /// <exception cref="InvalidMemoryRegionException">Throw for unhandled invalid or unmapped memory accesses</exception>
  133. public void Read(ulong va, Span<byte> data)
  134. {
  135. ReadImpl(va, data);
  136. }
  137. /// <summary>
  138. /// Writes data to CPU mapped memory.
  139. /// </summary>
  140. /// <typeparam name="T">Type of the data being written</typeparam>
  141. /// <param name="va">Virtual address to write the data into</param>
  142. /// <param name="value">Data to be written</param>
  143. /// <exception cref="InvalidMemoryRegionException">Throw for unhandled invalid or unmapped memory accesses</exception>
  144. public void Write<T>(ulong va, T value) where T : unmanaged
  145. {
  146. Write(va, MemoryMarshal.Cast<T, byte>(MemoryMarshal.CreateSpan(ref value, 1)));
  147. }
  148. /// <summary>
  149. /// Writes data to CPU mapped memory, with write tracking.
  150. /// </summary>
  151. /// <param name="va">Virtual address to write the data into</param>
  152. /// <param name="data">Data to be written</param>
  153. /// <exception cref="InvalidMemoryRegionException">Throw for unhandled invalid or unmapped memory accesses</exception>
  154. public void Write(ulong va, ReadOnlySpan<byte> data)
  155. {
  156. if (data.Length == 0)
  157. {
  158. return;
  159. }
  160. SignalMemoryTracking(va, (ulong)data.Length, true);
  161. WriteImpl(va, data);
  162. }
  163. /// <summary>
  164. /// Writes data to CPU mapped memory, without write tracking.
  165. /// </summary>
  166. /// <param name="va">Virtual address to write the data into</param>
  167. /// <param name="data">Data to be written</param>
  168. public void WriteUntracked(ulong va, ReadOnlySpan<byte> data)
  169. {
  170. if (data.Length == 0)
  171. {
  172. return;
  173. }
  174. WriteImpl(va, data);
  175. }
  176. /// <summary>
  177. /// Writes data to CPU mapped memory.
  178. /// </summary>
  179. /// <param name="va">Virtual address to write the data into</param>
  180. /// <param name="data">Data to be written</param>
  181. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  182. private void WriteImpl(ulong va, ReadOnlySpan<byte> data)
  183. {
  184. try
  185. {
  186. if (IsContiguousAndMapped(va, data.Length))
  187. {
  188. data.CopyTo(_backingMemory.GetSpan(GetPhysicalAddressInternal(va), data.Length));
  189. }
  190. else
  191. {
  192. int offset = 0, size;
  193. if ((va & PageMask) != 0)
  194. {
  195. ulong pa = GetPhysicalAddressInternal(va);
  196. size = Math.Min(data.Length, PageSize - (int)(va & PageMask));
  197. data.Slice(0, size).CopyTo(_backingMemory.GetSpan(pa, size));
  198. offset += size;
  199. }
  200. for (; offset < data.Length; offset += size)
  201. {
  202. ulong pa = GetPhysicalAddressInternal(va + (ulong)offset);
  203. size = Math.Min(data.Length - offset, PageSize);
  204. data.Slice(offset, size).CopyTo(_backingMemory.GetSpan(pa, size));
  205. }
  206. }
  207. }
  208. catch (InvalidMemoryRegionException)
  209. {
  210. if (_invalidAccessHandler == null || !_invalidAccessHandler(va))
  211. {
  212. throw;
  213. }
  214. }
  215. }
  216. /// <summary>
  217. /// Gets a read-only span of data from CPU mapped memory.
  218. /// </summary>
  219. /// <remarks>
  220. /// This may perform a allocation if the data is not contiguous in memory.
  221. /// For this reason, the span is read-only, you can't modify the data.
  222. /// </remarks>
  223. /// <param name="va">Virtual address of the data</param>
  224. /// <param name="size">Size of the data</param>
  225. /// <param name="tracked">True if read tracking is triggered on the span</param>
  226. /// <returns>A read-only span of the data</returns>
  227. /// <exception cref="InvalidMemoryRegionException">Throw for unhandled invalid or unmapped memory accesses</exception>
  228. public ReadOnlySpan<byte> GetSpan(ulong va, int size, bool tracked = false)
  229. {
  230. if (size == 0)
  231. {
  232. return ReadOnlySpan<byte>.Empty;
  233. }
  234. if (tracked)
  235. {
  236. SignalMemoryTracking(va, (ulong)size, false);
  237. }
  238. if (IsContiguousAndMapped(va, size))
  239. {
  240. return _backingMemory.GetSpan(GetPhysicalAddressInternal(va), size);
  241. }
  242. else
  243. {
  244. Span<byte> data = new byte[size];
  245. ReadImpl(va, data);
  246. return data;
  247. }
  248. }
  249. /// <summary>
  250. /// Gets a region of memory that can be written to.
  251. /// </summary>
  252. /// <remarks>
  253. /// If the requested region is not contiguous in physical memory,
  254. /// this will perform an allocation, and flush the data (writing it
  255. /// back to guest memory) on disposal.
  256. /// </remarks>
  257. /// <param name="va">Virtual address of the data</param>
  258. /// <param name="size">Size of the data</param>
  259. /// <returns>A writable region of memory containing the data</returns>
  260. /// <exception cref="InvalidMemoryRegionException">Throw for unhandled invalid or unmapped memory accesses</exception>
  261. public WritableRegion GetWritableRegion(ulong va, int size)
  262. {
  263. if (size == 0)
  264. {
  265. return new WritableRegion(null, va, Memory<byte>.Empty);
  266. }
  267. if (IsContiguousAndMapped(va, size))
  268. {
  269. return new WritableRegion(null, va, _backingMemory.GetMemory(GetPhysicalAddressInternal(va), size));
  270. }
  271. else
  272. {
  273. Memory<byte> memory = new byte[size];
  274. GetSpan(va, size).CopyTo(memory.Span);
  275. return new WritableRegion(this, va, memory);
  276. }
  277. }
  278. /// <summary>
  279. /// Gets a reference for the given type at the specified virtual memory address.
  280. /// </summary>
  281. /// <remarks>
  282. /// The data must be located at a contiguous memory region.
  283. /// </remarks>
  284. /// <typeparam name="T">Type of the data to get the reference</typeparam>
  285. /// <param name="va">Virtual address of the data</param>
  286. /// <returns>A reference to the data in memory</returns>
  287. /// <exception cref="MemoryNotContiguousException">Throw if the specified memory region is not contiguous in physical memory</exception>
  288. public ref T GetRef<T>(ulong va) where T : unmanaged
  289. {
  290. if (!IsContiguous(va, Unsafe.SizeOf<T>()))
  291. {
  292. ThrowMemoryNotContiguous();
  293. }
  294. SignalMemoryTracking(va, (ulong)Unsafe.SizeOf<T>(), true);
  295. return ref _backingMemory.GetRef<T>(GetPhysicalAddressInternal(va));
  296. }
  297. private void ThrowMemoryNotContiguous() => throw new MemoryNotContiguousException();
  298. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  299. private bool IsContiguousAndMapped(ulong va, int size) => IsContiguous(va, size) && IsMapped(va);
  300. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  301. private bool IsContiguous(ulong va, int size)
  302. {
  303. if (!ValidateAddress(va))
  304. {
  305. return false;
  306. }
  307. ulong endVa = (va + (ulong)size + PageMask) & ~(ulong)PageMask;
  308. va &= ~(ulong)PageMask;
  309. int pages = (int)((endVa - va) / PageSize);
  310. for (int page = 0; page < pages - 1; page++)
  311. {
  312. if (!ValidateAddress(va + PageSize))
  313. {
  314. return false;
  315. }
  316. if (GetPhysicalAddressInternal(va) + PageSize != GetPhysicalAddressInternal(va + PageSize))
  317. {
  318. return false;
  319. }
  320. va += PageSize;
  321. }
  322. return true;
  323. }
  324. /// <summary>
  325. /// Gets the physical regions that make up the given virtual address region.
  326. /// If any part of the virtual region is unmapped, null is returned.
  327. /// </summary>
  328. /// <param name="va">Virtual address of the range</param>
  329. /// <param name="size">Size of the range</param>
  330. /// <returns>Array of physical regions</returns>
  331. public (ulong address, ulong size)[] GetPhysicalRegions(ulong va, ulong size)
  332. {
  333. if (!ValidateAddress(va))
  334. {
  335. return null;
  336. }
  337. ulong endVa = (va + size + PageMask) & ~(ulong)PageMask;
  338. va &= ~(ulong)PageMask;
  339. int pages = (int)((endVa - va) / PageSize);
  340. List<(ulong, ulong)> regions = new List<(ulong, ulong)>();
  341. ulong regionStart = GetPhysicalAddressInternal(va);
  342. ulong regionSize = PageSize;
  343. for (int page = 0; page < pages - 1; page++)
  344. {
  345. if (!ValidateAddress(va + PageSize))
  346. {
  347. return null;
  348. }
  349. ulong newPa = GetPhysicalAddressInternal(va + PageSize);
  350. if (GetPhysicalAddressInternal(va) + PageSize != newPa)
  351. {
  352. regions.Add((regionStart, regionSize));
  353. regionStart = newPa;
  354. regionSize = 0;
  355. }
  356. va += PageSize;
  357. regionSize += PageSize;
  358. }
  359. regions.Add((regionStart, regionSize));
  360. return regions.ToArray();
  361. }
  362. private void ReadImpl(ulong va, Span<byte> data)
  363. {
  364. if (data.Length == 0)
  365. {
  366. return;
  367. }
  368. try
  369. {
  370. int offset = 0, size;
  371. if ((va & PageMask) != 0)
  372. {
  373. ulong pa = GetPhysicalAddressInternal(va);
  374. size = Math.Min(data.Length, PageSize - (int)(va & PageMask));
  375. _backingMemory.GetSpan(pa, size).CopyTo(data.Slice(0, size));
  376. offset += size;
  377. }
  378. for (; offset < data.Length; offset += size)
  379. {
  380. ulong pa = GetPhysicalAddressInternal(va + (ulong)offset);
  381. size = Math.Min(data.Length - offset, PageSize);
  382. _backingMemory.GetSpan(pa, size).CopyTo(data.Slice(offset, size));
  383. }
  384. }
  385. catch (InvalidMemoryRegionException)
  386. {
  387. if (_invalidAccessHandler == null || !_invalidAccessHandler(va))
  388. {
  389. throw;
  390. }
  391. }
  392. }
  393. /// <summary>
  394. /// Checks if a memory range is mapped.
  395. /// </summary>
  396. /// <param name="va">Virtual address of the range</param>
  397. /// <param name="size">Size of the range in bytes</param>
  398. /// <returns>True if the entire range is mapped, false otherwise</returns>
  399. public bool IsRangeMapped(ulong va, ulong size)
  400. {
  401. if (size == 0UL)
  402. {
  403. return true;
  404. }
  405. ulong endVa = (va + size + PageMask) & ~(ulong)PageMask;
  406. va &= ~(ulong)PageMask;
  407. while (va < endVa)
  408. {
  409. if (!IsMapped(va))
  410. {
  411. return false;
  412. }
  413. va += PageSize;
  414. }
  415. return true;
  416. }
  417. /// <summary>
  418. /// Checks if the page at a given CPU virtual address is mapped.
  419. /// </summary>
  420. /// <param name="va">Virtual address to check</param>
  421. /// <returns>True if the address is mapped, false otherwise</returns>
  422. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  423. public bool IsMapped(ulong va)
  424. {
  425. if (!ValidateAddress(va))
  426. {
  427. return false;
  428. }
  429. return _pageTable.Read<ulong>((va / PageSize) * PteSize) != 0;
  430. }
  431. private bool ValidateAddress(ulong va)
  432. {
  433. return va < _addressSpaceSize;
  434. }
  435. /// <summary>
  436. /// Performs address translation of the address inside a CPU mapped memory range.
  437. /// </summary>
  438. /// <remarks>
  439. /// If the address is invalid or unmapped, -1 will be returned.
  440. /// </remarks>
  441. /// <param name="va">Virtual address to be translated</param>
  442. /// <returns>The physical address</returns>
  443. public ulong GetPhysicalAddress(ulong va)
  444. {
  445. // We return -1L if the virtual address is invalid or unmapped.
  446. if (!ValidateAddress(va) || !IsMapped(va))
  447. {
  448. return ulong.MaxValue;
  449. }
  450. return GetPhysicalAddressInternal(va);
  451. }
  452. private ulong GetPhysicalAddressInternal(ulong va)
  453. {
  454. return PteToPa(_pageTable.Read<ulong>((va / PageSize) * PteSize) & ~(0xffffUL << 48)) + (va & PageMask);
  455. }
  456. /// <summary>
  457. /// Reprotect a region of virtual memory for tracking. Sets software protection bits.
  458. /// </summary>
  459. /// <param name="va">Virtual address base</param>
  460. /// <param name="size">Size of the region to protect</param>
  461. /// <param name="protection">Memory protection to set</param>
  462. public void TrackingReprotect(ulong va, ulong size, MemoryPermission protection)
  463. {
  464. // Protection is inverted on software pages, since the default value is 0.
  465. protection = (~protection) & MemoryPermission.ReadAndWrite;
  466. long tag = protection switch
  467. {
  468. MemoryPermission.None => 0L,
  469. MemoryPermission.Read => 2L << PointerTagBit,
  470. _ => 3L << PointerTagBit
  471. };
  472. ulong endVa = (va + size + PageMask) & ~(ulong)PageMask;
  473. long invTagMask = ~(0xffffL << 48);
  474. while (va < endVa)
  475. {
  476. ref long pageRef = ref _pageTable.GetRef<long>((va >> PageBits) * PteSize);
  477. long pte;
  478. do
  479. {
  480. pte = Volatile.Read(ref pageRef);
  481. }
  482. while (Interlocked.CompareExchange(ref pageRef, (pte & invTagMask) | tag, pte) != pte);
  483. va += PageSize;
  484. }
  485. }
  486. /// <summary>
  487. /// Obtains a memory tracking handle for the given virtual region. This should be disposed when finished with.
  488. /// </summary>
  489. /// <param name="address">CPU virtual address of the region</param>
  490. /// <param name="size">Size of the region</param>
  491. /// <returns>The memory tracking handle</returns>
  492. public CpuRegionHandle BeginTracking(ulong address, ulong size)
  493. {
  494. return new CpuRegionHandle(Tracking.BeginTracking(address, size));
  495. }
  496. /// <summary>
  497. /// Obtains a memory tracking handle for the given virtual region, with a specified granularity. This should be disposed when finished with.
  498. /// </summary>
  499. /// <param name="address">CPU virtual address of the region</param>
  500. /// <param name="size">Size of the region</param>
  501. /// <param name="granularity">Desired granularity of write tracking</param>
  502. /// <returns>The memory tracking handle</returns>
  503. public CpuMultiRegionHandle BeginGranularTracking(ulong address, ulong size, ulong granularity)
  504. {
  505. return new CpuMultiRegionHandle(Tracking.BeginGranularTracking(address, size, granularity));
  506. }
  507. /// <summary>
  508. /// Obtains a smart memory tracking handle for the given virtual region, with a specified granularity. This should be disposed when finished with.
  509. /// </summary>
  510. /// <param name="address">CPU virtual address of the region</param>
  511. /// <param name="size">Size of the region</param>
  512. /// <param name="granularity">Desired granularity of write tracking</param>
  513. /// <returns>The memory tracking handle</returns>
  514. public CpuSmartMultiRegionHandle BeginSmartGranularTracking(ulong address, ulong size, ulong granularity)
  515. {
  516. return new CpuSmartMultiRegionHandle(Tracking.BeginSmartGranularTracking(address, size, granularity));
  517. }
  518. /// <summary>
  519. /// Alerts the memory tracking that a given region has been read from or written to.
  520. /// This should be called before read/write is performed.
  521. /// </summary>
  522. /// <param name="va">Virtual address of the region</param>
  523. /// <param name="size">Size of the region</param>
  524. public void SignalMemoryTracking(ulong va, ulong size, bool write)
  525. {
  526. // We emulate guard pages for software memory access. This makes for an easy transition to
  527. // tracking using host guard pages in future, but also supporting platforms where this is not possible.
  528. // Write tag includes read protection, since we don't have any read actions that aren't performed before write too.
  529. long tag = (write ? 3L : 2L) << PointerTagBit;
  530. ulong endVa = (va + size + PageMask) & ~(ulong)PageMask;
  531. while (va < endVa)
  532. {
  533. ref long pageRef = ref _pageTable.GetRef<long>((va >> PageBits) * PteSize);
  534. long pte;
  535. pte = Volatile.Read(ref pageRef);
  536. if ((pte & tag) != 0)
  537. {
  538. Tracking.VirtualMemoryEvent(va, size, write);
  539. break;
  540. }
  541. va += PageSize;
  542. }
  543. }
  544. private ulong PaToPte(ulong pa)
  545. {
  546. return (ulong)_backingMemory.GetPointer(pa, PageSize).ToInt64();
  547. }
  548. private ulong PteToPa(ulong pte)
  549. {
  550. return (ulong)((long)pte - _backingMemory.Pointer.ToInt64());
  551. }
  552. /// <summary>
  553. /// Disposes of resources used by the memory manager.
  554. /// </summary>
  555. public void Dispose() => _pageTable.Dispose();
  556. }
  557. }