MemoryManagerHostMapped.cs 27 KB

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