MemoryManagerHostMapped.cs 26 KB

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