MemoryManager.cs 17 KB

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