AddressSpaceManager.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553
  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. while (size != 0)
  57. {
  58. PtMap(va, pa);
  59. va += PageSize;
  60. pa += PageSize;
  61. size -= PageSize;
  62. }
  63. }
  64. /// <summary>
  65. /// Unmaps a previously mapped range of virtual memory.
  66. /// </summary>
  67. /// <param name="va">Virtual address of the range to be unmapped</param>
  68. /// <param name="size">Size of the range to be unmapped</param>
  69. public void Unmap(ulong va, ulong size)
  70. {
  71. while (size != 0)
  72. {
  73. PtUnmap(va);
  74. va += PageSize;
  75. size -= PageSize;
  76. }
  77. }
  78. /// <summary>
  79. /// Reads data from mapped memory.
  80. /// </summary>
  81. /// <typeparam name="T">Type of the data being read</typeparam>
  82. /// <param name="va">Virtual address of the data in memory</param>
  83. /// <returns>The data</returns>
  84. /// <exception cref="InvalidMemoryRegionException">Throw for unhandled invalid or unmapped memory accesses</exception>
  85. public T Read<T>(ulong va) where T : unmanaged
  86. {
  87. return MemoryMarshal.Cast<byte, T>(GetSpan(va, Unsafe.SizeOf<T>()))[0];
  88. }
  89. /// <summary>
  90. /// Reads data from mapped memory.
  91. /// </summary>
  92. /// <param name="va">Virtual address of the data in memory</param>
  93. /// <param name="data">Span to store the data being read into</param>
  94. /// <exception cref="InvalidMemoryRegionException">Throw for unhandled invalid or unmapped memory accesses</exception>
  95. public void Read(ulong va, Span<byte> data)
  96. {
  97. ReadImpl(va, data);
  98. }
  99. /// <summary>
  100. /// Writes data to mapped memory.
  101. /// </summary>
  102. /// <typeparam name="T">Type of the data being written</typeparam>
  103. /// <param name="va">Virtual address to write the data into</param>
  104. /// <param name="value">Data to be written</param>
  105. /// <exception cref="InvalidMemoryRegionException">Throw for unhandled invalid or unmapped memory accesses</exception>
  106. public void Write<T>(ulong va, T value) where T : unmanaged
  107. {
  108. Write(va, MemoryMarshal.Cast<T, byte>(MemoryMarshal.CreateSpan(ref value, 1)));
  109. }
  110. /// <summary>
  111. /// Writes data to mapped memory.
  112. /// </summary>
  113. /// <param name="va">Virtual address to write the data into</param>
  114. /// <param name="data">Data to be written</param>
  115. /// <exception cref="InvalidMemoryRegionException">Throw for unhandled invalid or unmapped memory accesses</exception>
  116. public void Write(ulong va, ReadOnlySpan<byte> data)
  117. {
  118. if (data.Length == 0)
  119. {
  120. return;
  121. }
  122. if (IsContiguousAndMapped(va, data.Length))
  123. {
  124. data.CopyTo(_backingMemory.GetSpan(GetPhysicalAddressInternal(va), data.Length));
  125. }
  126. else
  127. {
  128. int offset = 0, size;
  129. if ((va & PageMask) != 0)
  130. {
  131. ulong pa = GetPhysicalAddressInternal(va);
  132. size = Math.Min(data.Length, PageSize - (int)(va & PageMask));
  133. data.Slice(0, size).CopyTo(_backingMemory.GetSpan(pa, size));
  134. offset += size;
  135. }
  136. for (; offset < data.Length; offset += size)
  137. {
  138. ulong pa = GetPhysicalAddressInternal(va + (ulong)offset);
  139. size = Math.Min(data.Length - offset, PageSize);
  140. data.Slice(offset, size).CopyTo(_backingMemory.GetSpan(pa, size));
  141. }
  142. }
  143. }
  144. /// <summary>
  145. /// Gets a read-only span of data from mapped memory.
  146. /// </summary>
  147. /// <remarks>
  148. /// This may perform a allocation if the data is not contiguous in memory.
  149. /// For this reason, the span is read-only, you can't modify the data.
  150. /// </remarks>
  151. /// <param name="va">Virtual address of the data</param>
  152. /// <param name="size">Size of the data</param>
  153. /// <param name="tracked">True if read tracking is triggered on the span</param>
  154. /// <returns>A read-only span of the data</returns>
  155. /// <exception cref="InvalidMemoryRegionException">Throw for unhandled invalid or unmapped memory accesses</exception>
  156. public ReadOnlySpan<byte> GetSpan(ulong va, int size, bool tracked = false)
  157. {
  158. if (size == 0)
  159. {
  160. return ReadOnlySpan<byte>.Empty;
  161. }
  162. if (IsContiguousAndMapped(va, size))
  163. {
  164. return _backingMemory.GetSpan(GetPhysicalAddressInternal(va), size);
  165. }
  166. else
  167. {
  168. Span<byte> data = new byte[size];
  169. ReadImpl(va, data);
  170. return data;
  171. }
  172. }
  173. /// <summary>
  174. /// Gets a region of memory that can be written to.
  175. /// </summary>
  176. /// <remarks>
  177. /// If the requested region is not contiguous in physical memory,
  178. /// this will perform an allocation, and flush the data (writing it
  179. /// back to the backing memory) on disposal.
  180. /// </remarks>
  181. /// <param name="va">Virtual address of the data</param>
  182. /// <param name="size">Size of the data</param>
  183. /// <returns>A writable region of memory containing the data</returns>
  184. /// <exception cref="InvalidMemoryRegionException">Throw for unhandled invalid or unmapped memory accesses</exception>
  185. public WritableRegion GetWritableRegion(ulong va, int size)
  186. {
  187. if (size == 0)
  188. {
  189. return new WritableRegion(null, va, Memory<byte>.Empty);
  190. }
  191. if (IsContiguousAndMapped(va, size))
  192. {
  193. return new WritableRegion(null, va, _backingMemory.GetMemory(GetPhysicalAddressInternal(va), size));
  194. }
  195. else
  196. {
  197. Memory<byte> memory = new byte[size];
  198. GetSpan(va, size).CopyTo(memory.Span);
  199. return new WritableRegion(this, va, memory);
  200. }
  201. }
  202. /// <summary>
  203. /// Gets a reference for the given type at the specified virtual memory address.
  204. /// </summary>
  205. /// <remarks>
  206. /// The data must be located at a contiguous memory region.
  207. /// </remarks>
  208. /// <typeparam name="T">Type of the data to get the reference</typeparam>
  209. /// <param name="va">Virtual address of the data</param>
  210. /// <returns>A reference to the data in memory</returns>
  211. /// <exception cref="MemoryNotContiguousException">Throw if the specified memory region is not contiguous in physical memory</exception>
  212. public ref T GetRef<T>(ulong va) where T : unmanaged
  213. {
  214. if (!IsContiguous(va, Unsafe.SizeOf<T>()))
  215. {
  216. ThrowMemoryNotContiguous();
  217. }
  218. return ref _backingMemory.GetRef<T>(GetPhysicalAddressInternal(va));
  219. }
  220. private void ThrowMemoryNotContiguous() => throw new MemoryNotContiguousException();
  221. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  222. private bool IsContiguousAndMapped(ulong va, int size) => IsContiguous(va, size) && IsMapped(va);
  223. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  224. private bool IsContiguous(ulong va, int size)
  225. {
  226. if (!ValidateAddress(va))
  227. {
  228. return false;
  229. }
  230. ulong endVa = (va + (ulong)size + PageMask) & ~(ulong)PageMask;
  231. va &= ~(ulong)PageMask;
  232. int pages = (int)((endVa - va) / PageSize);
  233. for (int page = 0; page < pages - 1; page++)
  234. {
  235. if (!ValidateAddress(va + PageSize))
  236. {
  237. return false;
  238. }
  239. if (GetPhysicalAddressInternal(va) + PageSize != GetPhysicalAddressInternal(va + PageSize))
  240. {
  241. return false;
  242. }
  243. va += PageSize;
  244. }
  245. return true;
  246. }
  247. /// <summary>
  248. /// Gets the physical regions that make up the given virtual address region.
  249. /// If any part of the virtual region is unmapped, null is returned.
  250. /// </summary>
  251. /// <param name="va">Virtual address of the range</param>
  252. /// <param name="size">Size of the range</param>
  253. /// <returns>Array of physical regions</returns>
  254. public (ulong address, ulong size)[] GetPhysicalRegions(ulong va, ulong size)
  255. {
  256. throw new NotImplementedException();
  257. }
  258. private void ReadImpl(ulong va, Span<byte> data)
  259. {
  260. if (data.Length == 0)
  261. {
  262. return;
  263. }
  264. int offset = 0, size;
  265. if ((va & PageMask) != 0)
  266. {
  267. ulong pa = GetPhysicalAddressInternal(va);
  268. size = Math.Min(data.Length, PageSize - (int)(va & PageMask));
  269. _backingMemory.GetSpan(pa, size).CopyTo(data.Slice(0, size));
  270. offset += size;
  271. }
  272. for (; offset < data.Length; offset += size)
  273. {
  274. ulong pa = GetPhysicalAddressInternal(va + (ulong)offset);
  275. size = Math.Min(data.Length - offset, PageSize);
  276. _backingMemory.GetSpan(pa, size).CopyTo(data.Slice(offset, size));
  277. }
  278. }
  279. /// <summary>
  280. /// Checks if the page at a given virtual address is mapped.
  281. /// </summary>
  282. /// <param name="va">Virtual address to check</param>
  283. /// <returns>True if the address is mapped, false otherwise</returns>
  284. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  285. public bool IsMapped(ulong va)
  286. {
  287. if (!ValidateAddress(va))
  288. {
  289. return false;
  290. }
  291. return PtRead(va) != Unmapped;
  292. }
  293. /// <summary>
  294. /// Checks if a memory range is mapped.
  295. /// </summary>
  296. /// <param name="va">Virtual address of the range</param>
  297. /// <param name="size">Size of the range in bytes</param>
  298. /// <returns>True if the entire range is mapped, false otherwise</returns>
  299. public bool IsRangeMapped(ulong va, ulong size)
  300. {
  301. if (size == 0UL)
  302. {
  303. return true;
  304. }
  305. ulong endVa = (va + size + PageMask) & ~(ulong)PageMask;
  306. va &= ~(ulong)PageMask;
  307. while (va < endVa)
  308. {
  309. if (!IsMapped(va))
  310. {
  311. return false;
  312. }
  313. va += PageSize;
  314. }
  315. return true;
  316. }
  317. private bool ValidateAddress(ulong va)
  318. {
  319. return va < _addressSpaceSize;
  320. }
  321. /// <summary>
  322. /// Performs address translation of the address inside a mapped memory range.
  323. /// </summary>
  324. /// <remarks>
  325. /// If the address is invalid or unmapped, -1 will be returned.
  326. /// </remarks>
  327. /// <param name="va">Virtual address to be translated</param>
  328. /// <returns>The physical address</returns>
  329. public ulong GetPhysicalAddress(ulong va)
  330. {
  331. // We return -1L if the virtual address is invalid or unmapped.
  332. if (!ValidateAddress(va) || !IsMapped(va))
  333. {
  334. return ulong.MaxValue;
  335. }
  336. return GetPhysicalAddressInternal(va);
  337. }
  338. private ulong GetPhysicalAddressInternal(ulong va)
  339. {
  340. return PtRead(va) + (va & PageMask);
  341. }
  342. /// <summary>
  343. /// Reprotect a region of virtual memory for tracking. Sets software protection bits.
  344. /// </summary>
  345. /// <param name="va">Virtual address base</param>
  346. /// <param name="size">Size of the region to protect</param>
  347. /// <param name="protection">Memory protection to set</param>
  348. public void TrackingReprotect(ulong va, ulong size, MemoryPermission protection)
  349. {
  350. throw new NotImplementedException();
  351. }
  352. private ulong PtRead(ulong va)
  353. {
  354. int l3 = (int)(va >> PageBits) & PtLevelMask;
  355. int l2 = (int)(va >> (PageBits + PtLevelBits)) & PtLevelMask;
  356. int l1 = (int)(va >> (PageBits + PtLevelBits * 2)) & PtLevelMask;
  357. int l0 = (int)(va >> (PageBits + PtLevelBits * 3)) & PtLevelMask;
  358. if (_pageTable[l0] == null)
  359. {
  360. return Unmapped;
  361. }
  362. if (_pageTable[l0][l1] == null)
  363. {
  364. return Unmapped;
  365. }
  366. if (_pageTable[l0][l1][l2] == null)
  367. {
  368. return Unmapped;
  369. }
  370. return _pageTable[l0][l1][l2][l3];
  371. }
  372. private void PtMap(ulong va, ulong value)
  373. {
  374. int l3 = (int)(va >> PageBits) & PtLevelMask;
  375. int l2 = (int)(va >> (PageBits + PtLevelBits)) & PtLevelMask;
  376. int l1 = (int)(va >> (PageBits + PtLevelBits * 2)) & PtLevelMask;
  377. int l0 = (int)(va >> (PageBits + PtLevelBits * 3)) & PtLevelMask;
  378. if (_pageTable[l0] == null)
  379. {
  380. _pageTable[l0] = new ulong[PtLevelSize][][];
  381. }
  382. if (_pageTable[l0][l1] == null)
  383. {
  384. _pageTable[l0][l1] = new ulong[PtLevelSize][];
  385. }
  386. if (_pageTable[l0][l1][l2] == null)
  387. {
  388. _pageTable[l0][l1][l2] = new ulong[PtLevelSize];
  389. for (int i = 0; i < _pageTable[l0][l1][l2].Length; i++)
  390. {
  391. _pageTable[l0][l1][l2][i] = Unmapped;
  392. }
  393. }
  394. _pageTable[l0][l1][l2][l3] = value;
  395. }
  396. private void PtUnmap(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;
  405. }
  406. if (_pageTable[l0][l1] == null)
  407. {
  408. return;
  409. }
  410. if (_pageTable[l0][l1][l2] == null)
  411. {
  412. return;
  413. }
  414. _pageTable[l0][l1][l2][l3] = Unmapped;
  415. bool empty = true;
  416. for (int i = 0; i < _pageTable[l0][l1][l2].Length; i++)
  417. {
  418. empty &= (_pageTable[l0][l1][l2][i] == Unmapped);
  419. }
  420. if (empty)
  421. {
  422. _pageTable[l0][l1][l2] = null;
  423. RemoveIfAllNull(l0, l1);
  424. }
  425. }
  426. private void RemoveIfAllNull(int l0, int l1)
  427. {
  428. bool empty = true;
  429. for (int i = 0; i < _pageTable[l0][l1].Length; i++)
  430. {
  431. empty &= (_pageTable[l0][l1][i] == null);
  432. }
  433. if (empty)
  434. {
  435. _pageTable[l0][l1] = null;
  436. RemoveIfAllNull(l0);
  437. }
  438. }
  439. private void RemoveIfAllNull(int l0)
  440. {
  441. bool empty = true;
  442. for (int i = 0; i < _pageTable[l0].Length; i++)
  443. {
  444. empty &= (_pageTable[l0][i] == null);
  445. }
  446. if (empty)
  447. {
  448. _pageTable[l0] = null;
  449. }
  450. }
  451. public void SignalMemoryTracking(ulong va, ulong size, bool write)
  452. {
  453. // Only the ARM Memory Manager has tracking for now.
  454. }
  455. }
  456. }