AddressSpaceManager.cs 12 KB

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