MemoryManager.cs 15 KB

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