MemoryManager.cs 26 KB

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