AddressSpaceManager.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412
  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 : VirtualMemoryManagerBase<ulong, nuint>, IVirtualMemoryManager, IWritableBlock
  14. {
  15. /// <inheritdoc/>
  16. public bool Supports4KBPages => true;
  17. /// <summary>
  18. /// Address space width in bits.
  19. /// </summary>
  20. public int AddressSpaceBits { get; }
  21. private readonly MemoryBlock _backingMemory;
  22. private readonly PageTable<nuint> _pageTable;
  23. protected override ulong AddressSpaceSize { get; }
  24. /// <summary>
  25. /// Creates a new instance of the memory manager.
  26. /// </summary>
  27. /// <param name="backingMemory">Physical backing memory where virtual memory will be mapped to</param>
  28. /// <param name="addressSpaceSize">Size of the address space</param>
  29. public AddressSpaceManager(MemoryBlock backingMemory, ulong addressSpaceSize)
  30. {
  31. ulong asSize = PageSize;
  32. int asBits = PageBits;
  33. while (asSize < addressSpaceSize)
  34. {
  35. asSize <<= 1;
  36. asBits++;
  37. }
  38. AddressSpaceBits = asBits;
  39. AddressSpaceSize = asSize;
  40. _backingMemory = backingMemory;
  41. _pageTable = new PageTable<nuint>();
  42. }
  43. /// <inheritdoc/>
  44. public void Map(ulong va, ulong pa, ulong size, MemoryMapFlags flags)
  45. {
  46. AssertValidAddressAndSize(va, size);
  47. while (size != 0)
  48. {
  49. _pageTable.Map(va, (nuint)(ulong)_backingMemory.GetPointer(pa, PageSize));
  50. va += PageSize;
  51. pa += PageSize;
  52. size -= PageSize;
  53. }
  54. }
  55. /// <inheritdoc/>
  56. public void MapForeign(ulong va, nuint hostPointer, ulong size)
  57. {
  58. AssertValidAddressAndSize(va, size);
  59. while (size != 0)
  60. {
  61. _pageTable.Map(va, hostPointer);
  62. va += PageSize;
  63. hostPointer += PageSize;
  64. size -= PageSize;
  65. }
  66. }
  67. /// <inheritdoc/>
  68. public void Unmap(ulong va, ulong size)
  69. {
  70. AssertValidAddressAndSize(va, size);
  71. while (size != 0)
  72. {
  73. _pageTable.Unmap(va);
  74. va += PageSize;
  75. size -= PageSize;
  76. }
  77. }
  78. /// <inheritdoc/>
  79. public T Read<T>(ulong va) where T : unmanaged
  80. {
  81. return MemoryMarshal.Cast<byte, T>(GetSpan(va, Unsafe.SizeOf<T>()))[0];
  82. }
  83. /// <inheritdoc/>
  84. public void Write<T>(ulong va, T value) where T : unmanaged
  85. {
  86. Write(va, MemoryMarshal.Cast<T, byte>(MemoryMarshal.CreateSpan(ref value, 1)));
  87. }
  88. /// <inheritdoc/>
  89. public void Write(ulong va, ReadOnlySpan<byte> data)
  90. {
  91. if (data.Length == 0)
  92. {
  93. return;
  94. }
  95. AssertValidAddressAndSize(va, (ulong)data.Length);
  96. if (IsContiguousAndMapped(va, data.Length))
  97. {
  98. data.CopyTo(GetHostSpanContiguous(va, data.Length));
  99. }
  100. else
  101. {
  102. int offset = 0, size;
  103. if ((va & PageMask) != 0)
  104. {
  105. size = Math.Min(data.Length, PageSize - (int)(va & PageMask));
  106. data[..size].CopyTo(GetHostSpanContiguous(va, size));
  107. offset += size;
  108. }
  109. for (; offset < data.Length; offset += size)
  110. {
  111. size = Math.Min(data.Length - offset, PageSize);
  112. data.Slice(offset, size).CopyTo(GetHostSpanContiguous(va + (ulong)offset, size));
  113. }
  114. }
  115. }
  116. /// <inheritdoc/>
  117. public bool WriteWithRedundancyCheck(ulong va, ReadOnlySpan<byte> data)
  118. {
  119. Write(va, data);
  120. return true;
  121. }
  122. /// <inheritdoc/>
  123. public ReadOnlySpan<byte> GetSpan(ulong va, int size, bool tracked = false)
  124. {
  125. if (size == 0)
  126. {
  127. return ReadOnlySpan<byte>.Empty;
  128. }
  129. if (IsContiguousAndMapped(va, size))
  130. {
  131. return GetHostSpanContiguous(va, size);
  132. }
  133. else
  134. {
  135. Span<byte> data = new byte[size];
  136. Read(va, data);
  137. return data;
  138. }
  139. }
  140. /// <inheritdoc/>
  141. public unsafe WritableRegion GetWritableRegion(ulong va, int size, bool tracked = false)
  142. {
  143. if (size == 0)
  144. {
  145. return new WritableRegion(null, va, Memory<byte>.Empty);
  146. }
  147. if (IsContiguousAndMapped(va, size))
  148. {
  149. return new WritableRegion(null, va, new NativeMemoryManager<byte>((byte*)GetHostAddress(va), size).Memory);
  150. }
  151. else
  152. {
  153. Memory<byte> memory = new byte[size];
  154. GetSpan(va, size).CopyTo(memory.Span);
  155. return new WritableRegion(this, va, memory);
  156. }
  157. }
  158. /// <inheritdoc/>
  159. public unsafe ref T GetRef<T>(ulong va) where T : unmanaged
  160. {
  161. if (!IsContiguous(va, Unsafe.SizeOf<T>()))
  162. {
  163. ThrowMemoryNotContiguous();
  164. }
  165. return ref *(T*)GetHostAddress(va);
  166. }
  167. /// <inheritdoc/>
  168. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  169. private static int GetPagesCount(ulong va, uint size, out ulong startVa)
  170. {
  171. // WARNING: Always check if ulong does not overflow during the operations.
  172. startVa = va & ~(ulong)PageMask;
  173. ulong vaSpan = (va - startVa + size + PageMask) & ~(ulong)PageMask;
  174. return (int)(vaSpan / PageSize);
  175. }
  176. private static void ThrowMemoryNotContiguous() => throw new MemoryNotContiguousException();
  177. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  178. private bool IsContiguousAndMapped(ulong va, int size) => IsContiguous(va, size) && IsMapped(va);
  179. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  180. private bool IsContiguous(ulong va, int size)
  181. {
  182. if (!ValidateAddress(va) || !ValidateAddressAndSize(va, (ulong)size))
  183. {
  184. return false;
  185. }
  186. int pages = GetPagesCount(va, (uint)size, out va);
  187. for (int page = 0; page < pages - 1; page++)
  188. {
  189. if (!ValidateAddress(va + PageSize))
  190. {
  191. return false;
  192. }
  193. if (GetHostAddress(va) + PageSize != GetHostAddress(va + PageSize))
  194. {
  195. return false;
  196. }
  197. va += PageSize;
  198. }
  199. return true;
  200. }
  201. /// <inheritdoc/>
  202. public IEnumerable<HostMemoryRange> GetHostRegions(ulong va, ulong size)
  203. {
  204. if (size == 0)
  205. {
  206. return Enumerable.Empty<HostMemoryRange>();
  207. }
  208. return GetHostRegionsImpl(va, size);
  209. }
  210. /// <inheritdoc/>
  211. public IEnumerable<MemoryRange> GetPhysicalRegions(ulong va, ulong size)
  212. {
  213. if (size == 0)
  214. {
  215. return Enumerable.Empty<MemoryRange>();
  216. }
  217. var hostRegions = GetHostRegionsImpl(va, size);
  218. if (hostRegions == null)
  219. {
  220. return null;
  221. }
  222. var regions = new MemoryRange[hostRegions.Count];
  223. ulong backingStart = (ulong)_backingMemory.Pointer;
  224. ulong backingEnd = backingStart + _backingMemory.Size;
  225. int count = 0;
  226. for (int i = 0; i < regions.Length; i++)
  227. {
  228. var hostRegion = hostRegions[i];
  229. if ((ulong)hostRegion.Address >= backingStart && (ulong)hostRegion.Address < backingEnd)
  230. {
  231. regions[count++] = new MemoryRange((ulong)hostRegion.Address - backingStart, hostRegion.Size);
  232. }
  233. }
  234. if (count != regions.Length)
  235. {
  236. return new ArraySegment<MemoryRange>(regions, 0, count);
  237. }
  238. return regions;
  239. }
  240. private List<HostMemoryRange> GetHostRegionsImpl(ulong va, ulong size)
  241. {
  242. if (!ValidateAddress(va) || !ValidateAddressAndSize(va, size))
  243. {
  244. return null;
  245. }
  246. int pages = GetPagesCount(va, (uint)size, out va);
  247. var regions = new List<HostMemoryRange>();
  248. nuint regionStart = GetHostAddress(va);
  249. ulong regionSize = PageSize;
  250. for (int page = 0; page < pages - 1; page++)
  251. {
  252. if (!ValidateAddress(va + PageSize))
  253. {
  254. return null;
  255. }
  256. nuint newHostAddress = GetHostAddress(va + PageSize);
  257. if (GetHostAddress(va) + PageSize != newHostAddress)
  258. {
  259. regions.Add(new HostMemoryRange(regionStart, regionSize));
  260. regionStart = newHostAddress;
  261. regionSize = 0;
  262. }
  263. va += PageSize;
  264. regionSize += PageSize;
  265. }
  266. regions.Add(new HostMemoryRange(regionStart, regionSize));
  267. return regions;
  268. }
  269. /// <inheritdoc/>
  270. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  271. public bool IsMapped(ulong va)
  272. {
  273. if (!ValidateAddress(va))
  274. {
  275. return false;
  276. }
  277. return _pageTable.Read(va) != 0;
  278. }
  279. /// <inheritdoc/>
  280. public bool IsRangeMapped(ulong va, ulong size)
  281. {
  282. if (size == 0UL)
  283. {
  284. return true;
  285. }
  286. if (!ValidateAddressAndSize(va, size))
  287. {
  288. return false;
  289. }
  290. int pages = GetPagesCount(va, (uint)size, out va);
  291. for (int page = 0; page < pages; page++)
  292. {
  293. if (!IsMapped(va))
  294. {
  295. return false;
  296. }
  297. va += PageSize;
  298. }
  299. return true;
  300. }
  301. private unsafe Span<byte> GetHostSpanContiguous(ulong va, int size)
  302. {
  303. return new Span<byte>((void*)GetHostAddress(va), size);
  304. }
  305. private nuint GetHostAddress(ulong va)
  306. {
  307. return _pageTable.Read(va) + (nuint)(va & PageMask);
  308. }
  309. /// <inheritdoc/>
  310. public void Reprotect(ulong va, ulong size, MemoryPermission protection)
  311. {
  312. }
  313. /// <inheritdoc/>
  314. public void TrackingReprotect(ulong va, ulong size, MemoryPermission protection)
  315. {
  316. throw new NotImplementedException();
  317. }
  318. /// <inheritdoc/>
  319. public void SignalMemoryTracking(ulong va, ulong size, bool write, bool precise = false, int? exemptId = null)
  320. {
  321. // Only the ARM Memory Manager has tracking for now.
  322. }
  323. protected override unsafe Span<byte> GetPhysicalAddressSpan(nuint pa, int size)
  324. => new((void*)pa, size);
  325. protected override nuint TranslateVirtualAddressForRead(ulong va)
  326. => GetHostAddress(va);
  327. }
  328. }