MemoryManager.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428
  1. using Ryujinx.Memory;
  2. using Ryujinx.Memory.Range;
  3. using System;
  4. using System.Collections.Generic;
  5. using System.Runtime.CompilerServices;
  6. using System.Runtime.InteropServices;
  7. namespace Ryujinx.Graphics.Gpu.Memory
  8. {
  9. /// <summary>
  10. /// GPU memory manager.
  11. /// </summary>
  12. public class MemoryManager : IWritableBlock
  13. {
  14. private const int PtLvl0Bits = 14;
  15. private const int PtLvl1Bits = 14;
  16. public const int PtPageBits = 12;
  17. private const ulong PtLvl0Size = 1UL << PtLvl0Bits;
  18. private const ulong PtLvl1Size = 1UL << PtLvl1Bits;
  19. public const ulong PageSize = 1UL << PtPageBits;
  20. private const ulong PtLvl0Mask = PtLvl0Size - 1;
  21. private const ulong PtLvl1Mask = PtLvl1Size - 1;
  22. public const ulong PageMask = PageSize - 1;
  23. private const int PtLvl0Bit = PtPageBits + PtLvl1Bits;
  24. private const int PtLvl1Bit = PtPageBits;
  25. private const int AddressSpaceBits = PtPageBits + PtLvl1Bits + PtLvl0Bits;
  26. public const ulong PteUnmapped = 0xffffffff_ffffffff;
  27. private readonly ulong[][] _pageTable;
  28. public event EventHandler<UnmapEventArgs> MemoryUnmapped;
  29. private GpuContext _context;
  30. /// <summary>
  31. /// Creates a new instance of the GPU memory manager.
  32. /// </summary>
  33. public MemoryManager(GpuContext context)
  34. {
  35. _context = context;
  36. _pageTable = new ulong[PtLvl0Size][];
  37. }
  38. /// <summary>
  39. /// Reads data from GPU mapped memory.
  40. /// </summary>
  41. /// <typeparam name="T">Type of the data</typeparam>
  42. /// <param name="va">GPU virtual address where the data is located</param>
  43. /// <returns>The data at the specified memory location</returns>
  44. public T Read<T>(ulong va) where T : unmanaged
  45. {
  46. return MemoryMarshal.Cast<byte, T>(GetSpan(va, Unsafe.SizeOf<T>()))[0];
  47. }
  48. /// <summary>
  49. /// Gets a read-only span of data from GPU mapped memory.
  50. /// </summary>
  51. /// <param name="va">GPU virtual address where the data is located</param>
  52. /// <param name="size">Size of the data</param>
  53. /// <returns>The span of the data at the specified memory location</returns>
  54. public ReadOnlySpan<byte> GetSpan(ulong va, int size, bool tracked = false)
  55. {
  56. if (IsContiguous(va, size))
  57. {
  58. return _context.PhysicalMemory.GetSpan(Translate(va), size, tracked);
  59. }
  60. else
  61. {
  62. Span<byte> data = new byte[size];
  63. ReadImpl(va, data, tracked);
  64. return data;
  65. }
  66. }
  67. /// <summary>
  68. /// Reads data from a possibly non-contiguous region of GPU mapped memory.
  69. /// </summary>
  70. /// <param name="va">GPU virtual address of the data</param>
  71. /// <param name="data">Span to write the read data into</param>
  72. /// <param name="tracked">True to enable write tracking on read, false otherwise</param>
  73. private void ReadImpl(ulong va, Span<byte> data, bool tracked)
  74. {
  75. if (data.Length == 0)
  76. {
  77. return;
  78. }
  79. int offset = 0, size;
  80. if ((va & PageMask) != 0)
  81. {
  82. ulong pa = Translate(va);
  83. size = Math.Min(data.Length, (int)PageSize - (int)(va & PageMask));
  84. _context.PhysicalMemory.GetSpan(pa, size, tracked).CopyTo(data.Slice(0, size));
  85. offset += size;
  86. }
  87. for (; offset < data.Length; offset += size)
  88. {
  89. ulong pa = Translate(va + (ulong)offset);
  90. size = Math.Min(data.Length - offset, (int)PageSize);
  91. _context.PhysicalMemory.GetSpan(pa, size, tracked).CopyTo(data.Slice(offset, size));
  92. }
  93. }
  94. /// <summary>
  95. /// Gets a writable region from GPU mapped memory.
  96. /// </summary>
  97. /// <param name="address">Start address of the range</param>
  98. /// <param name="size">Size in bytes to be range</param>
  99. /// <returns>A writable region with the data at the specified memory location</returns>
  100. public WritableRegion GetWritableRegion(ulong va, int size)
  101. {
  102. if (IsContiguous(va, size))
  103. {
  104. return _context.PhysicalMemory.GetWritableRegion(Translate(va), size);
  105. }
  106. else
  107. {
  108. Memory<byte> memory = new byte[size];
  109. GetSpan(va, size).CopyTo(memory.Span);
  110. return new WritableRegion(this, va, memory);
  111. }
  112. }
  113. /// <summary>
  114. /// Writes data to GPU mapped memory.
  115. /// </summary>
  116. /// <typeparam name="T">Type of the data</typeparam>
  117. /// <param name="va">GPU virtual address to write the value into</param>
  118. /// <param name="value">The value to be written</param>
  119. public void Write<T>(ulong va, T value) where T : unmanaged
  120. {
  121. Write(va, MemoryMarshal.Cast<T, byte>(MemoryMarshal.CreateSpan(ref value, 1)));
  122. }
  123. /// <summary>
  124. /// Writes data to GPU mapped memory.
  125. /// </summary>
  126. /// <param name="va">GPU virtual address to write the data into</param>
  127. /// <param name="data">The data to be written</param>
  128. public void Write(ulong va, ReadOnlySpan<byte> data)
  129. {
  130. WriteImpl(va, data, _context.PhysicalMemory.Write);
  131. }
  132. /// <summary>
  133. /// Writes data to GPU mapped memory without write tracking.
  134. /// </summary>
  135. /// <param name="va">GPU virtual address to write the data into</param>
  136. /// <param name="data">The data to be written</param>
  137. public void WriteUntracked(ulong va, ReadOnlySpan<byte> data)
  138. {
  139. WriteImpl(va, data, _context.PhysicalMemory.WriteUntracked);
  140. }
  141. private delegate void WriteCallback(ulong address, ReadOnlySpan<byte> data);
  142. /// <summary>
  143. /// Writes data to possibly non-contiguous GPU mapped memory.
  144. /// </summary>
  145. /// <param name="va">GPU virtual address of the region to write into</param>
  146. /// <param name="data">Data to be written</param>
  147. /// <param name="writeCallback">Write callback</param>
  148. private void WriteImpl(ulong va, ReadOnlySpan<byte> data, WriteCallback writeCallback)
  149. {
  150. if (IsContiguous(va, data.Length))
  151. {
  152. writeCallback(Translate(va), data);
  153. }
  154. else
  155. {
  156. int offset = 0, size;
  157. if ((va & PageMask) != 0)
  158. {
  159. ulong pa = Translate(va);
  160. size = Math.Min(data.Length, (int)PageSize - (int)(va & PageMask));
  161. writeCallback(pa, data.Slice(0, size));
  162. offset += size;
  163. }
  164. for (; offset < data.Length; offset += size)
  165. {
  166. ulong pa = Translate(va + (ulong)offset);
  167. size = Math.Min(data.Length - offset, (int)PageSize);
  168. writeCallback(pa, data.Slice(offset, size));
  169. }
  170. }
  171. }
  172. /// <summary>
  173. /// Maps a given range of pages to the specified CPU virtual address.
  174. /// </summary>
  175. /// <remarks>
  176. /// All addresses and sizes must be page aligned.
  177. /// </remarks>
  178. /// <param name="pa">CPU virtual address to map into</param>
  179. /// <param name="va">GPU virtual address to be mapped</param>
  180. /// <param name="size">Size in bytes of the mapping</param>
  181. public void Map(ulong pa, ulong va, ulong size)
  182. {
  183. lock (_pageTable)
  184. {
  185. MemoryUnmapped?.Invoke(this, new UnmapEventArgs(va, size));
  186. for (ulong offset = 0; offset < size; offset += PageSize)
  187. {
  188. SetPte(va + offset, pa + offset);
  189. }
  190. }
  191. }
  192. /// <summary>
  193. /// Unmaps a given range of pages at the specified GPU virtual memory region.
  194. /// </summary>
  195. /// <param name="va">GPU virtual address to unmap</param>
  196. /// <param name="size">Size in bytes of the region being unmapped</param>
  197. public void Unmap(ulong va, ulong size)
  198. {
  199. lock (_pageTable)
  200. {
  201. // Event handlers are not expected to be thread safe.
  202. MemoryUnmapped?.Invoke(this, new UnmapEventArgs(va, size));
  203. for (ulong offset = 0; offset < size; offset += PageSize)
  204. {
  205. SetPte(va + offset, PteUnmapped);
  206. }
  207. }
  208. }
  209. /// <summary>
  210. /// Checks if a region of GPU mapped memory is contiguous.
  211. /// </summary>
  212. /// <param name="va">GPU virtual address of the region</param>
  213. /// <param name="size">Size of the region</param>
  214. /// <returns>True if the region is contiguous, false otherwise</returns>
  215. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  216. private bool IsContiguous(ulong va, int size)
  217. {
  218. if (!ValidateAddress(va) || GetPte(va) == PteUnmapped)
  219. {
  220. return false;
  221. }
  222. ulong endVa = (va + (ulong)size + PageMask) & ~PageMask;
  223. va &= ~PageMask;
  224. int pages = (int)((endVa - va) / PageSize);
  225. for (int page = 0; page < pages - 1; page++)
  226. {
  227. if (!ValidateAddress(va + PageSize) || GetPte(va + PageSize) == PteUnmapped)
  228. {
  229. return false;
  230. }
  231. if (Translate(va) + PageSize != Translate(va + PageSize))
  232. {
  233. return false;
  234. }
  235. va += PageSize;
  236. }
  237. return true;
  238. }
  239. /// <summary>
  240. /// Gets the physical regions that make up the given virtual address region.
  241. /// </summary>
  242. /// <param name="va">Virtual address of the range</param>
  243. /// <param name="size">Size of the range</param>
  244. /// <returns>Multi-range with the physical regions</returns>
  245. /// <exception cref="InvalidMemoryRegionException">The memory region specified by <paramref name="va"/> and <paramref name="size"/> is not fully mapped</exception>
  246. public MultiRange GetPhysicalRegions(ulong va, ulong size)
  247. {
  248. if (IsContiguous(va, (int)size))
  249. {
  250. return new MultiRange(Translate(va), size);
  251. }
  252. if (!IsMapped(va))
  253. {
  254. throw new InvalidMemoryRegionException($"The specified GPU virtual address 0x{va:X} is not mapped.");
  255. }
  256. ulong regionStart = Translate(va);
  257. ulong regionSize = Math.Min(size, PageSize - (va & PageMask));
  258. ulong endVa = va + size;
  259. ulong endVaRounded = (endVa + PageMask) & ~PageMask;
  260. va &= ~PageMask;
  261. int pages = (int)((endVaRounded - va) / PageSize);
  262. var regions = new List<MemoryRange>();
  263. for (int page = 0; page < pages - 1; page++)
  264. {
  265. if (!IsMapped(va + PageSize))
  266. {
  267. throw new InvalidMemoryRegionException($"The specified GPU virtual memory range 0x{va:X}..0x{(va + size):X} is not fully mapped.");
  268. }
  269. ulong newPa = Translate(va + PageSize);
  270. if (Translate(va) + PageSize != newPa)
  271. {
  272. regions.Add(new MemoryRange(regionStart, regionSize));
  273. regionStart = newPa;
  274. regionSize = 0;
  275. }
  276. va += PageSize;
  277. regionSize += Math.Min(endVa - va, PageSize);
  278. }
  279. regions.Add(new MemoryRange(regionStart, regionSize));
  280. return new MultiRange(regions.ToArray());
  281. }
  282. /// <summary>
  283. /// Validates a GPU virtual address.
  284. /// </summary>
  285. /// <param name="va">Address to validate</param>
  286. /// <returns>True if the address is valid, false otherwise</returns>
  287. private static bool ValidateAddress(ulong va)
  288. {
  289. return va < (1UL << AddressSpaceBits);
  290. }
  291. /// <summary>
  292. /// Checks if a given page is mapped.
  293. /// </summary>
  294. /// <param name="va">GPU virtual address of the page to check</param>
  295. /// <returns>True if the page is mapped, false otherwise</returns>
  296. public bool IsMapped(ulong va)
  297. {
  298. return Translate(va) != PteUnmapped;
  299. }
  300. /// <summary>
  301. /// Translates a GPU virtual address to a CPU virtual address.
  302. /// </summary>
  303. /// <param name="va">GPU virtual address to be translated</param>
  304. /// <returns>CPU virtual address, or <see cref="PteUnmapped"/> if unmapped</returns>
  305. public ulong Translate(ulong va)
  306. {
  307. if (!ValidateAddress(va))
  308. {
  309. return PteUnmapped;
  310. }
  311. ulong baseAddress = GetPte(va);
  312. if (baseAddress == PteUnmapped)
  313. {
  314. return PteUnmapped;
  315. }
  316. return baseAddress + (va & PageMask);
  317. }
  318. /// <summary>
  319. /// Gets the Page Table entry for a given GPU virtual address.
  320. /// </summary>
  321. /// <param name="va">GPU virtual address</param>
  322. /// <returns>Page table entry (CPU virtual address)</returns>
  323. private ulong GetPte(ulong va)
  324. {
  325. ulong l0 = (va >> PtLvl0Bit) & PtLvl0Mask;
  326. ulong l1 = (va >> PtLvl1Bit) & PtLvl1Mask;
  327. if (_pageTable[l0] == null)
  328. {
  329. return PteUnmapped;
  330. }
  331. return _pageTable[l0][l1];
  332. }
  333. /// <summary>
  334. /// Sets a Page Table entry at a given GPU virtual address.
  335. /// </summary>
  336. /// <param name="va">GPU virtual address</param>
  337. /// <param name="pte">Page table entry (CPU virtual address)</param>
  338. private void SetPte(ulong va, ulong pte)
  339. {
  340. ulong l0 = (va >> PtLvl0Bit) & PtLvl0Mask;
  341. ulong l1 = (va >> PtLvl1Bit) & PtLvl1Mask;
  342. if (_pageTable[l0] == null)
  343. {
  344. _pageTable[l0] = new ulong[PtLvl1Size];
  345. for (ulong index = 0; index < PtLvl1Size; index++)
  346. {
  347. _pageTable[l0][index] = PteUnmapped;
  348. }
  349. }
  350. _pageTable[l0][l1] = pte;
  351. }
  352. }
  353. }