MemoryManager.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690
  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. private const long PteFlagNotModified = 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. return new IntPtr(ptr + (position & PageMask));
  83. }
  84. private IntPtr TranslateWrite(long position)
  85. {
  86. if (!IsValidPosition(position))
  87. {
  88. return IntPtr.Zero;
  89. }
  90. byte* ptr = GetPtEntry(position);
  91. ulong ptrUlong = (ulong)ptr;
  92. if ((ptrUlong & PteFlagsMask) != 0)
  93. {
  94. if ((ptrUlong & PteFlagNotModified) != 0)
  95. {
  96. ClearPtEntryFlag(position, PteFlagNotModified);
  97. }
  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)
  194. {
  195. List<(ulong, ulong)> ranges = new List<(ulong, ulong)>();
  196. ulong endAddress = (address + size + PageMask) & ~(ulong)PageMask;
  197. address &= ~(ulong)PageMask;
  198. ulong currAddr = address;
  199. ulong currSize = 0;
  200. while (address < endAddress)
  201. {
  202. if (IsValidPosition((long)address))
  203. {
  204. byte* ptr = ((byte**)_pageTable)[address >> PageBits];
  205. ulong ptrUlong = (ulong)ptr;
  206. if ((ptrUlong & PteFlagNotModified) == 0)
  207. {
  208. // Modified.
  209. currSize += PageSize;
  210. SetPtEntryFlag((long)address, PteFlagNotModified);
  211. }
  212. else
  213. {
  214. if (currSize != 0)
  215. {
  216. ranges.Add((currAddr, currSize));
  217. }
  218. currAddr = address + PageSize;
  219. currSize = 0;
  220. }
  221. }
  222. else
  223. {
  224. currSize += PageSize;
  225. }
  226. address += PageSize;
  227. }
  228. if (currSize != 0)
  229. {
  230. ranges.Add((currAddr, currSize));
  231. }
  232. return ranges.ToArray();
  233. }
  234. private bool IsContiguous(long position, long size)
  235. {
  236. long endPos = position + size;
  237. position &= ~PageMask;
  238. long expectedPa = GetPhysicalAddress(position);
  239. while ((ulong)position < (ulong)endPos)
  240. {
  241. long pa = GetPhysicalAddress(position);
  242. if (pa != expectedPa)
  243. {
  244. return false;
  245. }
  246. position += PageSize;
  247. expectedPa += PageSize;
  248. }
  249. return true;
  250. }
  251. public bool IsValidPosition(long position)
  252. {
  253. return (ulong)position < (ulong)AddressSpaceSize;
  254. }
  255. internal V128 AtomicLoadInt128(long position)
  256. {
  257. if ((position & 0xf) != 0)
  258. {
  259. AbortWithAlignmentFault(position);
  260. }
  261. IntPtr ptr = TranslateWrite(position);
  262. return MemoryManagerPal.AtomicLoad128(ptr);
  263. }
  264. internal bool AtomicCompareExchangeByte(long position, byte expected, byte desired)
  265. {
  266. int* ptr = (int*)Translate(position);
  267. int currentValue = *ptr;
  268. int expected32 = (currentValue & ~byte.MaxValue) | expected;
  269. int desired32 = (currentValue & ~byte.MaxValue) | desired;
  270. return Interlocked.CompareExchange(ref *ptr, desired32, expected32) == expected32;
  271. }
  272. internal bool AtomicCompareExchangeInt16(long position, short expected, short desired)
  273. {
  274. if ((position & 1) != 0)
  275. {
  276. AbortWithAlignmentFault(position);
  277. }
  278. int* ptr = (int*)Translate(position);
  279. int currentValue = *ptr;
  280. int expected32 = (currentValue & ~ushort.MaxValue) | (ushort)expected;
  281. int desired32 = (currentValue & ~ushort.MaxValue) | (ushort)desired;
  282. return Interlocked.CompareExchange(ref *ptr, desired32, expected32) == expected32;
  283. }
  284. public bool AtomicCompareExchangeInt32(long position, int expected, int desired)
  285. {
  286. if ((position & 3) != 0)
  287. {
  288. AbortWithAlignmentFault(position);
  289. }
  290. int* ptr = (int*)TranslateWrite(position);
  291. return Interlocked.CompareExchange(ref *ptr, desired, expected) == expected;
  292. }
  293. internal bool AtomicCompareExchangeInt64(long position, long expected, long desired)
  294. {
  295. if ((position & 7) != 0)
  296. {
  297. AbortWithAlignmentFault(position);
  298. }
  299. long* ptr = (long*)TranslateWrite(position);
  300. return Interlocked.CompareExchange(ref *ptr, desired, expected) == expected;
  301. }
  302. internal bool AtomicCompareExchangeInt128(long position, V128 expected, V128 desired)
  303. {
  304. if ((position & 0xf) != 0)
  305. {
  306. AbortWithAlignmentFault(position);
  307. }
  308. IntPtr ptr = TranslateWrite(position);
  309. return MemoryManagerPal.CompareAndSwap128(ptr, expected, desired) == expected;
  310. }
  311. public int AtomicIncrementInt32(long position)
  312. {
  313. if ((position & 3) != 0)
  314. {
  315. AbortWithAlignmentFault(position);
  316. }
  317. int* ptr = (int*)TranslateWrite(position);
  318. return Interlocked.Increment(ref *ptr);
  319. }
  320. public int AtomicDecrementInt32(long position)
  321. {
  322. if ((position & 3) != 0)
  323. {
  324. AbortWithAlignmentFault(position);
  325. }
  326. int* ptr = (int*)TranslateWrite(position);
  327. return Interlocked.Decrement(ref *ptr);
  328. }
  329. private void AbortWithAlignmentFault(long position)
  330. {
  331. // TODO: Abort mode and exception support on the CPU.
  332. throw new InvalidOperationException($"Tried to compare exchange a misaligned address 0x{position:X16}.");
  333. }
  334. public sbyte ReadSByte(long position)
  335. {
  336. return (sbyte)ReadByte(position);
  337. }
  338. public short ReadInt16(long position)
  339. {
  340. return (short)ReadUInt16(position);
  341. }
  342. public int ReadInt32(long position)
  343. {
  344. return (int)ReadUInt32(position);
  345. }
  346. public long ReadInt64(long position)
  347. {
  348. return (long)ReadUInt64(position);
  349. }
  350. public byte ReadByte(long position)
  351. {
  352. return *((byte*)Translate(position));
  353. }
  354. public ushort ReadUInt16(long position)
  355. {
  356. if ((position & 1) == 0)
  357. {
  358. return *((ushort*)Translate(position));
  359. }
  360. else
  361. {
  362. return (ushort)(ReadByte(position + 0) << 0 |
  363. ReadByte(position + 1) << 8);
  364. }
  365. }
  366. public uint ReadUInt32(long position)
  367. {
  368. if ((position & 3) == 0)
  369. {
  370. return *((uint*)Translate(position));
  371. }
  372. else
  373. {
  374. return (uint)(ReadUInt16(position + 0) << 0 |
  375. ReadUInt16(position + 2) << 16);
  376. }
  377. }
  378. public ulong ReadUInt64(long position)
  379. {
  380. if ((position & 7) == 0)
  381. {
  382. return *((ulong*)Translate(position));
  383. }
  384. else
  385. {
  386. return (ulong)ReadUInt32(position + 0) << 0 |
  387. (ulong)ReadUInt32(position + 4) << 32;
  388. }
  389. }
  390. public V128 ReadVector128(long position)
  391. {
  392. return new V128(ReadUInt64(position), ReadUInt64(position + 8));
  393. }
  394. public byte[] ReadBytes(long position, long size)
  395. {
  396. long endAddr = position + size;
  397. if ((ulong)size > int.MaxValue)
  398. {
  399. throw new ArgumentOutOfRangeException(nameof(size));
  400. }
  401. if ((ulong)endAddr < (ulong)position)
  402. {
  403. throw new ArgumentOutOfRangeException(nameof(position));
  404. }
  405. byte[] data = new byte[size];
  406. int offset = 0;
  407. while ((ulong)position < (ulong)endAddr)
  408. {
  409. long pageLimit = (position + PageSize) & ~(long)PageMask;
  410. if ((ulong)pageLimit > (ulong)endAddr)
  411. {
  412. pageLimit = endAddr;
  413. }
  414. int copySize = (int)(pageLimit - position);
  415. Marshal.Copy(Translate(position), data, offset, copySize);
  416. position += copySize;
  417. offset += copySize;
  418. }
  419. return data;
  420. }
  421. public void WriteSByte(long position, sbyte value)
  422. {
  423. WriteByte(position, (byte)value);
  424. }
  425. public void WriteInt16(long position, short value)
  426. {
  427. WriteUInt16(position, (ushort)value);
  428. }
  429. public void WriteInt32(long position, int value)
  430. {
  431. WriteUInt32(position, (uint)value);
  432. }
  433. public void WriteInt64(long position, long value)
  434. {
  435. WriteUInt64(position, (ulong)value);
  436. }
  437. public void WriteByte(long position, byte value)
  438. {
  439. *((byte*)TranslateWrite(position)) = value;
  440. }
  441. public void WriteUInt16(long position, ushort value)
  442. {
  443. if ((position & 1) == 0)
  444. {
  445. *((ushort*)TranslateWrite(position)) = value;
  446. }
  447. else
  448. {
  449. WriteByte(position + 0, (byte)(value >> 0));
  450. WriteByte(position + 1, (byte)(value >> 8));
  451. }
  452. }
  453. public void WriteUInt32(long position, uint value)
  454. {
  455. if ((position & 3) == 0)
  456. {
  457. *((uint*)TranslateWrite(position)) = value;
  458. }
  459. else
  460. {
  461. WriteUInt16(position + 0, (ushort)(value >> 0));
  462. WriteUInt16(position + 2, (ushort)(value >> 16));
  463. }
  464. }
  465. public void WriteUInt64(long position, ulong value)
  466. {
  467. if ((position & 7) == 0)
  468. {
  469. *((ulong*)TranslateWrite(position)) = value;
  470. }
  471. else
  472. {
  473. WriteUInt32(position + 0, (uint)(value >> 0));
  474. WriteUInt32(position + 4, (uint)(value >> 32));
  475. }
  476. }
  477. public void WriteVector128(long position, V128 value)
  478. {
  479. WriteUInt64(position + 0, value.GetUInt64(0));
  480. WriteUInt64(position + 8, value.GetUInt64(1));
  481. }
  482. public void WriteBytes(long position, byte[] data)
  483. {
  484. long endAddr = position + data.Length;
  485. if ((ulong)endAddr < (ulong)position)
  486. {
  487. throw new ArgumentOutOfRangeException(nameof(position));
  488. }
  489. int offset = 0;
  490. while ((ulong)position < (ulong)endAddr)
  491. {
  492. long pageLimit = (position + PageSize) & ~(long)PageMask;
  493. if ((ulong)pageLimit > (ulong)endAddr)
  494. {
  495. pageLimit = endAddr;
  496. }
  497. int copySize = (int)(pageLimit - position);
  498. Marshal.Copy(data, offset, TranslateWrite(position), copySize);
  499. position += copySize;
  500. offset += copySize;
  501. }
  502. }
  503. public void Dispose()
  504. {
  505. Dispose(true);
  506. }
  507. protected virtual void Dispose(bool disposing)
  508. {
  509. IntPtr ptr = Interlocked.Exchange(ref _pageTable, IntPtr.Zero);
  510. if (ptr != IntPtr.Zero)
  511. {
  512. FreePageTableEntry(ptr, PageBits);
  513. }
  514. }
  515. private void FreePageTableEntry(IntPtr ptr, int levelBitEnd)
  516. {
  517. levelBitEnd += PtLevelBits;
  518. if (levelBitEnd >= AddressSpaceBits)
  519. {
  520. Free(ptr);
  521. return;
  522. }
  523. for (int index = 0; index < PtLevelSize; index++)
  524. {
  525. IntPtr ptePtr = ((IntPtr*)ptr)[index];
  526. if (ptePtr != IntPtr.Zero)
  527. {
  528. FreePageTableEntry(ptePtr, levelBitEnd);
  529. }
  530. }
  531. Free(ptr);
  532. }
  533. }
  534. }