MemoryManager.cs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738
  1. using ARMeilleure.State;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Runtime.CompilerServices;
  5. using System.Runtime.InteropServices;
  6. using System.Threading;
  7. using static ARMeilleure.Memory.MemoryManagement;
  8. namespace ARMeilleure.Memory
  9. {
  10. public unsafe class MemoryManager
  11. {
  12. public const int PageBits = 12;
  13. public const int PageSize = 1 << PageBits;
  14. public const int PageMask = PageSize - 1;
  15. internal const long PteFlagsMask = 7;
  16. public IntPtr Ram { get; private set; }
  17. private byte* _ramPtr;
  18. private IntPtr _pageTable;
  19. internal IntPtr PageTable => _pageTable;
  20. internal int PtLevelBits { get; }
  21. internal int PtLevelSize { get; }
  22. internal int PtLevelMask { get; }
  23. public int AddressSpaceBits { get; }
  24. public long AddressSpaceSize { get; }
  25. public MemoryManager(
  26. IntPtr ram,
  27. int addressSpaceBits = 48,
  28. bool useFlatPageTable = false)
  29. {
  30. Ram = ram;
  31. _ramPtr = (byte*)ram;
  32. AddressSpaceBits = addressSpaceBits;
  33. AddressSpaceSize = 1L << addressSpaceBits;
  34. // When flat page table is requested, we use a single
  35. // array for the mappings of the entire address space.
  36. // This has better performance, but also high memory usage.
  37. // The multi level page table uses 9 bits per level, so
  38. // the memory usage is lower, but the performance is also
  39. // lower, since each address translation requires multiple reads.
  40. if (useFlatPageTable)
  41. {
  42. PtLevelBits = addressSpaceBits - PageBits;
  43. }
  44. else
  45. {
  46. PtLevelBits = 9;
  47. }
  48. PtLevelSize = 1 << PtLevelBits;
  49. PtLevelMask = PtLevelSize - 1;
  50. _pageTable = Allocate((ulong)(PtLevelSize * IntPtr.Size));
  51. }
  52. public void Map(long va, long pa, long size)
  53. {
  54. SetPtEntries(va, _ramPtr + pa, size);
  55. }
  56. public void Unmap(long position, long size)
  57. {
  58. SetPtEntries(position, null, size);
  59. }
  60. public bool IsMapped(long position)
  61. {
  62. return Translate(position) != IntPtr.Zero;
  63. }
  64. public long GetPhysicalAddress(long virtualAddress)
  65. {
  66. byte* ptr = (byte*)Translate(virtualAddress);
  67. return (long)(ptr - _ramPtr);
  68. }
  69. private IntPtr Translate(long position)
  70. {
  71. if (!IsValidPosition(position))
  72. {
  73. return IntPtr.Zero;
  74. }
  75. byte* ptr = GetPtEntry(position);
  76. ulong ptrUlong = (ulong)ptr;
  77. if ((ptrUlong & PteFlagsMask) != 0)
  78. {
  79. ptrUlong &= ~(ulong)PteFlagsMask;
  80. ptr = (byte*)ptrUlong;
  81. }
  82. if (ptr == null)
  83. {
  84. return IntPtr.Zero;
  85. }
  86. return new IntPtr(ptr + (position & PageMask));
  87. }
  88. private IntPtr TranslateWrite(long position)
  89. {
  90. if (!IsValidPosition(position))
  91. {
  92. return IntPtr.Zero;
  93. }
  94. byte* ptr = GetPtEntry(position);
  95. ulong ptrUlong = (ulong)ptr;
  96. if ((ptrUlong & PteFlagsMask) != 0)
  97. {
  98. ClearPtEntryFlag(position, PteFlagsMask);
  99. ptrUlong &= ~(ulong)PteFlagsMask;
  100. ptr = (byte*)ptrUlong;
  101. }
  102. return new IntPtr(ptr + (position & PageMask));
  103. }
  104. private byte* GetPtEntry(long position)
  105. {
  106. return *(byte**)GetPtPtr(position);
  107. }
  108. private void SetPtEntries(long va, byte* ptr, long size)
  109. {
  110. long endPosition = (va + size + PageMask) & ~PageMask;
  111. while ((ulong)va < (ulong)endPosition)
  112. {
  113. SetPtEntry(va, ptr);
  114. va += PageSize;
  115. if (ptr != null)
  116. {
  117. ptr += PageSize;
  118. }
  119. }
  120. }
  121. private void SetPtEntry(long position, byte* ptr)
  122. {
  123. *(byte**)GetPtPtr(position) = ptr;
  124. }
  125. private void SetPtEntryFlag(long position, long flag)
  126. {
  127. ModifyPtEntryFlag(position, flag, setFlag: true);
  128. }
  129. private void ClearPtEntryFlag(long position, long flag)
  130. {
  131. ModifyPtEntryFlag(position, flag, setFlag: false);
  132. }
  133. private void ModifyPtEntryFlag(long position, long flag, bool setFlag)
  134. {
  135. IntPtr* pt = (IntPtr*)_pageTable;
  136. while (true)
  137. {
  138. IntPtr* ptPtr = GetPtPtr(position);
  139. IntPtr old = *ptPtr;
  140. long modified = old.ToInt64();
  141. if (setFlag)
  142. {
  143. modified |= flag;
  144. }
  145. else
  146. {
  147. modified &= ~flag;
  148. }
  149. IntPtr origValue = Interlocked.CompareExchange(ref *ptPtr, new IntPtr(modified), old);
  150. if (origValue == old)
  151. {
  152. break;
  153. }
  154. }
  155. }
  156. private IntPtr* GetPtPtr(long position)
  157. {
  158. if (!IsValidPosition(position))
  159. {
  160. throw new ArgumentOutOfRangeException(nameof(position));
  161. }
  162. IntPtr nextPtr = _pageTable;
  163. IntPtr* ptePtr = null;
  164. int bit = PageBits;
  165. while (true)
  166. {
  167. long index = (position >> bit) & PtLevelMask;
  168. ptePtr = &((IntPtr*)nextPtr)[index];
  169. bit += PtLevelBits;
  170. if (bit >= AddressSpaceBits)
  171. {
  172. break;
  173. }
  174. nextPtr = *ptePtr;
  175. if (nextPtr == IntPtr.Zero)
  176. {
  177. // Entry does not yet exist, allocate a new one.
  178. IntPtr newPtr = Allocate((ulong)(PtLevelSize * IntPtr.Size));
  179. // Try to swap the current pointer (should be zero), with the allocated one.
  180. nextPtr = Interlocked.CompareExchange(ref *ptePtr, newPtr, IntPtr.Zero);
  181. // If the old pointer is not null, then another thread already has set it.
  182. if (nextPtr != IntPtr.Zero)
  183. {
  184. Free(newPtr);
  185. }
  186. else
  187. {
  188. nextPtr = newPtr;
  189. }
  190. }
  191. }
  192. return ptePtr;
  193. }
  194. public unsafe (ulong, ulong)[] GetModifiedRanges(ulong address, ulong size, int id)
  195. {
  196. ulong idMask = 1UL << id;
  197. List<(ulong, ulong)> ranges = new List<(ulong, ulong)>();
  198. ulong endAddress = (address + size + PageMask) & ~(ulong)PageMask;
  199. address &= ~(ulong)PageMask;
  200. ulong currAddr = address;
  201. ulong currSize = 0;
  202. while (address < endAddress)
  203. {
  204. // If the address is invalid, we stop and consider all the remaining memory
  205. // as not modified (since the address is invalid, we can't check, and technically
  206. // the memory doesn't exist).
  207. if (!IsValidPosition((long)address))
  208. {
  209. break;
  210. }
  211. byte* ptr = ((byte**)_pageTable)[address >> PageBits];
  212. ulong ptrUlong = (ulong)ptr;
  213. if ((ptrUlong & idMask) == 0)
  214. {
  215. // Modified.
  216. currSize += PageSize;
  217. SetPtEntryFlag((long)address, (long)idMask);
  218. }
  219. else
  220. {
  221. if (currSize != 0)
  222. {
  223. ranges.Add((currAddr, currSize));
  224. }
  225. currAddr = address + PageSize;
  226. currSize = 0;
  227. }
  228. address += PageSize;
  229. }
  230. if (currSize != 0)
  231. {
  232. ranges.Add((currAddr, currSize));
  233. }
  234. return ranges.ToArray();
  235. }
  236. private bool IsContiguous(long position, long size)
  237. {
  238. long endPos = position + size;
  239. position &= ~PageMask;
  240. long expectedPa = GetPhysicalAddress(position);
  241. while ((ulong)position < (ulong)endPos)
  242. {
  243. long pa = GetPhysicalAddress(position);
  244. if (pa != expectedPa)
  245. {
  246. return false;
  247. }
  248. position += PageSize;
  249. expectedPa += PageSize;
  250. }
  251. return true;
  252. }
  253. public bool IsValidPosition(long position)
  254. {
  255. return (ulong)position < (ulong)AddressSpaceSize;
  256. }
  257. internal V128 AtomicLoadInt128(long position)
  258. {
  259. if ((position & 0xf) != 0)
  260. {
  261. AbortWithAlignmentFault(position);
  262. }
  263. IntPtr ptr = TranslateWrite(position);
  264. return MemoryManagerPal.AtomicLoad128(ptr);
  265. }
  266. internal bool AtomicCompareExchangeByte(long position, byte expected, byte desired)
  267. {
  268. int* ptr = (int*)Translate(position);
  269. int currentValue = *ptr;
  270. int expected32 = (currentValue & ~byte.MaxValue) | expected;
  271. int desired32 = (currentValue & ~byte.MaxValue) | desired;
  272. return Interlocked.CompareExchange(ref *ptr, desired32, expected32) == expected32;
  273. }
  274. internal bool AtomicCompareExchangeInt16(long position, short expected, short desired)
  275. {
  276. if ((position & 1) != 0)
  277. {
  278. AbortWithAlignmentFault(position);
  279. }
  280. int* ptr = (int*)Translate(position);
  281. int currentValue = *ptr;
  282. int expected32 = (currentValue & ~ushort.MaxValue) | (ushort)expected;
  283. int desired32 = (currentValue & ~ushort.MaxValue) | (ushort)desired;
  284. return Interlocked.CompareExchange(ref *ptr, desired32, expected32) == expected32;
  285. }
  286. public bool AtomicCompareExchangeInt32(long position, int expected, int desired)
  287. {
  288. if ((position & 3) != 0)
  289. {
  290. AbortWithAlignmentFault(position);
  291. }
  292. int* ptr = (int*)TranslateWrite(position);
  293. return Interlocked.CompareExchange(ref *ptr, desired, expected) == expected;
  294. }
  295. internal bool AtomicCompareExchangeInt64(long position, long expected, long desired)
  296. {
  297. if ((position & 7) != 0)
  298. {
  299. AbortWithAlignmentFault(position);
  300. }
  301. long* ptr = (long*)TranslateWrite(position);
  302. return Interlocked.CompareExchange(ref *ptr, desired, expected) == expected;
  303. }
  304. internal bool AtomicCompareExchangeInt128(long position, V128 expected, V128 desired)
  305. {
  306. if ((position & 0xf) != 0)
  307. {
  308. AbortWithAlignmentFault(position);
  309. }
  310. IntPtr ptr = TranslateWrite(position);
  311. return MemoryManagerPal.CompareAndSwap128(ptr, expected, desired) == expected;
  312. }
  313. public int AtomicIncrementInt32(long position)
  314. {
  315. if ((position & 3) != 0)
  316. {
  317. AbortWithAlignmentFault(position);
  318. }
  319. int* ptr = (int*)TranslateWrite(position);
  320. return Interlocked.Increment(ref *ptr);
  321. }
  322. public int AtomicDecrementInt32(long position)
  323. {
  324. if ((position & 3) != 0)
  325. {
  326. AbortWithAlignmentFault(position);
  327. }
  328. int* ptr = (int*)TranslateWrite(position);
  329. return Interlocked.Decrement(ref *ptr);
  330. }
  331. private void AbortWithAlignmentFault(long position)
  332. {
  333. // TODO: Abort mode and exception support on the CPU.
  334. throw new InvalidOperationException($"Tried to compare exchange a misaligned address 0x{position:X16}.");
  335. }
  336. public sbyte ReadSByte(long position)
  337. {
  338. return (sbyte)ReadByte(position);
  339. }
  340. public short ReadInt16(long position)
  341. {
  342. return (short)ReadUInt16(position);
  343. }
  344. public int ReadInt32(long position)
  345. {
  346. return (int)ReadUInt32(position);
  347. }
  348. public long ReadInt64(long position)
  349. {
  350. return (long)ReadUInt64(position);
  351. }
  352. public byte ReadByte(long position)
  353. {
  354. return *((byte*)Translate(position));
  355. }
  356. public ushort ReadUInt16(long position)
  357. {
  358. if ((position & 1) == 0)
  359. {
  360. return *((ushort*)Translate(position));
  361. }
  362. else
  363. {
  364. return (ushort)(ReadByte(position + 0) << 0 |
  365. ReadByte(position + 1) << 8);
  366. }
  367. }
  368. public uint ReadUInt32(long position)
  369. {
  370. if ((position & 3) == 0)
  371. {
  372. return *((uint*)Translate(position));
  373. }
  374. else
  375. {
  376. return (uint)(ReadUInt16(position + 0) << 0 |
  377. ReadUInt16(position + 2) << 16);
  378. }
  379. }
  380. public ulong ReadUInt64(long position)
  381. {
  382. if ((position & 7) == 0)
  383. {
  384. return *((ulong*)Translate(position));
  385. }
  386. else
  387. {
  388. return (ulong)ReadUInt32(position + 0) << 0 |
  389. (ulong)ReadUInt32(position + 4) << 32;
  390. }
  391. }
  392. public V128 ReadVector128(long position)
  393. {
  394. return new V128(ReadUInt64(position), ReadUInt64(position + 8));
  395. }
  396. public byte[] ReadBytes(long position, long size)
  397. {
  398. long endAddr = position + size;
  399. if ((ulong)size > int.MaxValue)
  400. {
  401. throw new ArgumentOutOfRangeException(nameof(size));
  402. }
  403. if ((ulong)endAddr < (ulong)position)
  404. {
  405. throw new ArgumentOutOfRangeException(nameof(position));
  406. }
  407. byte[] data = new byte[size];
  408. int offset = 0;
  409. while ((ulong)position < (ulong)endAddr)
  410. {
  411. long pageLimit = (position + PageSize) & ~(long)PageMask;
  412. if ((ulong)pageLimit > (ulong)endAddr)
  413. {
  414. pageLimit = endAddr;
  415. }
  416. int copySize = (int)(pageLimit - position);
  417. Marshal.Copy(Translate(position), data, offset, copySize);
  418. position += copySize;
  419. offset += copySize;
  420. }
  421. return data;
  422. }
  423. public ReadOnlySpan<byte> GetSpan(ulong address, ulong size)
  424. {
  425. if (IsContiguous(address, size))
  426. {
  427. return new ReadOnlySpan<byte>((void*)Translate((long)address), (int)size);
  428. }
  429. else
  430. {
  431. return ReadBytes((long)address, (long)size);
  432. }
  433. }
  434. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  435. private bool IsContiguous(ulong address, ulong size)
  436. {
  437. if (!IsValidPosition((long)address))
  438. {
  439. return false;
  440. }
  441. ulong endVa = (address + size + PageMask) & ~(ulong)PageMask;
  442. address &= ~(ulong)PageMask;
  443. int pages = (int)((endVa - address) / PageSize);
  444. for (int page = 0; page < pages - 1; page++)
  445. {
  446. if (!IsValidPosition((long)address + PageSize))
  447. {
  448. return false;
  449. }
  450. if (GetPtEntry((long)address) + PageSize != GetPtEntry((long)address + PageSize))
  451. {
  452. return false;
  453. }
  454. address += PageSize;
  455. }
  456. return true;
  457. }
  458. public void WriteSByte(long position, sbyte value)
  459. {
  460. WriteByte(position, (byte)value);
  461. }
  462. public void WriteInt16(long position, short value)
  463. {
  464. WriteUInt16(position, (ushort)value);
  465. }
  466. public void WriteInt32(long position, int value)
  467. {
  468. WriteUInt32(position, (uint)value);
  469. }
  470. public void WriteInt64(long position, long value)
  471. {
  472. WriteUInt64(position, (ulong)value);
  473. }
  474. public void WriteByte(long position, byte value)
  475. {
  476. *((byte*)TranslateWrite(position)) = value;
  477. }
  478. public void WriteUInt16(long position, ushort value)
  479. {
  480. if ((position & 1) == 0)
  481. {
  482. *((ushort*)TranslateWrite(position)) = value;
  483. }
  484. else
  485. {
  486. WriteByte(position + 0, (byte)(value >> 0));
  487. WriteByte(position + 1, (byte)(value >> 8));
  488. }
  489. }
  490. public void WriteUInt32(long position, uint value)
  491. {
  492. if ((position & 3) == 0)
  493. {
  494. *((uint*)TranslateWrite(position)) = value;
  495. }
  496. else
  497. {
  498. WriteUInt16(position + 0, (ushort)(value >> 0));
  499. WriteUInt16(position + 2, (ushort)(value >> 16));
  500. }
  501. }
  502. public void WriteUInt64(long position, ulong value)
  503. {
  504. if ((position & 7) == 0)
  505. {
  506. *((ulong*)TranslateWrite(position)) = value;
  507. }
  508. else
  509. {
  510. WriteUInt32(position + 0, (uint)(value >> 0));
  511. WriteUInt32(position + 4, (uint)(value >> 32));
  512. }
  513. }
  514. public void WriteVector128(long position, V128 value)
  515. {
  516. WriteUInt64(position + 0, value.Extract<ulong>(0));
  517. WriteUInt64(position + 8, value.Extract<ulong>(1));
  518. }
  519. public void WriteBytes(long position, byte[] data)
  520. {
  521. long endAddr = position + data.Length;
  522. if ((ulong)endAddr < (ulong)position)
  523. {
  524. throw new ArgumentOutOfRangeException(nameof(position));
  525. }
  526. int offset = 0;
  527. while ((ulong)position < (ulong)endAddr)
  528. {
  529. long pageLimit = (position + PageSize) & ~(long)PageMask;
  530. if ((ulong)pageLimit > (ulong)endAddr)
  531. {
  532. pageLimit = endAddr;
  533. }
  534. int copySize = (int)(pageLimit - position);
  535. Marshal.Copy(data, offset, TranslateWrite(position), copySize);
  536. position += copySize;
  537. offset += copySize;
  538. }
  539. }
  540. public void Dispose()
  541. {
  542. Dispose(true);
  543. }
  544. protected virtual void Dispose(bool disposing)
  545. {
  546. IntPtr ptr = Interlocked.Exchange(ref _pageTable, IntPtr.Zero);
  547. if (ptr != IntPtr.Zero)
  548. {
  549. FreePageTableEntry(ptr, PageBits);
  550. }
  551. }
  552. private void FreePageTableEntry(IntPtr ptr, int levelBitEnd)
  553. {
  554. levelBitEnd += PtLevelBits;
  555. if (levelBitEnd >= AddressSpaceBits)
  556. {
  557. Free(ptr);
  558. return;
  559. }
  560. for (int index = 0; index < PtLevelSize; index++)
  561. {
  562. IntPtr ptePtr = ((IntPtr*)ptr)[index];
  563. if (ptePtr != IntPtr.Zero)
  564. {
  565. FreePageTableEntry(ptePtr, levelBitEnd);
  566. }
  567. }
  568. Free(ptr);
  569. }
  570. }
  571. }