MemoryManagerHostMapped.cs 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779
  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
  11. {
  12. /// <summary>
  13. /// Represents a CPU memory manager which maps guest virtual memory directly onto a host virtual region.
  14. /// </summary>
  15. public 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 | MemoryAllocationFlags.ForceWindows4KBViewMapping);
  72. Tracking = new MemoryTracking(this, PageSize, invalidAccessHandler);
  73. _memoryEh = new MemoryEhMeilleure(_addressSpace, 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. SignalMemoryTracking(va, (ulong)data.Length, write: true);
  231. _addressSpaceMirror.Write(va, data);
  232. }
  233. catch (InvalidMemoryRegionException)
  234. {
  235. if (_invalidAccessHandler == null || !_invalidAccessHandler(va))
  236. {
  237. throw;
  238. }
  239. }
  240. }
  241. /// <inheritdoc/>
  242. public void WriteUntracked(ulong va, ReadOnlySpan<byte> data)
  243. {
  244. try
  245. {
  246. AssertMapped(va, (ulong)data.Length);
  247. _addressSpaceMirror.Write(va, data);
  248. }
  249. catch (InvalidMemoryRegionException)
  250. {
  251. if (_invalidAccessHandler == null || !_invalidAccessHandler(va))
  252. {
  253. throw;
  254. }
  255. }
  256. }
  257. /// <inheritdoc/>
  258. public ReadOnlySpan<byte> GetSpan(ulong va, int size, bool tracked = false)
  259. {
  260. if (tracked)
  261. {
  262. SignalMemoryTracking(va, (ulong)size, write: false);
  263. }
  264. else
  265. {
  266. AssertMapped(va, (ulong)size);
  267. }
  268. return _addressSpaceMirror.GetSpan(va, size);
  269. }
  270. /// <inheritdoc/>
  271. public WritableRegion GetWritableRegion(ulong va, int size, bool tracked = false)
  272. {
  273. if (tracked)
  274. {
  275. SignalMemoryTracking(va, (ulong)size, true);
  276. }
  277. else
  278. {
  279. AssertMapped(va, (ulong)size);
  280. }
  281. return _addressSpaceMirror.GetWritableRegion(va, size);
  282. }
  283. /// <inheritdoc/>
  284. public ref T GetRef<T>(ulong va) where T : unmanaged
  285. {
  286. SignalMemoryTracking(va, (ulong)Unsafe.SizeOf<T>(), true);
  287. return ref _addressSpaceMirror.GetRef<T>(va);
  288. }
  289. /// <inheritdoc/>
  290. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  291. public bool IsMapped(ulong va)
  292. {
  293. return ValidateAddress(va) && IsMappedImpl(va);
  294. }
  295. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  296. private bool IsMappedImpl(ulong va)
  297. {
  298. ulong page = va >> PageBits;
  299. int bit = (int)((page & 31) << 1);
  300. int pageIndex = (int)(page >> PageToPteShift);
  301. ref ulong pageRef = ref _pageBitmap[pageIndex];
  302. ulong pte = Volatile.Read(ref pageRef);
  303. return ((pte >> bit) & 3) != 0;
  304. }
  305. /// <inheritdoc/>
  306. public bool IsRangeMapped(ulong va, ulong size)
  307. {
  308. AssertValidAddressAndSize(va, size);
  309. return IsRangeMappedImpl(va, size);
  310. }
  311. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  312. private void GetPageBlockRange(ulong pageStart, ulong pageEnd, out ulong startMask, out ulong endMask, out int pageIndex, out int pageEndIndex)
  313. {
  314. startMask = ulong.MaxValue << ((int)(pageStart & 31) << 1);
  315. endMask = ulong.MaxValue >> (64 - ((int)(pageEnd & 31) << 1));
  316. pageIndex = (int)(pageStart >> PageToPteShift);
  317. pageEndIndex = (int)((pageEnd - 1) >> PageToPteShift);
  318. }
  319. private bool IsRangeMappedImpl(ulong va, ulong size)
  320. {
  321. int pages = GetPagesCount(va, size, out _);
  322. if (pages == 1)
  323. {
  324. return IsMappedImpl(va);
  325. }
  326. ulong pageStart = va >> PageBits;
  327. ulong pageEnd = pageStart + (ulong)pages;
  328. GetPageBlockRange(pageStart, pageEnd, out ulong startMask, out ulong endMask, out int pageIndex, out int pageEndIndex);
  329. // Check if either bit in each 2 bit page entry is set.
  330. // OR the block with itself shifted down by 1, and check the first bit of each entry.
  331. ulong mask = BlockMappedMask & startMask;
  332. while (pageIndex <= pageEndIndex)
  333. {
  334. if (pageIndex == pageEndIndex)
  335. {
  336. mask &= endMask;
  337. }
  338. ref ulong pageRef = ref _pageBitmap[pageIndex++];
  339. ulong pte = Volatile.Read(ref pageRef);
  340. pte |= pte >> 1;
  341. if ((pte & mask) != mask)
  342. {
  343. return false;
  344. }
  345. mask = BlockMappedMask;
  346. }
  347. return true;
  348. }
  349. /// <inheritdoc/>
  350. public IEnumerable<MemoryRange> GetPhysicalRegions(ulong va, ulong size)
  351. {
  352. int pages = GetPagesCount(va, (uint)size, out va);
  353. var regions = new List<MemoryRange>();
  354. ulong regionStart = GetPhysicalAddressChecked(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 = GetPhysicalAddressChecked(va + PageSize);
  363. if (GetPhysicalAddressChecked(va) + PageSize != newPa)
  364. {
  365. regions.Add(new MemoryRange(regionStart, regionSize));
  366. regionStart = newPa;
  367. regionSize = 0;
  368. }
  369. va += PageSize;
  370. regionSize += PageSize;
  371. }
  372. regions.Add(new MemoryRange(regionStart, regionSize));
  373. return regions;
  374. }
  375. private ulong GetPhysicalAddressChecked(ulong va)
  376. {
  377. if (!IsMapped(va))
  378. {
  379. ThrowInvalidMemoryRegionException($"Not mapped: va=0x{va:X16}");
  380. }
  381. return GetPhysicalAddressInternal(va);
  382. }
  383. private ulong GetPhysicalAddressInternal(ulong va)
  384. {
  385. return _pageTable.Read(va) + (va & PageMask);
  386. }
  387. /// <inheritdoc/>
  388. /// <remarks>
  389. /// This function also validates that the given range is both valid and mapped, and will throw if it is not.
  390. /// </remarks>
  391. public void SignalMemoryTracking(ulong va, ulong size, bool write, bool precise = false)
  392. {
  393. AssertValidAddressAndSize(va, size);
  394. if (precise)
  395. {
  396. Tracking.VirtualMemoryEvent(va, size, write, precise: true);
  397. return;
  398. }
  399. // Software table, used for managed memory tracking.
  400. int pages = GetPagesCount(va, size, out _);
  401. ulong pageStart = va >> PageBits;
  402. if (pages == 1)
  403. {
  404. ulong tag = (ulong)(write ? HostMappedPtBits.WriteTracked : HostMappedPtBits.ReadWriteTracked);
  405. int bit = (int)((pageStart & 31) << 1);
  406. int pageIndex = (int)(pageStart >> PageToPteShift);
  407. ref ulong pageRef = ref _pageBitmap[pageIndex];
  408. ulong pte = Volatile.Read(ref pageRef);
  409. ulong state = ((pte >> bit) & 3);
  410. if (state >= tag)
  411. {
  412. Tracking.VirtualMemoryEvent(va, size, write);
  413. return;
  414. }
  415. else if (state == 0)
  416. {
  417. ThrowInvalidMemoryRegionException($"Not mapped: va=0x{va:X16}, size=0x{size:X16}");
  418. }
  419. }
  420. else
  421. {
  422. ulong pageEnd = pageStart + (ulong)pages;
  423. GetPageBlockRange(pageStart, pageEnd, out ulong startMask, out ulong endMask, out int pageIndex, out int pageEndIndex);
  424. ulong mask = startMask;
  425. ulong anyTrackingTag = (ulong)HostMappedPtBits.WriteTrackedReplicated;
  426. while (pageIndex <= pageEndIndex)
  427. {
  428. if (pageIndex == pageEndIndex)
  429. {
  430. mask &= endMask;
  431. }
  432. ref ulong pageRef = ref _pageBitmap[pageIndex++];
  433. ulong pte = Volatile.Read(ref pageRef);
  434. ulong mappedMask = mask & BlockMappedMask;
  435. ulong mappedPte = pte | (pte >> 1);
  436. if ((mappedPte & mappedMask) != mappedMask)
  437. {
  438. ThrowInvalidMemoryRegionException($"Not mapped: va=0x{va:X16}, size=0x{size:X16}");
  439. }
  440. pte &= mask;
  441. if ((pte & anyTrackingTag) != 0) // Search for any tracking.
  442. {
  443. // Writes trigger any tracking.
  444. // Only trigger tracking from reads if both bits are set on any page.
  445. if (write || (pte & (pte >> 1) & BlockMappedMask) != 0)
  446. {
  447. Tracking.VirtualMemoryEvent(va, size, write);
  448. break;
  449. }
  450. }
  451. mask = ulong.MaxValue;
  452. }
  453. }
  454. }
  455. /// <summary>
  456. /// Computes the number of pages in a virtual address range.
  457. /// </summary>
  458. /// <param name="va">Virtual address of the range</param>
  459. /// <param name="size">Size of the range</param>
  460. /// <param name="startVa">The virtual address of the beginning of the first page</param>
  461. /// <remarks>This function does not differentiate between allocated and unallocated pages.</remarks>
  462. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  463. private int GetPagesCount(ulong va, ulong size, out ulong startVa)
  464. {
  465. // WARNING: Always check if ulong does not overflow during the operations.
  466. startVa = va & ~(ulong)PageMask;
  467. ulong vaSpan = (va - startVa + size + PageMask) & ~(ulong)PageMask;
  468. return (int)(vaSpan / PageSize);
  469. }
  470. /// <inheritdoc/>
  471. public void TrackingReprotect(ulong va, ulong size, MemoryPermission protection)
  472. {
  473. // Protection is inverted on software pages, since the default value is 0.
  474. protection = (~protection) & MemoryPermission.ReadAndWrite;
  475. int pages = GetPagesCount(va, size, out va);
  476. ulong pageStart = va >> PageBits;
  477. if (pages == 1)
  478. {
  479. ulong protTag = protection switch
  480. {
  481. MemoryPermission.None => (ulong)HostMappedPtBits.Mapped,
  482. MemoryPermission.Write => (ulong)HostMappedPtBits.WriteTracked,
  483. _ => (ulong)HostMappedPtBits.ReadWriteTracked,
  484. };
  485. int bit = (int)((pageStart & 31) << 1);
  486. ulong tagMask = 3UL << bit;
  487. ulong invTagMask = ~tagMask;
  488. ulong tag = protTag << bit;
  489. int pageIndex = (int)(pageStart >> PageToPteShift);
  490. ref ulong pageRef = ref _pageBitmap[pageIndex];
  491. ulong pte;
  492. do
  493. {
  494. pte = Volatile.Read(ref pageRef);
  495. }
  496. while ((pte & tagMask) != 0 && Interlocked.CompareExchange(ref pageRef, (pte & invTagMask) | tag, pte) != pte);
  497. }
  498. else
  499. {
  500. ulong pageEnd = pageStart + (ulong)pages;
  501. GetPageBlockRange(pageStart, pageEnd, out ulong startMask, out ulong endMask, out int pageIndex, out int pageEndIndex);
  502. ulong mask = startMask;
  503. ulong protTag = protection switch
  504. {
  505. MemoryPermission.None => (ulong)HostMappedPtBits.MappedReplicated,
  506. MemoryPermission.Write => (ulong)HostMappedPtBits.WriteTrackedReplicated,
  507. _ => (ulong)HostMappedPtBits.ReadWriteTrackedReplicated,
  508. };
  509. while (pageIndex <= pageEndIndex)
  510. {
  511. if (pageIndex == pageEndIndex)
  512. {
  513. mask &= endMask;
  514. }
  515. ref ulong pageRef = ref _pageBitmap[pageIndex++];
  516. ulong pte;
  517. ulong mappedMask;
  518. // Change the protection of all 2 bit entries that are mapped.
  519. do
  520. {
  521. pte = Volatile.Read(ref pageRef);
  522. mappedMask = pte | (pte >> 1);
  523. mappedMask |= (mappedMask & BlockMappedMask) << 1;
  524. mappedMask &= mask; // Only update mapped pages within the given range.
  525. }
  526. while (Interlocked.CompareExchange(ref pageRef, (pte & (~mappedMask)) | (protTag & mappedMask), pte) != pte);
  527. mask = ulong.MaxValue;
  528. }
  529. }
  530. protection = protection switch
  531. {
  532. MemoryPermission.None => MemoryPermission.ReadAndWrite,
  533. MemoryPermission.Write => MemoryPermission.Read,
  534. _ => MemoryPermission.None
  535. };
  536. _addressSpace.Reprotect(va, size, protection, false);
  537. }
  538. /// <inheritdoc/>
  539. public CpuRegionHandle BeginTracking(ulong address, ulong size)
  540. {
  541. return new CpuRegionHandle(Tracking.BeginTracking(address, size));
  542. }
  543. /// <inheritdoc/>
  544. public CpuMultiRegionHandle BeginGranularTracking(ulong address, ulong size, IEnumerable<IRegionHandle> handles, ulong granularity)
  545. {
  546. return new CpuMultiRegionHandle(Tracking.BeginGranularTracking(address, size, handles, granularity));
  547. }
  548. /// <inheritdoc/>
  549. public CpuSmartMultiRegionHandle BeginSmartGranularTracking(ulong address, ulong size, ulong granularity)
  550. {
  551. return new CpuSmartMultiRegionHandle(Tracking.BeginSmartGranularTracking(address, size, granularity));
  552. }
  553. /// <summary>
  554. /// Adds the given address mapping to the page table.
  555. /// </summary>
  556. /// <param name="va">Virtual memory address</param>
  557. /// <param name="size">Size to be mapped</param>
  558. private void AddMapping(ulong va, ulong size)
  559. {
  560. int pages = GetPagesCount(va, size, out _);
  561. ulong pageStart = va >> PageBits;
  562. ulong pageEnd = pageStart + (ulong)pages;
  563. GetPageBlockRange(pageStart, pageEnd, out ulong startMask, out ulong endMask, out int pageIndex, out int pageEndIndex);
  564. ulong mask = startMask;
  565. while (pageIndex <= pageEndIndex)
  566. {
  567. if (pageIndex == pageEndIndex)
  568. {
  569. mask &= endMask;
  570. }
  571. ref ulong pageRef = ref _pageBitmap[pageIndex++];
  572. ulong pte;
  573. ulong mappedMask;
  574. // Map all 2-bit entries that are unmapped.
  575. do
  576. {
  577. pte = Volatile.Read(ref pageRef);
  578. mappedMask = pte | (pte >> 1);
  579. mappedMask |= (mappedMask & BlockMappedMask) << 1;
  580. mappedMask |= ~mask; // Treat everything outside the range as mapped, thus unchanged.
  581. }
  582. while (Interlocked.CompareExchange(ref pageRef, (pte & mappedMask) | (BlockMappedMask & (~mappedMask)), pte) != pte);
  583. mask = ulong.MaxValue;
  584. }
  585. }
  586. /// <summary>
  587. /// Removes the given address mapping from the page table.
  588. /// </summary>
  589. /// <param name="va">Virtual memory address</param>
  590. /// <param name="size">Size to be unmapped</param>
  591. private void RemoveMapping(ulong va, ulong size)
  592. {
  593. int pages = GetPagesCount(va, size, out _);
  594. ulong pageStart = va >> PageBits;
  595. ulong pageEnd = pageStart + (ulong)pages;
  596. GetPageBlockRange(pageStart, pageEnd, out ulong startMask, out ulong endMask, out int pageIndex, out int pageEndIndex);
  597. startMask = ~startMask;
  598. endMask = ~endMask;
  599. ulong mask = startMask;
  600. while (pageIndex <= pageEndIndex)
  601. {
  602. if (pageIndex == pageEndIndex)
  603. {
  604. mask |= endMask;
  605. }
  606. ref ulong pageRef = ref _pageBitmap[pageIndex++];
  607. ulong pte;
  608. do
  609. {
  610. pte = Volatile.Read(ref pageRef);
  611. }
  612. while (Interlocked.CompareExchange(ref pageRef, pte & mask, pte) != pte);
  613. mask = 0;
  614. }
  615. }
  616. /// <summary>
  617. /// Disposes of resources used by the memory manager.
  618. /// </summary>
  619. protected override void Destroy()
  620. {
  621. _addressSpace.Dispose();
  622. _addressSpaceMirror.Dispose();
  623. _memoryEh.Dispose();
  624. }
  625. private static void ThrowInvalidMemoryRegionException(string message) => throw new InvalidMemoryRegionException(message);
  626. }
  627. }