MemoryManagerHostMapped.cs 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817
  1. using ARMeilleure.Memory;
  2. using Ryujinx.Cpu.Tracking;
  3. using Ryujinx.Memory;
  4. using Ryujinx.Memory.Range;
  5. using Ryujinx.Memory.Tracking;
  6. using System;
  7. using System.Collections.Generic;
  8. using System.Linq;
  9. using System.Runtime.CompilerServices;
  10. using System.Threading;
  11. namespace Ryujinx.Cpu.Jit
  12. {
  13. /// <summary>
  14. /// Represents a CPU memory manager which maps guest virtual memory directly onto a host virtual region.
  15. /// </summary>
  16. public sealed class MemoryManagerHostMapped : MemoryManagerBase, IMemoryManager, IVirtualMemoryManagerTracked, IWritableBlock
  17. {
  18. public const int PageBits = 12;
  19. public const int PageSize = 1 << PageBits;
  20. public const int PageMask = PageSize - 1;
  21. public const int PageToPteShift = 5; // 32 pages (2 bits each) in one ulong page table entry.
  22. public const ulong BlockMappedMask = 0x5555555555555555; // First bit of each table entry set.
  23. private enum HostMappedPtBits : ulong
  24. {
  25. Unmapped = 0,
  26. Mapped,
  27. WriteTracked,
  28. ReadWriteTracked,
  29. MappedReplicated = 0x5555555555555555,
  30. WriteTrackedReplicated = 0xaaaaaaaaaaaaaaaa,
  31. ReadWriteTrackedReplicated = ulong.MaxValue
  32. }
  33. private readonly InvalidAccessHandler _invalidAccessHandler;
  34. private readonly bool _unsafeMode;
  35. private readonly AddressSpace _addressSpace;
  36. private readonly ulong _addressSpaceSize;
  37. private readonly PageTable<ulong> _pageTable;
  38. private readonly MemoryEhMeilleure _memoryEh;
  39. private readonly ulong[] _pageBitmap;
  40. /// <inheritdoc/>
  41. public bool Supports4KBPages => MemoryBlock.GetPageSize() == PageSize;
  42. public int AddressSpaceBits { get; }
  43. public IntPtr PageTablePointer => _addressSpace.Base.Pointer;
  44. public MemoryManagerType Type => _unsafeMode ? MemoryManagerType.HostMappedUnsafe : MemoryManagerType.HostMapped;
  45. public MemoryTracking Tracking { get; }
  46. public event Action<ulong, ulong> UnmapEvent;
  47. /// <summary>
  48. /// Creates a new instance of the host mapped memory manager.
  49. /// </summary>
  50. /// <param name="backingMemory">Physical backing memory where virtual memory will be mapped to</param>
  51. /// <param name="addressSpaceSize">Size of the address space</param>
  52. /// <param name="unsafeMode">True if unmanaged access should not be masked (unsafe), false otherwise.</param>
  53. /// <param name="invalidAccessHandler">Optional function to handle invalid memory accesses</param>
  54. public MemoryManagerHostMapped(MemoryBlock backingMemory, ulong addressSpaceSize, bool unsafeMode, InvalidAccessHandler invalidAccessHandler = null)
  55. {
  56. _pageTable = new PageTable<ulong>();
  57. _invalidAccessHandler = invalidAccessHandler;
  58. _unsafeMode = unsafeMode;
  59. _addressSpaceSize = addressSpaceSize;
  60. ulong asSize = PageSize;
  61. int asBits = PageBits;
  62. while (asSize < addressSpaceSize)
  63. {
  64. asSize <<= 1;
  65. asBits++;
  66. }
  67. AddressSpaceBits = asBits;
  68. _pageBitmap = new ulong[1 << (AddressSpaceBits - (PageBits + PageToPteShift))];
  69. _addressSpace = new AddressSpace(backingMemory, asSize, Supports4KBPages);
  70. Tracking = new MemoryTracking(this, (int)MemoryBlock.GetPageSize(), invalidAccessHandler);
  71. _memoryEh = new MemoryEhMeilleure(_addressSpace.Base, _addressSpace.Mirror, Tracking);
  72. }
  73. /// <summary>
  74. /// Checks if the virtual address is part of the addressable space.
  75. /// </summary>
  76. /// <param name="va">Virtual address</param>
  77. /// <returns>True if the virtual address is part of the addressable space</returns>
  78. private bool ValidateAddress(ulong va)
  79. {
  80. return va < _addressSpaceSize;
  81. }
  82. /// <summary>
  83. /// Checks if the combination of virtual address and size is part of the addressable space.
  84. /// </summary>
  85. /// <param name="va">Virtual address of the range</param>
  86. /// <param name="size">Size of the range in bytes</param>
  87. /// <returns>True if the combination of virtual address and size is part of the addressable space</returns>
  88. private bool ValidateAddressAndSize(ulong va, ulong size)
  89. {
  90. ulong endVa = va + size;
  91. return endVa >= va && endVa >= size && endVa <= _addressSpaceSize;
  92. }
  93. /// <summary>
  94. /// Ensures the combination of virtual address and size is part of the addressable space.
  95. /// </summary>
  96. /// <param name="va">Virtual address of the range</param>
  97. /// <param name="size">Size of the range in bytes</param>
  98. /// <exception cref="InvalidMemoryRegionException">Throw when the memory region specified outside the addressable space</exception>
  99. private void AssertValidAddressAndSize(ulong va, ulong size)
  100. {
  101. if (!ValidateAddressAndSize(va, size))
  102. {
  103. throw new InvalidMemoryRegionException($"va=0x{va:X16}, size=0x{size:X16}");
  104. }
  105. }
  106. /// <summary>
  107. /// Ensures the combination of virtual address and size is part of the addressable space and fully mapped.
  108. /// </summary>
  109. /// <param name="va">Virtual address of the range</param>
  110. /// <param name="size">Size of the range in bytes</param>
  111. private void AssertMapped(ulong va, ulong size)
  112. {
  113. if (!ValidateAddressAndSize(va, size) || !IsRangeMappedImpl(va, size))
  114. {
  115. throw new InvalidMemoryRegionException($"Not mapped: va=0x{va:X16}, size=0x{size:X16}");
  116. }
  117. }
  118. /// <inheritdoc/>
  119. public void Map(ulong va, ulong pa, ulong size, MemoryMapFlags flags)
  120. {
  121. AssertValidAddressAndSize(va, size);
  122. _addressSpace.Map(va, pa, size, flags);
  123. AddMapping(va, size);
  124. PtMap(va, pa, size);
  125. Tracking.Map(va, size);
  126. }
  127. /// <inheritdoc/>
  128. public void MapForeign(ulong va, nuint hostPointer, ulong size)
  129. {
  130. throw new NotSupportedException();
  131. }
  132. /// <inheritdoc/>
  133. public void Unmap(ulong va, ulong size)
  134. {
  135. AssertValidAddressAndSize(va, size);
  136. UnmapEvent?.Invoke(va, size);
  137. Tracking.Unmap(va, size);
  138. RemoveMapping(va, size);
  139. PtUnmap(va, size);
  140. _addressSpace.Unmap(va, size);
  141. }
  142. private void PtMap(ulong va, ulong pa, ulong size)
  143. {
  144. while (size != 0)
  145. {
  146. _pageTable.Map(va, pa);
  147. va += PageSize;
  148. pa += PageSize;
  149. size -= PageSize;
  150. }
  151. }
  152. private void PtUnmap(ulong va, ulong size)
  153. {
  154. while (size != 0)
  155. {
  156. _pageTable.Unmap(va);
  157. va += PageSize;
  158. size -= PageSize;
  159. }
  160. }
  161. /// <inheritdoc/>
  162. public T Read<T>(ulong va) where T : unmanaged
  163. {
  164. try
  165. {
  166. AssertMapped(va, (ulong)Unsafe.SizeOf<T>());
  167. return _addressSpace.Mirror.Read<T>(va);
  168. }
  169. catch (InvalidMemoryRegionException)
  170. {
  171. if (_invalidAccessHandler == null || !_invalidAccessHandler(va))
  172. {
  173. throw;
  174. }
  175. return default;
  176. }
  177. }
  178. /// <inheritdoc/>
  179. public T ReadTracked<T>(ulong va) where T : unmanaged
  180. {
  181. try
  182. {
  183. SignalMemoryTracking(va, (ulong)Unsafe.SizeOf<T>(), false);
  184. return Read<T>(va);
  185. }
  186. catch (InvalidMemoryRegionException)
  187. {
  188. if (_invalidAccessHandler == null || !_invalidAccessHandler(va))
  189. {
  190. throw;
  191. }
  192. return default;
  193. }
  194. }
  195. /// <inheritdoc/>
  196. public void Read(ulong va, Span<byte> data)
  197. {
  198. try
  199. {
  200. AssertMapped(va, (ulong)data.Length);
  201. _addressSpace.Mirror.Read(va, data);
  202. }
  203. catch (InvalidMemoryRegionException)
  204. {
  205. if (_invalidAccessHandler == null || !_invalidAccessHandler(va))
  206. {
  207. throw;
  208. }
  209. }
  210. }
  211. /// <inheritdoc/>
  212. public void Write<T>(ulong va, T value) where T : unmanaged
  213. {
  214. try
  215. {
  216. SignalMemoryTracking(va, (ulong)Unsafe.SizeOf<T>(), write: true);
  217. _addressSpace.Mirror.Write(va, value);
  218. }
  219. catch (InvalidMemoryRegionException)
  220. {
  221. if (_invalidAccessHandler == null || !_invalidAccessHandler(va))
  222. {
  223. throw;
  224. }
  225. }
  226. }
  227. /// <inheritdoc/>
  228. public void Write(ulong va, ReadOnlySpan<byte> data)
  229. {
  230. try
  231. {
  232. SignalMemoryTracking(va, (ulong)data.Length, write: true);
  233. _addressSpace.Mirror.Write(va, data);
  234. }
  235. catch (InvalidMemoryRegionException)
  236. {
  237. if (_invalidAccessHandler == null || !_invalidAccessHandler(va))
  238. {
  239. throw;
  240. }
  241. }
  242. }
  243. /// <inheritdoc/>
  244. public void WriteUntracked(ulong va, ReadOnlySpan<byte> data)
  245. {
  246. try
  247. {
  248. AssertMapped(va, (ulong)data.Length);
  249. _addressSpace.Mirror.Write(va, data);
  250. }
  251. catch (InvalidMemoryRegionException)
  252. {
  253. if (_invalidAccessHandler == null || !_invalidAccessHandler(va))
  254. {
  255. throw;
  256. }
  257. }
  258. }
  259. /// <inheritdoc/>
  260. public bool WriteWithRedundancyCheck(ulong va, ReadOnlySpan<byte> data)
  261. {
  262. try
  263. {
  264. SignalMemoryTracking(va, (ulong)data.Length, false);
  265. Span<byte> target = _addressSpace.Mirror.GetSpan(va, data.Length);
  266. bool changed = !data.SequenceEqual(target);
  267. if (changed)
  268. {
  269. data.CopyTo(target);
  270. }
  271. return changed;
  272. }
  273. catch (InvalidMemoryRegionException)
  274. {
  275. if (_invalidAccessHandler == null || !_invalidAccessHandler(va))
  276. {
  277. throw;
  278. }
  279. return true;
  280. }
  281. }
  282. /// <inheritdoc/>
  283. public ReadOnlySpan<byte> GetSpan(ulong va, int size, bool tracked = false)
  284. {
  285. if (tracked)
  286. {
  287. SignalMemoryTracking(va, (ulong)size, write: false);
  288. }
  289. else
  290. {
  291. AssertMapped(va, (ulong)size);
  292. }
  293. return _addressSpace.Mirror.GetSpan(va, size);
  294. }
  295. /// <inheritdoc/>
  296. public WritableRegion GetWritableRegion(ulong va, int size, bool tracked = false)
  297. {
  298. if (tracked)
  299. {
  300. SignalMemoryTracking(va, (ulong)size, true);
  301. }
  302. else
  303. {
  304. AssertMapped(va, (ulong)size);
  305. }
  306. return _addressSpace.Mirror.GetWritableRegion(va, size);
  307. }
  308. /// <inheritdoc/>
  309. public ref T GetRef<T>(ulong va) where T : unmanaged
  310. {
  311. SignalMemoryTracking(va, (ulong)Unsafe.SizeOf<T>(), true);
  312. return ref _addressSpace.Mirror.GetRef<T>(va);
  313. }
  314. /// <inheritdoc/>
  315. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  316. public bool IsMapped(ulong va)
  317. {
  318. return ValidateAddress(va) && IsMappedImpl(va);
  319. }
  320. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  321. private bool IsMappedImpl(ulong va)
  322. {
  323. ulong page = va >> PageBits;
  324. int bit = (int)((page & 31) << 1);
  325. int pageIndex = (int)(page >> PageToPteShift);
  326. ref ulong pageRef = ref _pageBitmap[pageIndex];
  327. ulong pte = Volatile.Read(ref pageRef);
  328. return ((pte >> bit) & 3) != 0;
  329. }
  330. /// <inheritdoc/>
  331. public bool IsRangeMapped(ulong va, ulong size)
  332. {
  333. AssertValidAddressAndSize(va, size);
  334. return IsRangeMappedImpl(va, size);
  335. }
  336. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  337. private void GetPageBlockRange(ulong pageStart, ulong pageEnd, out ulong startMask, out ulong endMask, out int pageIndex, out int pageEndIndex)
  338. {
  339. startMask = ulong.MaxValue << ((int)(pageStart & 31) << 1);
  340. endMask = ulong.MaxValue >> (64 - ((int)(pageEnd & 31) << 1));
  341. pageIndex = (int)(pageStart >> PageToPteShift);
  342. pageEndIndex = (int)((pageEnd - 1) >> PageToPteShift);
  343. }
  344. private bool IsRangeMappedImpl(ulong va, ulong size)
  345. {
  346. int pages = GetPagesCount(va, size, out _);
  347. if (pages == 1)
  348. {
  349. return IsMappedImpl(va);
  350. }
  351. ulong pageStart = va >> PageBits;
  352. ulong pageEnd = pageStart + (ulong)pages;
  353. GetPageBlockRange(pageStart, pageEnd, out ulong startMask, out ulong endMask, out int pageIndex, out int pageEndIndex);
  354. // Check if either bit in each 2 bit page entry is set.
  355. // OR the block with itself shifted down by 1, and check the first bit of each entry.
  356. ulong mask = BlockMappedMask & startMask;
  357. while (pageIndex <= pageEndIndex)
  358. {
  359. if (pageIndex == pageEndIndex)
  360. {
  361. mask &= endMask;
  362. }
  363. ref ulong pageRef = ref _pageBitmap[pageIndex++];
  364. ulong pte = Volatile.Read(ref pageRef);
  365. pte |= pte >> 1;
  366. if ((pte & mask) != mask)
  367. {
  368. return false;
  369. }
  370. mask = BlockMappedMask;
  371. }
  372. return true;
  373. }
  374. /// <inheritdoc/>
  375. public IEnumerable<HostMemoryRange> GetHostRegions(ulong va, ulong size)
  376. {
  377. AssertValidAddressAndSize(va, size);
  378. return Enumerable.Repeat(new HostMemoryRange((nuint)(ulong)_addressSpace.Mirror.GetPointer(va, size), size), 1);
  379. }
  380. /// <inheritdoc/>
  381. public IEnumerable<MemoryRange> GetPhysicalRegions(ulong va, ulong size)
  382. {
  383. int pages = GetPagesCount(va, (uint)size, out va);
  384. var regions = new List<MemoryRange>();
  385. ulong regionStart = GetPhysicalAddressChecked(va);
  386. ulong regionSize = PageSize;
  387. for (int page = 0; page < pages - 1; page++)
  388. {
  389. if (!ValidateAddress(va + PageSize))
  390. {
  391. return null;
  392. }
  393. ulong newPa = GetPhysicalAddressChecked(va + PageSize);
  394. if (GetPhysicalAddressChecked(va) + PageSize != newPa)
  395. {
  396. regions.Add(new MemoryRange(regionStart, regionSize));
  397. regionStart = newPa;
  398. regionSize = 0;
  399. }
  400. va += PageSize;
  401. regionSize += PageSize;
  402. }
  403. regions.Add(new MemoryRange(regionStart, regionSize));
  404. return regions;
  405. }
  406. private ulong GetPhysicalAddressChecked(ulong va)
  407. {
  408. if (!IsMapped(va))
  409. {
  410. ThrowInvalidMemoryRegionException($"Not mapped: va=0x{va:X16}");
  411. }
  412. return GetPhysicalAddressInternal(va);
  413. }
  414. private ulong GetPhysicalAddressInternal(ulong va)
  415. {
  416. return _pageTable.Read(va) + (va & PageMask);
  417. }
  418. /// <inheritdoc/>
  419. /// <remarks>
  420. /// This function also validates that the given range is both valid and mapped, and will throw if it is not.
  421. /// </remarks>
  422. public void SignalMemoryTracking(ulong va, ulong size, bool write, bool precise = false, int? exemptId = null)
  423. {
  424. AssertValidAddressAndSize(va, size);
  425. if (precise)
  426. {
  427. Tracking.VirtualMemoryEvent(va, size, write, precise: true, exemptId);
  428. return;
  429. }
  430. // Software table, used for managed memory tracking.
  431. int pages = GetPagesCount(va, size, out _);
  432. ulong pageStart = va >> PageBits;
  433. if (pages == 1)
  434. {
  435. ulong tag = (ulong)(write ? HostMappedPtBits.WriteTracked : HostMappedPtBits.ReadWriteTracked);
  436. int bit = (int)((pageStart & 31) << 1);
  437. int pageIndex = (int)(pageStart >> PageToPteShift);
  438. ref ulong pageRef = ref _pageBitmap[pageIndex];
  439. ulong pte = Volatile.Read(ref pageRef);
  440. ulong state = ((pte >> bit) & 3);
  441. if (state >= tag)
  442. {
  443. Tracking.VirtualMemoryEvent(va, size, write, precise: false, exemptId);
  444. return;
  445. }
  446. else if (state == 0)
  447. {
  448. ThrowInvalidMemoryRegionException($"Not mapped: va=0x{va:X16}, size=0x{size:X16}");
  449. }
  450. }
  451. else
  452. {
  453. ulong pageEnd = pageStart + (ulong)pages;
  454. GetPageBlockRange(pageStart, pageEnd, out ulong startMask, out ulong endMask, out int pageIndex, out int pageEndIndex);
  455. ulong mask = startMask;
  456. ulong anyTrackingTag = (ulong)HostMappedPtBits.WriteTrackedReplicated;
  457. while (pageIndex <= pageEndIndex)
  458. {
  459. if (pageIndex == pageEndIndex)
  460. {
  461. mask &= endMask;
  462. }
  463. ref ulong pageRef = ref _pageBitmap[pageIndex++];
  464. ulong pte = Volatile.Read(ref pageRef);
  465. ulong mappedMask = mask & BlockMappedMask;
  466. ulong mappedPte = pte | (pte >> 1);
  467. if ((mappedPte & mappedMask) != mappedMask)
  468. {
  469. ThrowInvalidMemoryRegionException($"Not mapped: va=0x{va:X16}, size=0x{size:X16}");
  470. }
  471. pte &= mask;
  472. if ((pte & anyTrackingTag) != 0) // Search for any tracking.
  473. {
  474. // Writes trigger any tracking.
  475. // Only trigger tracking from reads if both bits are set on any page.
  476. if (write || (pte & (pte >> 1) & BlockMappedMask) != 0)
  477. {
  478. Tracking.VirtualMemoryEvent(va, size, write, precise: false, exemptId);
  479. break;
  480. }
  481. }
  482. mask = ulong.MaxValue;
  483. }
  484. }
  485. }
  486. /// <summary>
  487. /// Computes the number of pages in a virtual address range.
  488. /// </summary>
  489. /// <param name="va">Virtual address of the range</param>
  490. /// <param name="size">Size of the range</param>
  491. /// <param name="startVa">The virtual address of the beginning of the first page</param>
  492. /// <remarks>This function does not differentiate between allocated and unallocated pages.</remarks>
  493. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  494. private int GetPagesCount(ulong va, ulong size, out ulong startVa)
  495. {
  496. // WARNING: Always check if ulong does not overflow during the operations.
  497. startVa = va & ~(ulong)PageMask;
  498. ulong vaSpan = (va - startVa + size + PageMask) & ~(ulong)PageMask;
  499. return (int)(vaSpan / PageSize);
  500. }
  501. /// <inheritdoc/>
  502. public void TrackingReprotect(ulong va, ulong size, MemoryPermission protection)
  503. {
  504. // Protection is inverted on software pages, since the default value is 0.
  505. protection = (~protection) & MemoryPermission.ReadAndWrite;
  506. int pages = GetPagesCount(va, size, out va);
  507. ulong pageStart = va >> PageBits;
  508. if (pages == 1)
  509. {
  510. ulong protTag = protection switch
  511. {
  512. MemoryPermission.None => (ulong)HostMappedPtBits.Mapped,
  513. MemoryPermission.Write => (ulong)HostMappedPtBits.WriteTracked,
  514. _ => (ulong)HostMappedPtBits.ReadWriteTracked,
  515. };
  516. int bit = (int)((pageStart & 31) << 1);
  517. ulong tagMask = 3UL << bit;
  518. ulong invTagMask = ~tagMask;
  519. ulong tag = protTag << bit;
  520. int pageIndex = (int)(pageStart >> PageToPteShift);
  521. ref ulong pageRef = ref _pageBitmap[pageIndex];
  522. ulong pte;
  523. do
  524. {
  525. pte = Volatile.Read(ref pageRef);
  526. }
  527. while ((pte & tagMask) != 0 && Interlocked.CompareExchange(ref pageRef, (pte & invTagMask) | tag, pte) != pte);
  528. }
  529. else
  530. {
  531. ulong pageEnd = pageStart + (ulong)pages;
  532. GetPageBlockRange(pageStart, pageEnd, out ulong startMask, out ulong endMask, out int pageIndex, out int pageEndIndex);
  533. ulong mask = startMask;
  534. ulong protTag = protection switch
  535. {
  536. MemoryPermission.None => (ulong)HostMappedPtBits.MappedReplicated,
  537. MemoryPermission.Write => (ulong)HostMappedPtBits.WriteTrackedReplicated,
  538. _ => (ulong)HostMappedPtBits.ReadWriteTrackedReplicated,
  539. };
  540. while (pageIndex <= pageEndIndex)
  541. {
  542. if (pageIndex == pageEndIndex)
  543. {
  544. mask &= endMask;
  545. }
  546. ref ulong pageRef = ref _pageBitmap[pageIndex++];
  547. ulong pte;
  548. ulong mappedMask;
  549. // Change the protection of all 2 bit entries that are mapped.
  550. do
  551. {
  552. pte = Volatile.Read(ref pageRef);
  553. mappedMask = pte | (pte >> 1);
  554. mappedMask |= (mappedMask & BlockMappedMask) << 1;
  555. mappedMask &= mask; // Only update mapped pages within the given range.
  556. }
  557. while (Interlocked.CompareExchange(ref pageRef, (pte & (~mappedMask)) | (protTag & mappedMask), pte) != pte);
  558. mask = ulong.MaxValue;
  559. }
  560. }
  561. protection = protection switch
  562. {
  563. MemoryPermission.None => MemoryPermission.ReadAndWrite,
  564. MemoryPermission.Write => MemoryPermission.Read,
  565. _ => MemoryPermission.None
  566. };
  567. _addressSpace.Base.Reprotect(va, size, protection, false);
  568. }
  569. /// <inheritdoc/>
  570. public CpuRegionHandle BeginTracking(ulong address, ulong size, int id)
  571. {
  572. return new CpuRegionHandle(Tracking.BeginTracking(address, size, id));
  573. }
  574. /// <inheritdoc/>
  575. public CpuMultiRegionHandle BeginGranularTracking(ulong address, ulong size, IEnumerable<IRegionHandle> handles, ulong granularity, int id)
  576. {
  577. return new CpuMultiRegionHandle(Tracking.BeginGranularTracking(address, size, handles, granularity, id));
  578. }
  579. /// <inheritdoc/>
  580. public CpuSmartMultiRegionHandle BeginSmartGranularTracking(ulong address, ulong size, ulong granularity, int id)
  581. {
  582. return new CpuSmartMultiRegionHandle(Tracking.BeginSmartGranularTracking(address, size, granularity, id));
  583. }
  584. /// <summary>
  585. /// Adds the given address mapping to the page table.
  586. /// </summary>
  587. /// <param name="va">Virtual memory address</param>
  588. /// <param name="size">Size to be mapped</param>
  589. private void AddMapping(ulong va, ulong size)
  590. {
  591. int pages = GetPagesCount(va, size, out _);
  592. ulong pageStart = va >> PageBits;
  593. ulong pageEnd = pageStart + (ulong)pages;
  594. GetPageBlockRange(pageStart, pageEnd, out ulong startMask, out ulong endMask, out int pageIndex, out int pageEndIndex);
  595. ulong mask = startMask;
  596. while (pageIndex <= pageEndIndex)
  597. {
  598. if (pageIndex == pageEndIndex)
  599. {
  600. mask &= endMask;
  601. }
  602. ref ulong pageRef = ref _pageBitmap[pageIndex++];
  603. ulong pte;
  604. ulong mappedMask;
  605. // Map all 2-bit entries that are unmapped.
  606. do
  607. {
  608. pte = Volatile.Read(ref pageRef);
  609. mappedMask = pte | (pte >> 1);
  610. mappedMask |= (mappedMask & BlockMappedMask) << 1;
  611. mappedMask |= ~mask; // Treat everything outside the range as mapped, thus unchanged.
  612. }
  613. while (Interlocked.CompareExchange(ref pageRef, (pte & mappedMask) | (BlockMappedMask & (~mappedMask)), pte) != pte);
  614. mask = ulong.MaxValue;
  615. }
  616. }
  617. /// <summary>
  618. /// Removes the given address mapping from the page table.
  619. /// </summary>
  620. /// <param name="va">Virtual memory address</param>
  621. /// <param name="size">Size to be unmapped</param>
  622. private void RemoveMapping(ulong va, ulong size)
  623. {
  624. int pages = GetPagesCount(va, size, out _);
  625. ulong pageStart = va >> PageBits;
  626. ulong pageEnd = pageStart + (ulong)pages;
  627. GetPageBlockRange(pageStart, pageEnd, out ulong startMask, out ulong endMask, out int pageIndex, out int pageEndIndex);
  628. startMask = ~startMask;
  629. endMask = ~endMask;
  630. ulong mask = startMask;
  631. while (pageIndex <= pageEndIndex)
  632. {
  633. if (pageIndex == pageEndIndex)
  634. {
  635. mask |= endMask;
  636. }
  637. ref ulong pageRef = ref _pageBitmap[pageIndex++];
  638. ulong pte;
  639. do
  640. {
  641. pte = Volatile.Read(ref pageRef);
  642. }
  643. while (Interlocked.CompareExchange(ref pageRef, pte & mask, pte) != pte);
  644. mask = 0;
  645. }
  646. }
  647. /// <summary>
  648. /// Disposes of resources used by the memory manager.
  649. /// </summary>
  650. protected override void Destroy()
  651. {
  652. _addressSpace.Dispose();
  653. _memoryEh.Dispose();
  654. }
  655. private static void ThrowInvalidMemoryRegionException(string message) => throw new InvalidMemoryRegionException(message);
  656. }
  657. }