MemoryManager.cs 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922
  1. using ChocolArm64.Events;
  2. using ChocolArm64.Exceptions;
  3. using ChocolArm64.Instructions;
  4. using ChocolArm64.State;
  5. using System;
  6. using System.Collections.Concurrent;
  7. using System.Collections.Generic;
  8. using System.Runtime.CompilerServices;
  9. using System.Runtime.InteropServices;
  10. using System.Runtime.Intrinsics;
  11. using System.Runtime.Intrinsics.X86;
  12. using System.Threading;
  13. namespace ChocolArm64.Memory
  14. {
  15. public unsafe class MemoryManager : IMemory, IDisposable
  16. {
  17. private const int PtLvl0Bits = 13;
  18. private const int PtLvl1Bits = 14;
  19. private const int PtPageBits = 12;
  20. private const int PtLvl0Size = 1 << PtLvl0Bits;
  21. private const int PtLvl1Size = 1 << PtLvl1Bits;
  22. public const int PageSize = 1 << PtPageBits;
  23. private const int PtLvl0Mask = PtLvl0Size - 1;
  24. private const int PtLvl1Mask = PtLvl1Size - 1;
  25. public const int PageMask = PageSize - 1;
  26. private const int PtLvl0Bit = PtPageBits + PtLvl1Bits;
  27. private const int PtLvl1Bit = PtPageBits;
  28. private const long ErgMask = (4 << CpuThreadState.ErgSizeLog2) - 1;
  29. private class ArmMonitor
  30. {
  31. public long Position;
  32. public bool ExState;
  33. public bool HasExclusiveAccess(long position)
  34. {
  35. return Position == position && ExState;
  36. }
  37. }
  38. private Dictionary<int, ArmMonitor> _monitors;
  39. private ConcurrentDictionary<long, IntPtr> _observedPages;
  40. public IntPtr Ram { get; private set; }
  41. private byte* _ramPtr;
  42. private byte*** _pageTable;
  43. public event EventHandler<InvalidAccessEventArgs> InvalidAccess;
  44. public MemoryManager(IntPtr ram)
  45. {
  46. _monitors = new Dictionary<int, ArmMonitor>();
  47. _observedPages = new ConcurrentDictionary<long, IntPtr>();
  48. Ram = ram;
  49. _ramPtr = (byte*)ram;
  50. _pageTable = (byte***)Marshal.AllocHGlobal(PtLvl0Size * IntPtr.Size);
  51. for (int l0 = 0; l0 < PtLvl0Size; l0++)
  52. {
  53. _pageTable[l0] = null;
  54. }
  55. }
  56. public void RemoveMonitor(int core)
  57. {
  58. lock (_monitors)
  59. {
  60. ClearExclusive(core);
  61. _monitors.Remove(core);
  62. }
  63. }
  64. public void SetExclusive(int core, long position)
  65. {
  66. position &= ~ErgMask;
  67. lock (_monitors)
  68. {
  69. foreach (ArmMonitor mon in _monitors.Values)
  70. {
  71. if (mon.Position == position && mon.ExState)
  72. {
  73. mon.ExState = false;
  74. }
  75. }
  76. if (!_monitors.TryGetValue(core, out ArmMonitor threadMon))
  77. {
  78. threadMon = new ArmMonitor();
  79. _monitors.Add(core, threadMon);
  80. }
  81. threadMon.Position = position;
  82. threadMon.ExState = true;
  83. }
  84. }
  85. public bool TestExclusive(int core, long position)
  86. {
  87. //Note: Any call to this method also should be followed by a
  88. //call to ClearExclusiveForStore if this method returns true.
  89. position &= ~ErgMask;
  90. Monitor.Enter(_monitors);
  91. if (!_monitors.TryGetValue(core, out ArmMonitor threadMon))
  92. {
  93. return false;
  94. }
  95. bool exState = threadMon.HasExclusiveAccess(position);
  96. if (!exState)
  97. {
  98. Monitor.Exit(_monitors);
  99. }
  100. return exState;
  101. }
  102. public void ClearExclusiveForStore(int core)
  103. {
  104. if (_monitors.TryGetValue(core, out ArmMonitor threadMon))
  105. {
  106. threadMon.ExState = false;
  107. }
  108. Monitor.Exit(_monitors);
  109. }
  110. public void ClearExclusive(int core)
  111. {
  112. lock (_monitors)
  113. {
  114. if (_monitors.TryGetValue(core, out ArmMonitor threadMon))
  115. {
  116. threadMon.ExState = false;
  117. }
  118. }
  119. }
  120. public void WriteInt32ToSharedAddr(long position, int value)
  121. {
  122. long maskedPosition = position & ~ErgMask;
  123. lock (_monitors)
  124. {
  125. foreach (ArmMonitor mon in _monitors.Values)
  126. {
  127. if (mon.Position == maskedPosition && mon.ExState)
  128. {
  129. mon.ExState = false;
  130. }
  131. }
  132. WriteInt32(position, value);
  133. }
  134. }
  135. public sbyte ReadSByte(long position)
  136. {
  137. return (sbyte)ReadByte(position);
  138. }
  139. public short ReadInt16(long position)
  140. {
  141. return (short)ReadUInt16(position);
  142. }
  143. public int ReadInt32(long position)
  144. {
  145. return (int)ReadUInt32(position);
  146. }
  147. public long ReadInt64(long position)
  148. {
  149. return (long)ReadUInt64(position);
  150. }
  151. public byte ReadByte(long position)
  152. {
  153. return *((byte*)Translate(position));
  154. }
  155. public ushort ReadUInt16(long position)
  156. {
  157. if ((position & 1) == 0)
  158. {
  159. return *((ushort*)Translate(position));
  160. }
  161. else
  162. {
  163. return (ushort)(ReadByte(position + 0) << 0 |
  164. ReadByte(position + 1) << 8);
  165. }
  166. }
  167. public uint ReadUInt32(long position)
  168. {
  169. if ((position & 3) == 0)
  170. {
  171. return *((uint*)Translate(position));
  172. }
  173. else
  174. {
  175. return (uint)(ReadUInt16(position + 0) << 0 |
  176. ReadUInt16(position + 2) << 16);
  177. }
  178. }
  179. public ulong ReadUInt64(long position)
  180. {
  181. if ((position & 7) == 0)
  182. {
  183. return *((ulong*)Translate(position));
  184. }
  185. else
  186. {
  187. return (ulong)ReadUInt32(position + 0) << 0 |
  188. (ulong)ReadUInt32(position + 4) << 32;
  189. }
  190. }
  191. public Vector128<float> ReadVector8(long position)
  192. {
  193. if (Sse2.IsSupported)
  194. {
  195. return Sse.StaticCast<byte, float>(Sse2.SetVector128(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ReadByte(position)));
  196. }
  197. else
  198. {
  199. Vector128<float> value = VectorHelper.VectorSingleZero();
  200. value = VectorHelper.VectorInsertInt(ReadByte(position), value, 0, 0);
  201. return value;
  202. }
  203. }
  204. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  205. public Vector128<float> ReadVector16(long position)
  206. {
  207. if (Sse2.IsSupported && (position & 1) == 0)
  208. {
  209. return Sse.StaticCast<ushort, float>(Sse2.Insert(Sse2.SetZeroVector128<ushort>(), ReadUInt16(position), 0));
  210. }
  211. else
  212. {
  213. Vector128<float> value = VectorHelper.VectorSingleZero();
  214. value = VectorHelper.VectorInsertInt(ReadUInt16(position), value, 0, 1);
  215. return value;
  216. }
  217. }
  218. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  219. public Vector128<float> ReadVector32(long position)
  220. {
  221. if (Sse.IsSupported && (position & 3) == 0)
  222. {
  223. return Sse.LoadScalarVector128((float*)Translate(position));
  224. }
  225. else
  226. {
  227. Vector128<float> value = VectorHelper.VectorSingleZero();
  228. value = VectorHelper.VectorInsertInt(ReadUInt32(position), value, 0, 2);
  229. return value;
  230. }
  231. }
  232. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  233. public Vector128<float> ReadVector64(long position)
  234. {
  235. if (Sse2.IsSupported && (position & 7) == 0)
  236. {
  237. return Sse.StaticCast<double, float>(Sse2.LoadScalarVector128((double*)Translate(position)));
  238. }
  239. else
  240. {
  241. Vector128<float> value = VectorHelper.VectorSingleZero();
  242. value = VectorHelper.VectorInsertInt(ReadUInt64(position), value, 0, 3);
  243. return value;
  244. }
  245. }
  246. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  247. public Vector128<float> ReadVector128(long position)
  248. {
  249. if (Sse.IsSupported && (position & 15) == 0)
  250. {
  251. return Sse.LoadVector128((float*)Translate(position));
  252. }
  253. else
  254. {
  255. Vector128<float> value = VectorHelper.VectorSingleZero();
  256. value = VectorHelper.VectorInsertInt(ReadUInt64(position + 0), value, 0, 3);
  257. value = VectorHelper.VectorInsertInt(ReadUInt64(position + 8), value, 1, 3);
  258. return value;
  259. }
  260. }
  261. public byte[] ReadBytes(long position, long size)
  262. {
  263. long endAddr = position + size;
  264. if ((ulong)size > int.MaxValue)
  265. {
  266. throw new ArgumentOutOfRangeException(nameof(size));
  267. }
  268. if ((ulong)endAddr < (ulong)position)
  269. {
  270. throw new ArgumentOutOfRangeException(nameof(position));
  271. }
  272. byte[] data = new byte[size];
  273. int offset = 0;
  274. while ((ulong)position < (ulong)endAddr)
  275. {
  276. long pageLimit = (position + PageSize) & ~(long)PageMask;
  277. if ((ulong)pageLimit > (ulong)endAddr)
  278. {
  279. pageLimit = endAddr;
  280. }
  281. int copySize = (int)(pageLimit - position);
  282. Marshal.Copy((IntPtr)Translate(position), data, offset, copySize);
  283. position += copySize;
  284. offset += copySize;
  285. }
  286. return data;
  287. }
  288. public void ReadBytes(long position, byte[] data, int startIndex, int size)
  289. {
  290. //Note: This will be moved later.
  291. long endAddr = position + size;
  292. if ((ulong)size > int.MaxValue)
  293. {
  294. throw new ArgumentOutOfRangeException(nameof(size));
  295. }
  296. if ((ulong)endAddr < (ulong)position)
  297. {
  298. throw new ArgumentOutOfRangeException(nameof(position));
  299. }
  300. int offset = startIndex;
  301. while ((ulong)position < (ulong)endAddr)
  302. {
  303. long pageLimit = (position + PageSize) & ~(long)PageMask;
  304. if ((ulong)pageLimit > (ulong)endAddr)
  305. {
  306. pageLimit = endAddr;
  307. }
  308. int copySize = (int)(pageLimit - position);
  309. Marshal.Copy((IntPtr)Translate(position), data, offset, copySize);
  310. position += copySize;
  311. offset += copySize;
  312. }
  313. }
  314. public void WriteSByte(long position, sbyte value)
  315. {
  316. WriteByte(position, (byte)value);
  317. }
  318. public void WriteInt16(long position, short value)
  319. {
  320. WriteUInt16(position, (ushort)value);
  321. }
  322. public void WriteInt32(long position, int value)
  323. {
  324. WriteUInt32(position, (uint)value);
  325. }
  326. public void WriteInt64(long position, long value)
  327. {
  328. WriteUInt64(position, (ulong)value);
  329. }
  330. public void WriteByte(long position, byte value)
  331. {
  332. *((byte*)TranslateWrite(position)) = value;
  333. }
  334. public void WriteUInt16(long position, ushort value)
  335. {
  336. if ((position & 1) == 0)
  337. {
  338. *((ushort*)TranslateWrite(position)) = value;
  339. }
  340. else
  341. {
  342. WriteByte(position + 0, (byte)(value >> 0));
  343. WriteByte(position + 1, (byte)(value >> 8));
  344. }
  345. }
  346. public void WriteUInt32(long position, uint value)
  347. {
  348. if ((position & 3) == 0)
  349. {
  350. *((uint*)TranslateWrite(position)) = value;
  351. }
  352. else
  353. {
  354. WriteUInt16(position + 0, (ushort)(value >> 0));
  355. WriteUInt16(position + 2, (ushort)(value >> 16));
  356. }
  357. }
  358. public void WriteUInt64(long position, ulong value)
  359. {
  360. if ((position & 7) == 0)
  361. {
  362. *((ulong*)TranslateWrite(position)) = value;
  363. }
  364. else
  365. {
  366. WriteUInt32(position + 0, (uint)(value >> 0));
  367. WriteUInt32(position + 4, (uint)(value >> 32));
  368. }
  369. }
  370. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  371. public void WriteVector8(long position, Vector128<float> value)
  372. {
  373. if (Sse41.IsSupported)
  374. {
  375. WriteByte(position, Sse41.Extract(Sse.StaticCast<float, byte>(value), 0));
  376. }
  377. else if (Sse2.IsSupported)
  378. {
  379. WriteByte(position, (byte)Sse2.Extract(Sse.StaticCast<float, ushort>(value), 0));
  380. }
  381. else
  382. {
  383. WriteByte(position, (byte)VectorHelper.VectorExtractIntZx(value, 0, 0));
  384. }
  385. }
  386. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  387. public void WriteVector16(long position, Vector128<float> value)
  388. {
  389. if (Sse2.IsSupported)
  390. {
  391. WriteUInt16(position, Sse2.Extract(Sse.StaticCast<float, ushort>(value), 0));
  392. }
  393. else
  394. {
  395. WriteUInt16(position, (ushort)VectorHelper.VectorExtractIntZx(value, 0, 1));
  396. }
  397. }
  398. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  399. public void WriteVector32(long position, Vector128<float> value)
  400. {
  401. if (Sse.IsSupported && (position & 3) == 0)
  402. {
  403. Sse.StoreScalar((float*)TranslateWrite(position), value);
  404. }
  405. else
  406. {
  407. WriteUInt32(position, (uint)VectorHelper.VectorExtractIntZx(value, 0, 2));
  408. }
  409. }
  410. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  411. public void WriteVector64(long position, Vector128<float> value)
  412. {
  413. if (Sse2.IsSupported && (position & 7) == 0)
  414. {
  415. Sse2.StoreScalar((double*)TranslateWrite(position), Sse.StaticCast<float, double>(value));
  416. }
  417. else
  418. {
  419. WriteUInt64(position, VectorHelper.VectorExtractIntZx(value, 0, 3));
  420. }
  421. }
  422. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  423. public void WriteVector128(long position, Vector128<float> value)
  424. {
  425. if (Sse.IsSupported && (position & 15) == 0)
  426. {
  427. Sse.Store((float*)TranslateWrite(position), value);
  428. }
  429. else
  430. {
  431. WriteUInt64(position + 0, VectorHelper.VectorExtractIntZx(value, 0, 3));
  432. WriteUInt64(position + 8, VectorHelper.VectorExtractIntZx(value, 1, 3));
  433. }
  434. }
  435. public void WriteBytes(long position, byte[] data)
  436. {
  437. long endAddr = position + data.Length;
  438. if ((ulong)endAddr < (ulong)position)
  439. {
  440. throw new ArgumentOutOfRangeException(nameof(position));
  441. }
  442. int offset = 0;
  443. while ((ulong)position < (ulong)endAddr)
  444. {
  445. long pageLimit = (position + PageSize) & ~(long)PageMask;
  446. if ((ulong)pageLimit > (ulong)endAddr)
  447. {
  448. pageLimit = endAddr;
  449. }
  450. int copySize = (int)(pageLimit - position);
  451. Marshal.Copy(data, offset, (IntPtr)TranslateWrite(position), copySize);
  452. position += copySize;
  453. offset += copySize;
  454. }
  455. }
  456. public void WriteBytes(long position, byte[] data, int startIndex, int size)
  457. {
  458. //Note: This will be moved later.
  459. long endAddr = position + size;
  460. if ((ulong)endAddr < (ulong)position)
  461. {
  462. throw new ArgumentOutOfRangeException(nameof(position));
  463. }
  464. int offset = startIndex;
  465. while ((ulong)position < (ulong)endAddr)
  466. {
  467. long pageLimit = (position + PageSize) & ~(long)PageMask;
  468. if ((ulong)pageLimit > (ulong)endAddr)
  469. {
  470. pageLimit = endAddr;
  471. }
  472. int copySize = (int)(pageLimit - position);
  473. Marshal.Copy(data, offset, (IntPtr)TranslateWrite(position), copySize);
  474. position += copySize;
  475. offset += copySize;
  476. }
  477. }
  478. public void CopyBytes(long src, long dst, long size)
  479. {
  480. //Note: This will be moved later.
  481. if (IsContiguous(src, size) &&
  482. IsContiguous(dst, size))
  483. {
  484. byte* srcPtr = Translate(src);
  485. byte* dstPtr = TranslateWrite(dst);
  486. Buffer.MemoryCopy(srcPtr, dstPtr, size, size);
  487. }
  488. else
  489. {
  490. WriteBytes(dst, ReadBytes(src, size));
  491. }
  492. }
  493. public void Map(long va, long pa, long size)
  494. {
  495. SetPtEntries(va, _ramPtr + pa, size);
  496. }
  497. public void Unmap(long position, long size)
  498. {
  499. SetPtEntries(position, null, size);
  500. StopObservingRegion(position, size);
  501. }
  502. public bool IsMapped(long position)
  503. {
  504. if (!(IsValidPosition(position)))
  505. {
  506. return false;
  507. }
  508. long l0 = (position >> PtLvl0Bit) & PtLvl0Mask;
  509. long l1 = (position >> PtLvl1Bit) & PtLvl1Mask;
  510. if (_pageTable[l0] == null)
  511. {
  512. return false;
  513. }
  514. return _pageTable[l0][l1] != null || _observedPages.ContainsKey(position >> PtPageBits);
  515. }
  516. public long GetPhysicalAddress(long virtualAddress)
  517. {
  518. byte* ptr = Translate(virtualAddress);
  519. return (long)(ptr - _ramPtr);
  520. }
  521. internal byte* Translate(long position)
  522. {
  523. long l0 = (position >> PtLvl0Bit) & PtLvl0Mask;
  524. long l1 = (position >> PtLvl1Bit) & PtLvl1Mask;
  525. long old = position;
  526. byte** lvl1 = _pageTable[l0];
  527. if ((position >> (PtLvl0Bit + PtLvl0Bits)) != 0)
  528. {
  529. goto Unmapped;
  530. }
  531. if (lvl1 == null)
  532. {
  533. goto Unmapped;
  534. }
  535. position &= PageMask;
  536. byte* ptr = lvl1[l1];
  537. if (ptr == null)
  538. {
  539. goto Unmapped;
  540. }
  541. return ptr + position;
  542. Unmapped:
  543. return HandleNullPte(old);
  544. }
  545. private byte* HandleNullPte(long position)
  546. {
  547. long key = position >> PtPageBits;
  548. if (_observedPages.TryGetValue(key, out IntPtr ptr))
  549. {
  550. return (byte*)ptr + (position & PageMask);
  551. }
  552. InvalidAccess?.Invoke(this, new InvalidAccessEventArgs(position));
  553. throw new VmmPageFaultException(position);
  554. }
  555. internal byte* TranslateWrite(long position)
  556. {
  557. long l0 = (position >> PtLvl0Bit) & PtLvl0Mask;
  558. long l1 = (position >> PtLvl1Bit) & PtLvl1Mask;
  559. long old = position;
  560. byte** lvl1 = _pageTable[l0];
  561. if ((position >> (PtLvl0Bit + PtLvl0Bits)) != 0)
  562. {
  563. goto Unmapped;
  564. }
  565. if (lvl1 == null)
  566. {
  567. goto Unmapped;
  568. }
  569. position &= PageMask;
  570. byte* ptr = lvl1[l1];
  571. if (ptr == null)
  572. {
  573. goto Unmapped;
  574. }
  575. return ptr + position;
  576. Unmapped:
  577. return HandleNullPteWrite(old);
  578. }
  579. private byte* HandleNullPteWrite(long position)
  580. {
  581. long key = position >> PtPageBits;
  582. if (_observedPages.TryGetValue(key, out IntPtr ptr))
  583. {
  584. SetPtEntry(position, (byte*)ptr);
  585. return (byte*)ptr + (position & PageMask);
  586. }
  587. InvalidAccess?.Invoke(this, new InvalidAccessEventArgs(position));
  588. throw new VmmPageFaultException(position);
  589. }
  590. private void SetPtEntries(long va, byte* ptr, long size)
  591. {
  592. long endPosition = (va + size + PageMask) & ~PageMask;
  593. while ((ulong)va < (ulong)endPosition)
  594. {
  595. SetPtEntry(va, ptr);
  596. va += PageSize;
  597. if (ptr != null)
  598. {
  599. ptr += PageSize;
  600. }
  601. }
  602. }
  603. private void SetPtEntry(long position, byte* ptr)
  604. {
  605. if (!IsValidPosition(position))
  606. {
  607. throw new ArgumentOutOfRangeException(nameof(position));
  608. }
  609. long l0 = (position >> PtLvl0Bit) & PtLvl0Mask;
  610. long l1 = (position >> PtLvl1Bit) & PtLvl1Mask;
  611. if (_pageTable[l0] == null)
  612. {
  613. byte** lvl1 = (byte**)Marshal.AllocHGlobal(PtLvl1Size * IntPtr.Size);
  614. for (int zl1 = 0; zl1 < PtLvl1Size; zl1++)
  615. {
  616. lvl1[zl1] = null;
  617. }
  618. Thread.MemoryBarrier();
  619. _pageTable[l0] = lvl1;
  620. }
  621. _pageTable[l0][l1] = ptr;
  622. }
  623. public (bool[], int) IsRegionModified(long position, long size)
  624. {
  625. long endPosition = (position + size + PageMask) & ~PageMask;
  626. position &= ~PageMask;
  627. size = endPosition - position;
  628. bool[] modified = new bool[size >> PtPageBits];
  629. int count = 0;
  630. lock (_observedPages)
  631. {
  632. for (int page = 0; page < modified.Length; page++)
  633. {
  634. byte* ptr = Translate(position);
  635. if (_observedPages.TryAdd(position >> PtPageBits, (IntPtr)ptr))
  636. {
  637. modified[page] = true;
  638. count++;
  639. }
  640. else
  641. {
  642. long l0 = (position >> PtLvl0Bit) & PtLvl0Mask;
  643. long l1 = (position >> PtLvl1Bit) & PtLvl1Mask;
  644. byte** lvl1 = _pageTable[l0];
  645. if (lvl1 != null)
  646. {
  647. if (modified[page] = lvl1[l1] != null)
  648. {
  649. count++;
  650. }
  651. }
  652. }
  653. SetPtEntry(position, null);
  654. position += PageSize;
  655. }
  656. }
  657. return (modified, count);
  658. }
  659. public void StopObservingRegion(long position, long size)
  660. {
  661. long endPosition = (position + size + PageMask) & ~PageMask;
  662. while (position < endPosition)
  663. {
  664. lock (_observedPages)
  665. {
  666. if (_observedPages.TryRemove(position >> PtPageBits, out IntPtr ptr))
  667. {
  668. SetPtEntry(position, (byte*)ptr);
  669. }
  670. }
  671. position += PageSize;
  672. }
  673. }
  674. public bool TryGetHostAddress(long position, long size, out IntPtr ptr)
  675. {
  676. if (IsContiguous(position, size))
  677. {
  678. ptr = (IntPtr)Translate(position);
  679. return true;
  680. }
  681. ptr = IntPtr.Zero;
  682. return false;
  683. }
  684. private bool IsContiguous(long position, long size)
  685. {
  686. long endPos = position + size;
  687. position &= ~PageMask;
  688. long expectedPa = GetPhysicalAddress(position);
  689. while ((ulong)position < (ulong)endPos)
  690. {
  691. long pa = GetPhysicalAddress(position);
  692. if (pa != expectedPa)
  693. {
  694. return false;
  695. }
  696. position += PageSize;
  697. expectedPa += PageSize;
  698. }
  699. return true;
  700. }
  701. public bool IsValidPosition(long position)
  702. {
  703. return position >> (PtLvl0Bits + PtLvl1Bits + PtPageBits) == 0;
  704. }
  705. public void Dispose()
  706. {
  707. Dispose(true);
  708. }
  709. protected virtual void Dispose(bool disposing)
  710. {
  711. if (_pageTable == null)
  712. {
  713. return;
  714. }
  715. for (int l0 = 0; l0 < PtLvl0Size; l0++)
  716. {
  717. if (_pageTable[l0] != null)
  718. {
  719. Marshal.FreeHGlobal((IntPtr)_pageTable[l0]);
  720. }
  721. _pageTable[l0] = null;
  722. }
  723. Marshal.FreeHGlobal((IntPtr)_pageTable);
  724. _pageTable = null;
  725. }
  726. }
  727. }