MemoryManager.cs 23 KB

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