AddressSpaceManager.cs 18 KB

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