MemoryManager.cs 21 KB

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