MemoryManager.cs 26 KB

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