AddressSpaceManager.cs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603
  1. using System;
  2. using System.Runtime.CompilerServices;
  3. using System.Runtime.InteropServices;
  4. namespace Ryujinx.Memory
  5. {
  6. /// <summary>
  7. /// Represents a address space manager.
  8. /// Supports virtual memory region mapping, address translation and read/write access to mapped regions.
  9. /// </summary>
  10. public sealed class AddressSpaceManager : IVirtualMemoryManager, IWritableBlock
  11. {
  12. public const int PageBits = 12;
  13. public const int PageSize = 1 << PageBits;
  14. public const int PageMask = PageSize - 1;
  15. private const int PtLevelBits = 9; // 9 * 4 + 12 = 48 (max address space size)
  16. private const int PtLevelSize = 1 << PtLevelBits;
  17. private const int PtLevelMask = PtLevelSize - 1;
  18. private const ulong Unmapped = ulong.MaxValue;
  19. /// <summary>
  20. /// Address space width in bits.
  21. /// </summary>
  22. public int AddressSpaceBits { get; }
  23. private readonly ulong _addressSpaceSize;
  24. private readonly MemoryBlock _backingMemory;
  25. private readonly ulong[][][][] _pageTable;
  26. /// <summary>
  27. /// Creates a new instance of the memory manager.
  28. /// </summary>
  29. /// <param name="backingMemory">Physical backing memory where virtual memory will be mapped to</param>
  30. /// <param name="addressSpaceSize">Size of the address space</param>
  31. public AddressSpaceManager(MemoryBlock backingMemory, ulong addressSpaceSize)
  32. {
  33. ulong asSize = PageSize;
  34. int asBits = PageBits;
  35. while (asSize < addressSpaceSize)
  36. {
  37. asSize <<= 1;
  38. asBits++;
  39. }
  40. AddressSpaceBits = asBits;
  41. _addressSpaceSize = asSize;
  42. _backingMemory = backingMemory;
  43. _pageTable = new ulong[PtLevelSize][][][];
  44. }
  45. /// <summary>
  46. /// Maps a virtual memory range into a physical memory range.
  47. /// </summary>
  48. /// <remarks>
  49. /// Addresses and size must be page aligned.
  50. /// </remarks>
  51. /// <param name="va">Virtual memory address</param>
  52. /// <param name="pa">Physical memory address</param>
  53. /// <param name="size">Size to be mapped</param>
  54. public void Map(ulong va, ulong pa, ulong size)
  55. {
  56. AssertValidAddressAndSize(va, size);
  57. while (size != 0)
  58. {
  59. PtMap(va, pa);
  60. va += PageSize;
  61. pa += PageSize;
  62. size -= PageSize;
  63. }
  64. }
  65. /// <summary>
  66. /// Unmaps a previously mapped range of virtual memory.
  67. /// </summary>
  68. /// <param name="va">Virtual address of the range to be unmapped</param>
  69. /// <param name="size">Size of the range to be unmapped</param>
  70. public void Unmap(ulong va, ulong size)
  71. {
  72. AssertValidAddressAndSize(va, size);
  73. while (size != 0)
  74. {
  75. PtUnmap(va);
  76. va += PageSize;
  77. size -= PageSize;
  78. }
  79. }
  80. /// <summary>
  81. /// Reads data from mapped memory.
  82. /// </summary>
  83. /// <typeparam name="T">Type of the data being read</typeparam>
  84. /// <param name="va">Virtual address of the data in memory</param>
  85. /// <returns>The data</returns>
  86. /// <exception cref="InvalidMemoryRegionException">Throw for unhandled invalid or unmapped memory accesses</exception>
  87. public T Read<T>(ulong va) where T : unmanaged
  88. {
  89. return MemoryMarshal.Cast<byte, T>(GetSpan(va, Unsafe.SizeOf<T>()))[0];
  90. }
  91. /// <summary>
  92. /// Reads data from mapped memory.
  93. /// </summary>
  94. /// <param name="va">Virtual address of the data in memory</param>
  95. /// <param name="data">Span to store the data being read into</param>
  96. /// <exception cref="InvalidMemoryRegionException">Throw for unhandled invalid or unmapped memory accesses</exception>
  97. public void Read(ulong va, Span<byte> data)
  98. {
  99. ReadImpl(va, data);
  100. }
  101. /// <summary>
  102. /// Writes data to mapped memory.
  103. /// </summary>
  104. /// <typeparam name="T">Type of the data being written</typeparam>
  105. /// <param name="va">Virtual address to write the data into</param>
  106. /// <param name="value">Data to be written</param>
  107. /// <exception cref="InvalidMemoryRegionException">Throw for unhandled invalid or unmapped memory accesses</exception>
  108. public void Write<T>(ulong va, T value) where T : unmanaged
  109. {
  110. Write(va, MemoryMarshal.Cast<T, byte>(MemoryMarshal.CreateSpan(ref value, 1)));
  111. }
  112. /// <summary>
  113. /// Writes data to mapped memory.
  114. /// </summary>
  115. /// <param name="va">Virtual address to write the data into</param>
  116. /// <param name="data">Data to be written</param>
  117. /// <exception cref="InvalidMemoryRegionException">Throw for unhandled invalid or unmapped memory accesses</exception>
  118. public void Write(ulong va, ReadOnlySpan<byte> data)
  119. {
  120. if (data.Length == 0)
  121. {
  122. return;
  123. }
  124. AssertValidAddressAndSize(va, (ulong)data.Length);
  125. if (IsContiguousAndMapped(va, data.Length))
  126. {
  127. data.CopyTo(_backingMemory.GetSpan(GetPhysicalAddressInternal(va), data.Length));
  128. }
  129. else
  130. {
  131. int offset = 0, size;
  132. if ((va & PageMask) != 0)
  133. {
  134. ulong pa = GetPhysicalAddressInternal(va);
  135. size = Math.Min(data.Length, PageSize - (int)(va & PageMask));
  136. data.Slice(0, size).CopyTo(_backingMemory.GetSpan(pa, size));
  137. offset += size;
  138. }
  139. for (; offset < data.Length; offset += size)
  140. {
  141. ulong pa = GetPhysicalAddressInternal(va + (ulong)offset);
  142. size = Math.Min(data.Length - offset, PageSize);
  143. data.Slice(offset, size).CopyTo(_backingMemory.GetSpan(pa, size));
  144. }
  145. }
  146. }
  147. /// <summary>
  148. /// Gets a read-only span of data from mapped memory.
  149. /// </summary>
  150. /// <remarks>
  151. /// This may perform a allocation if the data is not contiguous in memory.
  152. /// For this reason, the span is read-only, you can't modify the data.
  153. /// </remarks>
  154. /// <param name="va">Virtual address of the data</param>
  155. /// <param name="size">Size of the data</param>
  156. /// <param name="tracked">True if read tracking is triggered on the span</param>
  157. /// <returns>A read-only span of the data</returns>
  158. /// <exception cref="InvalidMemoryRegionException">Throw for unhandled invalid or unmapped memory accesses</exception>
  159. public ReadOnlySpan<byte> GetSpan(ulong va, int size, bool tracked = false)
  160. {
  161. if (size == 0)
  162. {
  163. return ReadOnlySpan<byte>.Empty;
  164. }
  165. if (IsContiguousAndMapped(va, size))
  166. {
  167. return _backingMemory.GetSpan(GetPhysicalAddressInternal(va), size);
  168. }
  169. else
  170. {
  171. Span<byte> data = new byte[size];
  172. ReadImpl(va, data);
  173. return data;
  174. }
  175. }
  176. /// <summary>
  177. /// Gets a region of memory that can be written to.
  178. /// </summary>
  179. /// <remarks>
  180. /// If the requested region is not contiguous in physical memory,
  181. /// this will perform an allocation, and flush the data (writing it
  182. /// back to the backing memory) on disposal.
  183. /// </remarks>
  184. /// <param name="va">Virtual address of the data</param>
  185. /// <param name="size">Size of the data</param>
  186. /// <returns>A writable region of memory containing the data</returns>
  187. /// <exception cref="InvalidMemoryRegionException">Throw for unhandled invalid or unmapped memory accesses</exception>
  188. public WritableRegion GetWritableRegion(ulong va, int size)
  189. {
  190. if (size == 0)
  191. {
  192. return new WritableRegion(null, va, Memory<byte>.Empty);
  193. }
  194. if (IsContiguousAndMapped(va, size))
  195. {
  196. return new WritableRegion(null, va, _backingMemory.GetMemory(GetPhysicalAddressInternal(va), size));
  197. }
  198. else
  199. {
  200. Memory<byte> memory = new byte[size];
  201. GetSpan(va, size).CopyTo(memory.Span);
  202. return new WritableRegion(this, va, memory);
  203. }
  204. }
  205. /// <summary>
  206. /// Gets a reference for the given type at the specified virtual memory address.
  207. /// </summary>
  208. /// <remarks>
  209. /// The data must be located at a contiguous memory region.
  210. /// </remarks>
  211. /// <typeparam name="T">Type of the data to get the reference</typeparam>
  212. /// <param name="va">Virtual address of the data</param>
  213. /// <returns>A reference to the data in memory</returns>
  214. /// <exception cref="MemoryNotContiguousException">Throw if the specified memory region is not contiguous in physical memory</exception>
  215. public ref T GetRef<T>(ulong va) where T : unmanaged
  216. {
  217. if (!IsContiguous(va, Unsafe.SizeOf<T>()))
  218. {
  219. ThrowMemoryNotContiguous();
  220. }
  221. return ref _backingMemory.GetRef<T>(GetPhysicalAddressInternal(va));
  222. }
  223. /// <summary>
  224. /// Computes the number of pages in a virtual address range.
  225. /// </summary>
  226. /// <param name="va">Virtual address of the range</param>
  227. /// <param name="size">Size of the range</param>
  228. /// <param name="startVa">The virtual address of the beginning of the first page</param>
  229. /// <remarks>This function does not differentiate between allocated and unallocated pages.</remarks>
  230. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  231. private int GetPagesCount(ulong va, uint size, out ulong startVa)
  232. {
  233. // WARNING: Always check if ulong does not overflow during the operations.
  234. startVa = va & ~(ulong)PageMask;
  235. ulong vaSpan = (va - startVa + size + PageMask) & ~(ulong)PageMask;
  236. return (int)(vaSpan / PageSize);
  237. }
  238. private void ThrowMemoryNotContiguous() => throw new MemoryNotContiguousException();
  239. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  240. private bool IsContiguousAndMapped(ulong va, int size) => IsContiguous(va, size) && IsMapped(va);
  241. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  242. private bool IsContiguous(ulong va, int size)
  243. {
  244. if (!ValidateAddress(va) || !ValidateAddressAndSize(va, (ulong)size))
  245. {
  246. return false;
  247. }
  248. int pages = GetPagesCount(va, (uint)size, out va);
  249. for (int page = 0; page < pages - 1; page++)
  250. {
  251. if (!ValidateAddress(va + PageSize))
  252. {
  253. return false;
  254. }
  255. if (GetPhysicalAddressInternal(va) + PageSize != GetPhysicalAddressInternal(va + PageSize))
  256. {
  257. return false;
  258. }
  259. va += PageSize;
  260. }
  261. return true;
  262. }
  263. /// <summary>
  264. /// Gets the physical regions that make up the given virtual address region.
  265. /// If any part of the virtual region is unmapped, null is returned.
  266. /// </summary>
  267. /// <param name="va">Virtual address of the range</param>
  268. /// <param name="size">Size of the range</param>
  269. /// <returns>Array of physical regions</returns>
  270. public (ulong address, ulong size)[] GetPhysicalRegions(ulong va, ulong size)
  271. {
  272. throw new NotImplementedException();
  273. }
  274. private void ReadImpl(ulong va, Span<byte> data)
  275. {
  276. if (data.Length == 0)
  277. {
  278. return;
  279. }
  280. AssertValidAddressAndSize(va, (ulong)data.Length);
  281. int offset = 0, size;
  282. if ((va & PageMask) != 0)
  283. {
  284. ulong pa = GetPhysicalAddressInternal(va);
  285. size = Math.Min(data.Length, PageSize - (int)(va & PageMask));
  286. _backingMemory.GetSpan(pa, size).CopyTo(data.Slice(0, size));
  287. offset += size;
  288. }
  289. for (; offset < data.Length; offset += size)
  290. {
  291. ulong pa = GetPhysicalAddressInternal(va + (ulong)offset);
  292. size = Math.Min(data.Length - offset, PageSize);
  293. _backingMemory.GetSpan(pa, size).CopyTo(data.Slice(offset, size));
  294. }
  295. }
  296. /// <summary>
  297. /// Checks if the page at a given virtual address is mapped.
  298. /// </summary>
  299. /// <param name="va">Virtual address to check</param>
  300. /// <returns>True if the address is mapped, false otherwise</returns>
  301. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  302. public bool IsMapped(ulong va)
  303. {
  304. if (!ValidateAddress(va))
  305. {
  306. return false;
  307. }
  308. return PtRead(va) != Unmapped;
  309. }
  310. /// <summary>
  311. /// Checks if a memory range is mapped.
  312. /// </summary>
  313. /// <param name="va">Virtual address of the range</param>
  314. /// <param name="size">Size of the range in bytes</param>
  315. /// <returns>True if the entire range is mapped, false otherwise</returns>
  316. public bool IsRangeMapped(ulong va, ulong size)
  317. {
  318. if (size == 0UL)
  319. {
  320. return true;
  321. }
  322. if (!ValidateAddressAndSize(va, size))
  323. {
  324. return false;
  325. }
  326. int pages = GetPagesCount(va, (uint)size, out va);
  327. for (int page = 0; page < pages; page++)
  328. {
  329. if (!IsMapped(va))
  330. {
  331. return false;
  332. }
  333. va += PageSize;
  334. }
  335. return true;
  336. }
  337. private bool ValidateAddress(ulong va)
  338. {
  339. return va < _addressSpaceSize;
  340. }
  341. /// <summary>
  342. /// Checks if the combination of virtual address and size is part of the addressable space.
  343. /// </summary>
  344. /// <param name="va">Virtual address of the range</param>
  345. /// <param name="size">Size of the range in bytes</param>
  346. /// <returns>True if the combination of virtual address and size is part of the addressable space</returns>
  347. private bool ValidateAddressAndSize(ulong va, ulong size)
  348. {
  349. ulong endVa = va + size;
  350. return endVa >= va && endVa >= size && endVa <= _addressSpaceSize;
  351. }
  352. /// <summary>
  353. /// Ensures the combination of virtual address and size is part of the addressable space.
  354. /// </summary>
  355. /// <param name="va">Virtual address of the range</param>
  356. /// <param name="size">Size of the range in bytes</param>
  357. /// <exception cref="InvalidMemoryRegionException">Throw when the memory region specified outside the addressable space</exception>
  358. private void AssertValidAddressAndSize(ulong va, ulong size)
  359. {
  360. if (!ValidateAddressAndSize(va, size))
  361. {
  362. throw new InvalidMemoryRegionException($"va=0x{va:X16}, size=0x{size:X16}");
  363. }
  364. }
  365. /// <summary>
  366. /// Performs address translation of the address inside a mapped memory range.
  367. /// </summary>
  368. /// <remarks>
  369. /// If the address is invalid or unmapped, -1 will be returned.
  370. /// </remarks>
  371. /// <param name="va">Virtual address to be translated</param>
  372. /// <returns>The physical address</returns>
  373. public ulong GetPhysicalAddress(ulong va)
  374. {
  375. // We return -1L if the virtual address is invalid or unmapped.
  376. if (!ValidateAddress(va) || !IsMapped(va))
  377. {
  378. return ulong.MaxValue;
  379. }
  380. return GetPhysicalAddressInternal(va);
  381. }
  382. private ulong GetPhysicalAddressInternal(ulong va)
  383. {
  384. return PtRead(va) + (va & PageMask);
  385. }
  386. /// <summary>
  387. /// Reprotect a region of virtual memory for tracking. Sets software protection bits.
  388. /// </summary>
  389. /// <param name="va">Virtual address base</param>
  390. /// <param name="size">Size of the region to protect</param>
  391. /// <param name="protection">Memory protection to set</param>
  392. public void TrackingReprotect(ulong va, ulong size, MemoryPermission protection)
  393. {
  394. throw new NotImplementedException();
  395. }
  396. private ulong PtRead(ulong va)
  397. {
  398. int l3 = (int)(va >> PageBits) & PtLevelMask;
  399. int l2 = (int)(va >> (PageBits + PtLevelBits)) & PtLevelMask;
  400. int l1 = (int)(va >> (PageBits + PtLevelBits * 2)) & PtLevelMask;
  401. int l0 = (int)(va >> (PageBits + PtLevelBits * 3)) & PtLevelMask;
  402. if (_pageTable[l0] == null)
  403. {
  404. return Unmapped;
  405. }
  406. if (_pageTable[l0][l1] == null)
  407. {
  408. return Unmapped;
  409. }
  410. if (_pageTable[l0][l1][l2] == null)
  411. {
  412. return Unmapped;
  413. }
  414. return _pageTable[l0][l1][l2][l3];
  415. }
  416. private void PtMap(ulong va, ulong value)
  417. {
  418. int l3 = (int)(va >> PageBits) & PtLevelMask;
  419. int l2 = (int)(va >> (PageBits + PtLevelBits)) & PtLevelMask;
  420. int l1 = (int)(va >> (PageBits + PtLevelBits * 2)) & PtLevelMask;
  421. int l0 = (int)(va >> (PageBits + PtLevelBits * 3)) & PtLevelMask;
  422. if (_pageTable[l0] == null)
  423. {
  424. _pageTable[l0] = new ulong[PtLevelSize][][];
  425. }
  426. if (_pageTable[l0][l1] == null)
  427. {
  428. _pageTable[l0][l1] = new ulong[PtLevelSize][];
  429. }
  430. if (_pageTable[l0][l1][l2] == null)
  431. {
  432. _pageTable[l0][l1][l2] = new ulong[PtLevelSize];
  433. for (int i = 0; i < _pageTable[l0][l1][l2].Length; i++)
  434. {
  435. _pageTable[l0][l1][l2][i] = Unmapped;
  436. }
  437. }
  438. _pageTable[l0][l1][l2][l3] = value;
  439. }
  440. private void PtUnmap(ulong va)
  441. {
  442. int l3 = (int)(va >> PageBits) & PtLevelMask;
  443. int l2 = (int)(va >> (PageBits + PtLevelBits)) & PtLevelMask;
  444. int l1 = (int)(va >> (PageBits + PtLevelBits * 2)) & PtLevelMask;
  445. int l0 = (int)(va >> (PageBits + PtLevelBits * 3)) & PtLevelMask;
  446. if (_pageTable[l0] == null)
  447. {
  448. return;
  449. }
  450. if (_pageTable[l0][l1] == null)
  451. {
  452. return;
  453. }
  454. if (_pageTable[l0][l1][l2] == null)
  455. {
  456. return;
  457. }
  458. _pageTable[l0][l1][l2][l3] = Unmapped;
  459. bool empty = true;
  460. for (int i = 0; i < _pageTable[l0][l1][l2].Length; i++)
  461. {
  462. empty &= (_pageTable[l0][l1][l2][i] == Unmapped);
  463. }
  464. if (empty)
  465. {
  466. _pageTable[l0][l1][l2] = null;
  467. RemoveIfAllNull(l0, l1);
  468. }
  469. }
  470. private void RemoveIfAllNull(int l0, int l1)
  471. {
  472. bool empty = true;
  473. for (int i = 0; i < _pageTable[l0][l1].Length; i++)
  474. {
  475. empty &= (_pageTable[l0][l1][i] == null);
  476. }
  477. if (empty)
  478. {
  479. _pageTable[l0][l1] = null;
  480. RemoveIfAllNull(l0);
  481. }
  482. }
  483. private void RemoveIfAllNull(int l0)
  484. {
  485. bool empty = true;
  486. for (int i = 0; i < _pageTable[l0].Length; i++)
  487. {
  488. empty &= (_pageTable[l0][i] == null);
  489. }
  490. if (empty)
  491. {
  492. _pageTable[l0] = null;
  493. }
  494. }
  495. public void SignalMemoryTracking(ulong va, ulong size, bool write)
  496. {
  497. // Only the ARM Memory Manager has tracking for now.
  498. }
  499. }
  500. }