AMemory.cs 20 KB

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