MemoryManager.cs 23 KB

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