MemoryManager.cs 18 KB

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