MemoryManager.cs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745
  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. EnsureRangeIsValid(position, (uint)data.Length);
  341. Marshal.Copy(data, 0, (IntPtr)TranslateWrite(position), data.Length);
  342. }
  343. public void WriteBytes(long position, byte[] data, int startIndex, int size)
  344. {
  345. //Note: This will be moved later.
  346. //Using Translate instead of TranslateWrite is on purpose.
  347. EnsureRangeIsValid(position, (uint)size);
  348. Marshal.Copy(data, startIndex, (IntPtr)Translate(position), size);
  349. }
  350. public void CopyBytes(long src, long dst, long size)
  351. {
  352. //Note: This will be moved later.
  353. EnsureRangeIsValid(src, size);
  354. EnsureRangeIsValid(dst, size);
  355. byte* srcPtr = Translate(src);
  356. byte* dstPtr = TranslateWrite(dst);
  357. Buffer.MemoryCopy(srcPtr, dstPtr, size, size);
  358. }
  359. public void Map(long va, long pa, long size)
  360. {
  361. SetPtEntries(va, _ramPtr + pa, size);
  362. }
  363. public void Unmap(long position, long size)
  364. {
  365. SetPtEntries(position, null, size);
  366. StopObservingRegion(position, size);
  367. }
  368. public bool IsMapped(long position)
  369. {
  370. if (!(IsValidPosition(position)))
  371. {
  372. return false;
  373. }
  374. long l0 = (position >> PtLvl0Bit) & PtLvl0Mask;
  375. long l1 = (position >> PtLvl1Bit) & PtLvl1Mask;
  376. if (_pageTable[l0] == null)
  377. {
  378. return false;
  379. }
  380. return _pageTable[l0][l1] != null || _observedPages.ContainsKey(position >> PtPageBits);
  381. }
  382. public long GetPhysicalAddress(long virtualAddress)
  383. {
  384. byte* ptr = Translate(virtualAddress);
  385. return (long)(ptr - _ramPtr);
  386. }
  387. internal byte* Translate(long position)
  388. {
  389. long l0 = (position >> PtLvl0Bit) & PtLvl0Mask;
  390. long l1 = (position >> PtLvl1Bit) & PtLvl1Mask;
  391. long old = position;
  392. byte** lvl1 = _pageTable[l0];
  393. if ((position >> (PtLvl0Bit + PtLvl0Bits)) != 0)
  394. {
  395. goto Unmapped;
  396. }
  397. if (lvl1 == null)
  398. {
  399. goto Unmapped;
  400. }
  401. position &= PageMask;
  402. byte* ptr = lvl1[l1];
  403. if (ptr == null)
  404. {
  405. goto Unmapped;
  406. }
  407. return ptr + position;
  408. Unmapped:
  409. return HandleNullPte(old);
  410. }
  411. private byte* HandleNullPte(long position)
  412. {
  413. long key = position >> PtPageBits;
  414. if (_observedPages.TryGetValue(key, out IntPtr ptr))
  415. {
  416. return (byte*)ptr + (position & PageMask);
  417. }
  418. InvalidAccess?.Invoke(this, new InvalidAccessEventArgs(position));
  419. throw new VmmPageFaultException(position);
  420. }
  421. internal byte* TranslateWrite(long position)
  422. {
  423. long l0 = (position >> PtLvl0Bit) & PtLvl0Mask;
  424. long l1 = (position >> PtLvl1Bit) & PtLvl1Mask;
  425. long old = position;
  426. byte** lvl1 = _pageTable[l0];
  427. if ((position >> (PtLvl0Bit + PtLvl0Bits)) != 0)
  428. {
  429. goto Unmapped;
  430. }
  431. if (lvl1 == null)
  432. {
  433. goto Unmapped;
  434. }
  435. position &= PageMask;
  436. byte* ptr = lvl1[l1];
  437. if (ptr == null)
  438. {
  439. goto Unmapped;
  440. }
  441. return ptr + position;
  442. Unmapped:
  443. return HandleNullPteWrite(old);
  444. }
  445. private byte* HandleNullPteWrite(long position)
  446. {
  447. long key = position >> PtPageBits;
  448. if (_observedPages.TryGetValue(key, out IntPtr ptr))
  449. {
  450. SetPtEntry(position, (byte*)ptr);
  451. return (byte*)ptr + (position & PageMask);
  452. }
  453. InvalidAccess?.Invoke(this, new InvalidAccessEventArgs(position));
  454. throw new VmmPageFaultException(position);
  455. }
  456. private void SetPtEntries(long va, byte* ptr, long size)
  457. {
  458. long endPosition = (va + size + PageMask) & ~PageMask;
  459. while ((ulong)va < (ulong)endPosition)
  460. {
  461. SetPtEntry(va, ptr);
  462. va += PageSize;
  463. if (ptr != null)
  464. {
  465. ptr += PageSize;
  466. }
  467. }
  468. }
  469. private void SetPtEntry(long position, byte* ptr)
  470. {
  471. if (!IsValidPosition(position))
  472. {
  473. throw new ArgumentOutOfRangeException(nameof(position));
  474. }
  475. long l0 = (position >> PtLvl0Bit) & PtLvl0Mask;
  476. long l1 = (position >> PtLvl1Bit) & PtLvl1Mask;
  477. if (_pageTable[l0] == null)
  478. {
  479. byte** lvl1 = (byte**)Marshal.AllocHGlobal(PtLvl1Size * IntPtr.Size);
  480. for (int zl1 = 0; zl1 < PtLvl1Size; zl1++)
  481. {
  482. lvl1[zl1] = null;
  483. }
  484. Thread.MemoryBarrier();
  485. _pageTable[l0] = lvl1;
  486. }
  487. _pageTable[l0][l1] = ptr;
  488. }
  489. public (bool[], int) IsRegionModified(long position, long size)
  490. {
  491. long endPosition = (position + size + PageMask) & ~PageMask;
  492. position &= ~PageMask;
  493. size = endPosition - position;
  494. bool[] modified = new bool[size >> PtPageBits];
  495. int count = 0;
  496. lock (_observedPages)
  497. {
  498. for (int page = 0; page < modified.Length; page++)
  499. {
  500. byte* ptr = Translate(position);
  501. if (_observedPages.TryAdd(position >> PtPageBits, (IntPtr)ptr))
  502. {
  503. modified[page] = true;
  504. count++;
  505. }
  506. else
  507. {
  508. long l0 = (position >> PtLvl0Bit) & PtLvl0Mask;
  509. long l1 = (position >> PtLvl1Bit) & PtLvl1Mask;
  510. byte** lvl1 = _pageTable[l0];
  511. if (lvl1 != null)
  512. {
  513. if (modified[page] = lvl1[l1] != null)
  514. {
  515. count++;
  516. }
  517. }
  518. }
  519. SetPtEntry(position, null);
  520. position += PageSize;
  521. }
  522. }
  523. return (modified, count);
  524. }
  525. public void StopObservingRegion(long position, long size)
  526. {
  527. long endPosition = (position + size + PageMask) & ~PageMask;
  528. while (position < endPosition)
  529. {
  530. lock (_observedPages)
  531. {
  532. if (_observedPages.TryRemove(position >> PtPageBits, out IntPtr ptr))
  533. {
  534. SetPtEntry(position, (byte*)ptr);
  535. }
  536. }
  537. position += PageSize;
  538. }
  539. }
  540. public IntPtr GetHostAddress(long position, long size)
  541. {
  542. EnsureRangeIsValid(position, size);
  543. return (IntPtr)Translate(position);
  544. }
  545. internal void EnsureRangeIsValid(long position, long size)
  546. {
  547. long endPos = position + size;
  548. position &= ~PageMask;
  549. long expectedPa = GetPhysicalAddress(position);
  550. while ((ulong)position < (ulong)endPos)
  551. {
  552. long pa = GetPhysicalAddress(position);
  553. if (pa != expectedPa)
  554. {
  555. throw new VmmAccessException(position, size);
  556. }
  557. position += PageSize;
  558. expectedPa += PageSize;
  559. }
  560. }
  561. public bool IsValidPosition(long position)
  562. {
  563. return position >> (PtLvl0Bits + PtLvl1Bits + PtPageBits) == 0;
  564. }
  565. public void Dispose()
  566. {
  567. Dispose(true);
  568. }
  569. protected virtual void Dispose(bool disposing)
  570. {
  571. if (_pageTable == null)
  572. {
  573. return;
  574. }
  575. for (int l0 = 0; l0 < PtLvl0Size; l0++)
  576. {
  577. if (_pageTable[l0] != null)
  578. {
  579. Marshal.FreeHGlobal((IntPtr)_pageTable[l0]);
  580. }
  581. _pageTable[l0] = null;
  582. }
  583. Marshal.FreeHGlobal((IntPtr)_pageTable);
  584. _pageTable = null;
  585. }
  586. }
  587. }