AddressSpaceManager.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415
  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 bool WriteWithRedundancyCheck(ulong va, ReadOnlySpan<byte> data)
  114. {
  115. Write(va, data);
  116. return true;
  117. }
  118. /// <inheritdoc/>
  119. public ReadOnlySpan<byte> GetSpan(ulong va, int size, bool tracked = false)
  120. {
  121. if (size == 0)
  122. {
  123. return ReadOnlySpan<byte>.Empty;
  124. }
  125. if (IsContiguousAndMapped(va, size))
  126. {
  127. return _backingMemory.GetSpan(GetPhysicalAddressInternal(va), size);
  128. }
  129. else
  130. {
  131. Span<byte> data = new byte[size];
  132. ReadImpl(va, data);
  133. return data;
  134. }
  135. }
  136. /// <inheritdoc/>
  137. public unsafe WritableRegion GetWritableRegion(ulong va, int size, bool tracked = false)
  138. {
  139. if (size == 0)
  140. {
  141. return new WritableRegion(null, va, Memory<byte>.Empty);
  142. }
  143. if (IsContiguousAndMapped(va, size))
  144. {
  145. return new WritableRegion(null, va, _backingMemory.GetMemory(GetPhysicalAddressInternal(va), size));
  146. }
  147. else
  148. {
  149. Memory<byte> memory = new byte[size];
  150. GetSpan(va, size).CopyTo(memory.Span);
  151. return new WritableRegion(this, va, memory);
  152. }
  153. }
  154. /// <inheritdoc/>
  155. public ref T GetRef<T>(ulong va) where T : unmanaged
  156. {
  157. if (!IsContiguous(va, Unsafe.SizeOf<T>()))
  158. {
  159. ThrowMemoryNotContiguous();
  160. }
  161. return ref _backingMemory.GetRef<T>(GetPhysicalAddressInternal(va));
  162. }
  163. /// <inheritdoc/>
  164. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  165. private int GetPagesCount(ulong va, uint size, out ulong startVa)
  166. {
  167. // WARNING: Always check if ulong does not overflow during the operations.
  168. startVa = va & ~(ulong)PageMask;
  169. ulong vaSpan = (va - startVa + size + PageMask) & ~(ulong)PageMask;
  170. return (int)(vaSpan / PageSize);
  171. }
  172. private static void ThrowMemoryNotContiguous() => throw new MemoryNotContiguousException();
  173. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  174. private bool IsContiguousAndMapped(ulong va, int size) => IsContiguous(va, size) && IsMapped(va);
  175. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  176. private bool IsContiguous(ulong va, int size)
  177. {
  178. if (!ValidateAddress(va) || !ValidateAddressAndSize(va, (ulong)size))
  179. {
  180. return false;
  181. }
  182. int pages = GetPagesCount(va, (uint)size, out va);
  183. for (int page = 0; page < pages - 1; page++)
  184. {
  185. if (!ValidateAddress(va + PageSize))
  186. {
  187. return false;
  188. }
  189. if (GetPhysicalAddressInternal(va) + PageSize != GetPhysicalAddressInternal(va + PageSize))
  190. {
  191. return false;
  192. }
  193. va += PageSize;
  194. }
  195. return true;
  196. }
  197. /// <inheritdoc/>
  198. public IEnumerable<MemoryRange> GetPhysicalRegions(ulong va, ulong size)
  199. {
  200. if (size == 0)
  201. {
  202. return Enumerable.Empty<MemoryRange>();
  203. }
  204. if (!ValidateAddress(va) || !ValidateAddressAndSize(va, size))
  205. {
  206. return null;
  207. }
  208. int pages = GetPagesCount(va, (uint)size, out va);
  209. var regions = new List<MemoryRange>();
  210. ulong regionStart = GetPhysicalAddressInternal(va);
  211. ulong regionSize = PageSize;
  212. for (int page = 0; page < pages - 1; page++)
  213. {
  214. if (!ValidateAddress(va + PageSize))
  215. {
  216. return null;
  217. }
  218. ulong newPa = GetPhysicalAddressInternal(va + PageSize);
  219. if (GetPhysicalAddressInternal(va) + PageSize != newPa)
  220. {
  221. regions.Add(new MemoryRange(regionStart, regionSize));
  222. regionStart = newPa;
  223. regionSize = 0;
  224. }
  225. va += PageSize;
  226. regionSize += PageSize;
  227. }
  228. regions.Add(new MemoryRange(regionStart, regionSize));
  229. return regions;
  230. }
  231. private void ReadImpl(ulong va, Span<byte> data)
  232. {
  233. if (data.Length == 0)
  234. {
  235. return;
  236. }
  237. AssertValidAddressAndSize(va, (ulong)data.Length);
  238. int offset = 0, size;
  239. if ((va & PageMask) != 0)
  240. {
  241. ulong pa = GetPhysicalAddressInternal(va);
  242. size = Math.Min(data.Length, PageSize - (int)(va & PageMask));
  243. _backingMemory.GetSpan(pa, size).CopyTo(data.Slice(0, size));
  244. offset += size;
  245. }
  246. for (; offset < data.Length; offset += size)
  247. {
  248. ulong pa = GetPhysicalAddressInternal(va + (ulong)offset);
  249. size = Math.Min(data.Length - offset, PageSize);
  250. _backingMemory.GetSpan(pa, size).CopyTo(data.Slice(offset, size));
  251. }
  252. }
  253. /// <inheritdoc/>
  254. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  255. public bool IsMapped(ulong va)
  256. {
  257. if (!ValidateAddress(va))
  258. {
  259. return false;
  260. }
  261. return _pageTable.Read(va) != 0;
  262. }
  263. /// <inheritdoc/>
  264. public bool IsRangeMapped(ulong va, ulong size)
  265. {
  266. if (size == 0UL)
  267. {
  268. return true;
  269. }
  270. if (!ValidateAddressAndSize(va, size))
  271. {
  272. return false;
  273. }
  274. int pages = GetPagesCount(va, (uint)size, out va);
  275. for (int page = 0; page < pages; page++)
  276. {
  277. if (!IsMapped(va))
  278. {
  279. return false;
  280. }
  281. va += PageSize;
  282. }
  283. return true;
  284. }
  285. private bool ValidateAddress(ulong va)
  286. {
  287. return va < _addressSpaceSize;
  288. }
  289. /// <summary>
  290. /// Checks if the combination of virtual address and size is part of the addressable space.
  291. /// </summary>
  292. /// <param name="va">Virtual address of the range</param>
  293. /// <param name="size">Size of the range in bytes</param>
  294. /// <returns>True if the combination of virtual address and size is part of the addressable space</returns>
  295. private bool ValidateAddressAndSize(ulong va, ulong size)
  296. {
  297. ulong endVa = va + size;
  298. return endVa >= va && endVa >= size && endVa <= _addressSpaceSize;
  299. }
  300. /// <summary>
  301. /// Ensures the combination of virtual address and size is part of the addressable space.
  302. /// </summary>
  303. /// <param name="va">Virtual address of the range</param>
  304. /// <param name="size">Size of the range in bytes</param>
  305. /// <exception cref="InvalidMemoryRegionException">Throw when the memory region specified outside the addressable space</exception>
  306. private void AssertValidAddressAndSize(ulong va, ulong size)
  307. {
  308. if (!ValidateAddressAndSize(va, size))
  309. {
  310. throw new InvalidMemoryRegionException($"va=0x{va:X16}, size=0x{size:X16}");
  311. }
  312. }
  313. private ulong GetPhysicalAddressInternal(ulong va)
  314. {
  315. return _pageTable.Read(va) + (va & PageMask);
  316. }
  317. /// <summary>
  318. /// Reprotect a region of virtual memory for tracking. Sets software protection bits.
  319. /// </summary>
  320. /// <param name="va">Virtual address base</param>
  321. /// <param name="size">Size of the region to protect</param>
  322. /// <param name="protection">Memory protection to set</param>
  323. public void TrackingReprotect(ulong va, ulong size, MemoryPermission protection)
  324. {
  325. throw new NotImplementedException();
  326. }
  327. public void SignalMemoryTracking(ulong va, ulong size, bool write, bool precise = false)
  328. {
  329. // Only the ARM Memory Manager has tracking for now.
  330. }
  331. }
  332. }