MemoryManager.cs 16 KB

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