AddressSpaceManager.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475
  1. using Ryujinx.Memory.Range;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. using System.Runtime.CompilerServices;
  6. using System.Runtime.InteropServices;
  7. namespace Ryujinx.Memory
  8. {
  9. /// <summary>
  10. /// Represents a address space manager.
  11. /// Supports virtual memory region mapping, address translation and read/write access to mapped regions.
  12. /// </summary>
  13. public sealed class AddressSpaceManager : IVirtualMemoryManager, IWritableBlock
  14. {
  15. public const int PageBits = PageTable<nuint>.PageBits;
  16. public const int PageSize = PageTable<nuint>.PageSize;
  17. public const int PageMask = PageTable<nuint>.PageMask;
  18. /// <inheritdoc/>
  19. public bool Supports4KBPages => true;
  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 PageTable<nuint> _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 PageTable<nuint>();
  45. }
  46. /// <inheritdoc/>
  47. public void Map(ulong va, ulong pa, ulong size, MemoryMapFlags flags)
  48. {
  49. AssertValidAddressAndSize(va, size);
  50. while (size != 0)
  51. {
  52. _pageTable.Map(va, (nuint)(ulong)_backingMemory.GetPointer(pa, PageSize));
  53. va += PageSize;
  54. pa += PageSize;
  55. size -= PageSize;
  56. }
  57. }
  58. /// <inheritdoc/>
  59. public void MapForeign(ulong va, nuint hostPointer, ulong size)
  60. {
  61. AssertValidAddressAndSize(va, size);
  62. while (size != 0)
  63. {
  64. _pageTable.Map(va, hostPointer);
  65. va += PageSize;
  66. hostPointer += PageSize;
  67. size -= PageSize;
  68. }
  69. }
  70. /// <inheritdoc/>
  71. public void Unmap(ulong va, ulong size)
  72. {
  73. AssertValidAddressAndSize(va, size);
  74. while (size != 0)
  75. {
  76. _pageTable.Unmap(va);
  77. va += PageSize;
  78. size -= PageSize;
  79. }
  80. }
  81. /// <inheritdoc/>
  82. public T Read<T>(ulong va) where T : unmanaged
  83. {
  84. return MemoryMarshal.Cast<byte, T>(GetSpan(va, Unsafe.SizeOf<T>()))[0];
  85. }
  86. /// <inheritdoc/>
  87. public void Read(ulong va, Span<byte> data)
  88. {
  89. ReadImpl(va, data);
  90. }
  91. /// <inheritdoc/>
  92. public void Write<T>(ulong va, T value) where T : unmanaged
  93. {
  94. Write(va, MemoryMarshal.Cast<T, byte>(MemoryMarshal.CreateSpan(ref value, 1)));
  95. }
  96. /// <inheritdoc/>
  97. public void Write(ulong va, ReadOnlySpan<byte> data)
  98. {
  99. if (data.Length == 0)
  100. {
  101. return;
  102. }
  103. AssertValidAddressAndSize(va, (ulong)data.Length);
  104. if (IsContiguousAndMapped(va, data.Length))
  105. {
  106. data.CopyTo(GetHostSpanContiguous(va, data.Length));
  107. }
  108. else
  109. {
  110. int offset = 0, size;
  111. if ((va & PageMask) != 0)
  112. {
  113. size = Math.Min(data.Length, PageSize - (int)(va & PageMask));
  114. data[..size].CopyTo(GetHostSpanContiguous(va, size));
  115. offset += size;
  116. }
  117. for (; offset < data.Length; offset += size)
  118. {
  119. size = Math.Min(data.Length - offset, PageSize);
  120. data.Slice(offset, size).CopyTo(GetHostSpanContiguous(va + (ulong)offset, size));
  121. }
  122. }
  123. }
  124. /// <inheritdoc/>
  125. public bool WriteWithRedundancyCheck(ulong va, ReadOnlySpan<byte> data)
  126. {
  127. Write(va, data);
  128. return true;
  129. }
  130. /// <inheritdoc/>
  131. public ReadOnlySpan<byte> GetSpan(ulong va, int size, bool tracked = false)
  132. {
  133. if (size == 0)
  134. {
  135. return ReadOnlySpan<byte>.Empty;
  136. }
  137. if (IsContiguousAndMapped(va, size))
  138. {
  139. return GetHostSpanContiguous(va, size);
  140. }
  141. else
  142. {
  143. Span<byte> data = new byte[size];
  144. ReadImpl(va, data);
  145. return data;
  146. }
  147. }
  148. /// <inheritdoc/>
  149. public unsafe WritableRegion GetWritableRegion(ulong va, int size, bool tracked = false)
  150. {
  151. if (size == 0)
  152. {
  153. return new WritableRegion(null, va, Memory<byte>.Empty);
  154. }
  155. if (IsContiguousAndMapped(va, size))
  156. {
  157. return new WritableRegion(null, va, new NativeMemoryManager<byte>((byte*)GetHostAddress(va), size).Memory);
  158. }
  159. else
  160. {
  161. Memory<byte> memory = new byte[size];
  162. GetSpan(va, size).CopyTo(memory.Span);
  163. return new WritableRegion(this, va, memory);
  164. }
  165. }
  166. /// <inheritdoc/>
  167. public unsafe ref T GetRef<T>(ulong va) where T : unmanaged
  168. {
  169. if (!IsContiguous(va, Unsafe.SizeOf<T>()))
  170. {
  171. ThrowMemoryNotContiguous();
  172. }
  173. return ref *(T*)GetHostAddress(va);
  174. }
  175. /// <inheritdoc/>
  176. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  177. private static int GetPagesCount(ulong va, uint size, out ulong startVa)
  178. {
  179. // WARNING: Always check if ulong does not overflow during the operations.
  180. startVa = va & ~(ulong)PageMask;
  181. ulong vaSpan = (va - startVa + size + PageMask) & ~(ulong)PageMask;
  182. return (int)(vaSpan / PageSize);
  183. }
  184. private static void ThrowMemoryNotContiguous() => throw new MemoryNotContiguousException();
  185. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  186. private bool IsContiguousAndMapped(ulong va, int size) => IsContiguous(va, size) && IsMapped(va);
  187. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  188. private bool IsContiguous(ulong va, int size)
  189. {
  190. if (!ValidateAddress(va) || !ValidateAddressAndSize(va, (ulong)size))
  191. {
  192. return false;
  193. }
  194. int pages = GetPagesCount(va, (uint)size, out va);
  195. for (int page = 0; page < pages - 1; page++)
  196. {
  197. if (!ValidateAddress(va + PageSize))
  198. {
  199. return false;
  200. }
  201. if (GetHostAddress(va) + PageSize != GetHostAddress(va + PageSize))
  202. {
  203. return false;
  204. }
  205. va += PageSize;
  206. }
  207. return true;
  208. }
  209. /// <inheritdoc/>
  210. public IEnumerable<HostMemoryRange> GetHostRegions(ulong va, ulong size)
  211. {
  212. if (size == 0)
  213. {
  214. return Enumerable.Empty<HostMemoryRange>();
  215. }
  216. return GetHostRegionsImpl(va, size);
  217. }
  218. /// <inheritdoc/>
  219. public IEnumerable<MemoryRange> GetPhysicalRegions(ulong va, ulong size)
  220. {
  221. if (size == 0)
  222. {
  223. return Enumerable.Empty<MemoryRange>();
  224. }
  225. var hostRegions = GetHostRegionsImpl(va, size);
  226. if (hostRegions == null)
  227. {
  228. return null;
  229. }
  230. var regions = new MemoryRange[hostRegions.Count];
  231. ulong backingStart = (ulong)_backingMemory.Pointer;
  232. ulong backingEnd = backingStart + _backingMemory.Size;
  233. int count = 0;
  234. for (int i = 0; i < regions.Length; i++)
  235. {
  236. var hostRegion = hostRegions[i];
  237. if ((ulong)hostRegion.Address >= backingStart && (ulong)hostRegion.Address < backingEnd)
  238. {
  239. regions[count++] = new MemoryRange((ulong)hostRegion.Address - backingStart, hostRegion.Size);
  240. }
  241. }
  242. if (count != regions.Length)
  243. {
  244. return new ArraySegment<MemoryRange>(regions, 0, count);
  245. }
  246. return regions;
  247. }
  248. private List<HostMemoryRange> GetHostRegionsImpl(ulong va, ulong size)
  249. {
  250. if (!ValidateAddress(va) || !ValidateAddressAndSize(va, size))
  251. {
  252. return null;
  253. }
  254. int pages = GetPagesCount(va, (uint)size, out va);
  255. var regions = new List<HostMemoryRange>();
  256. nuint regionStart = GetHostAddress(va);
  257. ulong regionSize = PageSize;
  258. for (int page = 0; page < pages - 1; page++)
  259. {
  260. if (!ValidateAddress(va + PageSize))
  261. {
  262. return null;
  263. }
  264. nuint newHostAddress = GetHostAddress(va + PageSize);
  265. if (GetHostAddress(va) + PageSize != newHostAddress)
  266. {
  267. regions.Add(new HostMemoryRange(regionStart, regionSize));
  268. regionStart = newHostAddress;
  269. regionSize = 0;
  270. }
  271. va += PageSize;
  272. regionSize += PageSize;
  273. }
  274. regions.Add(new HostMemoryRange(regionStart, regionSize));
  275. return regions;
  276. }
  277. private void ReadImpl(ulong va, Span<byte> data)
  278. {
  279. if (data.Length == 0)
  280. {
  281. return;
  282. }
  283. AssertValidAddressAndSize(va, (ulong)data.Length);
  284. int offset = 0, size;
  285. if ((va & PageMask) != 0)
  286. {
  287. size = Math.Min(data.Length, PageSize - (int)(va & PageMask));
  288. GetHostSpanContiguous(va, size).CopyTo(data[..size]);
  289. offset += size;
  290. }
  291. for (; offset < data.Length; offset += size)
  292. {
  293. size = Math.Min(data.Length - offset, PageSize);
  294. GetHostSpanContiguous(va + (ulong)offset, size).CopyTo(data.Slice(offset, size));
  295. }
  296. }
  297. /// <inheritdoc/>
  298. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  299. public bool IsMapped(ulong va)
  300. {
  301. if (!ValidateAddress(va))
  302. {
  303. return false;
  304. }
  305. return _pageTable.Read(va) != 0;
  306. }
  307. /// <inheritdoc/>
  308. public bool IsRangeMapped(ulong va, ulong size)
  309. {
  310. if (size == 0UL)
  311. {
  312. return true;
  313. }
  314. if (!ValidateAddressAndSize(va, size))
  315. {
  316. return false;
  317. }
  318. int pages = GetPagesCount(va, (uint)size, out va);
  319. for (int page = 0; page < pages; page++)
  320. {
  321. if (!IsMapped(va))
  322. {
  323. return false;
  324. }
  325. va += PageSize;
  326. }
  327. return true;
  328. }
  329. private bool ValidateAddress(ulong va)
  330. {
  331. return va < _addressSpaceSize;
  332. }
  333. /// <summary>
  334. /// Checks if the combination of virtual address and size is part of the addressable space.
  335. /// </summary>
  336. /// <param name="va">Virtual address of the range</param>
  337. /// <param name="size">Size of the range in bytes</param>
  338. /// <returns>True if the combination of virtual address and size is part of the addressable space</returns>
  339. private bool ValidateAddressAndSize(ulong va, ulong size)
  340. {
  341. ulong endVa = va + size;
  342. return endVa >= va && endVa >= size && endVa <= _addressSpaceSize;
  343. }
  344. /// <summary>
  345. /// Ensures the combination of virtual address and size is part of the addressable space.
  346. /// </summary>
  347. /// <param name="va">Virtual address of the range</param>
  348. /// <param name="size">Size of the range in bytes</param>
  349. /// <exception cref="InvalidMemoryRegionException">Throw when the memory region specified outside the addressable space</exception>
  350. private void AssertValidAddressAndSize(ulong va, ulong size)
  351. {
  352. if (!ValidateAddressAndSize(va, size))
  353. {
  354. throw new InvalidMemoryRegionException($"va=0x{va:X16}, size=0x{size:X16}");
  355. }
  356. }
  357. private unsafe Span<byte> GetHostSpanContiguous(ulong va, int size)
  358. {
  359. return new Span<byte>((void*)GetHostAddress(va), size);
  360. }
  361. private nuint GetHostAddress(ulong va)
  362. {
  363. return _pageTable.Read(va) + (nuint)(va & PageMask);
  364. }
  365. /// <inheritdoc/>
  366. public void Reprotect(ulong va, ulong size, MemoryPermission protection)
  367. {
  368. }
  369. /// <inheritdoc/>
  370. public void TrackingReprotect(ulong va, ulong size, MemoryPermission protection)
  371. {
  372. throw new NotImplementedException();
  373. }
  374. /// <inheritdoc/>
  375. public void SignalMemoryTracking(ulong va, ulong size, bool write, bool precise = false, int? exemptId = null)
  376. {
  377. // Only the ARM Memory Manager has tracking for now.
  378. }
  379. }
  380. }