MemoryManager.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508
  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, destined for a tracked resource.
  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 WriteTrackedResource(ulong va, ReadOnlySpan<byte> data)
  170. {
  171. WriteImpl(va, data, Physical.WriteTrackedResource);
  172. }
  173. /// <summary>
  174. /// Writes data to GPU mapped memory without write tracking.
  175. /// </summary>
  176. /// <param name="va">GPU virtual address to write the data into</param>
  177. /// <param name="data">The data to be written</param>
  178. public void WriteUntracked(ulong va, ReadOnlySpan<byte> data)
  179. {
  180. WriteImpl(va, data, Physical.WriteUntracked);
  181. }
  182. private delegate void WriteCallback(ulong address, ReadOnlySpan<byte> data);
  183. /// <summary>
  184. /// Writes data to possibly non-contiguous GPU mapped memory.
  185. /// </summary>
  186. /// <param name="va">GPU virtual address of the region to write into</param>
  187. /// <param name="data">Data to be written</param>
  188. /// <param name="writeCallback">Write callback</param>
  189. private void WriteImpl(ulong va, ReadOnlySpan<byte> data, WriteCallback writeCallback)
  190. {
  191. if (IsContiguous(va, data.Length))
  192. {
  193. writeCallback(Translate(va), data);
  194. }
  195. else
  196. {
  197. int offset = 0, size;
  198. if ((va & PageMask) != 0)
  199. {
  200. ulong pa = Translate(va);
  201. size = Math.Min(data.Length, (int)PageSize - (int)(va & PageMask));
  202. writeCallback(pa, data.Slice(0, size));
  203. offset += size;
  204. }
  205. for (; offset < data.Length; offset += size)
  206. {
  207. ulong pa = Translate(va + (ulong)offset);
  208. size = Math.Min(data.Length - offset, (int)PageSize);
  209. writeCallback(pa, data.Slice(offset, size));
  210. }
  211. }
  212. }
  213. /// <summary>
  214. /// Maps a given range of pages to the specified CPU virtual address.
  215. /// </summary>
  216. /// <remarks>
  217. /// All addresses and sizes must be page aligned.
  218. /// </remarks>
  219. /// <param name="pa">CPU virtual address to map into</param>
  220. /// <param name="va">GPU virtual address to be mapped</param>
  221. /// <param name="size">Size in bytes of the mapping</param>
  222. public void Map(ulong pa, ulong va, ulong size)
  223. {
  224. lock (_pageTable)
  225. {
  226. MemoryUnmapped?.Invoke(this, new UnmapEventArgs(va, size));
  227. for (ulong offset = 0; offset < size; offset += PageSize)
  228. {
  229. SetPte(va + offset, pa + offset);
  230. }
  231. }
  232. }
  233. /// <summary>
  234. /// Unmaps a given range of pages at the specified GPU virtual memory region.
  235. /// </summary>
  236. /// <param name="va">GPU virtual address to unmap</param>
  237. /// <param name="size">Size in bytes of the region being unmapped</param>
  238. public void Unmap(ulong va, ulong size)
  239. {
  240. lock (_pageTable)
  241. {
  242. // Event handlers are not expected to be thread safe.
  243. MemoryUnmapped?.Invoke(this, new UnmapEventArgs(va, size));
  244. for (ulong offset = 0; offset < size; offset += PageSize)
  245. {
  246. SetPte(va + offset, PteUnmapped);
  247. }
  248. }
  249. }
  250. /// <summary>
  251. /// Checks if a region of GPU mapped memory is contiguous.
  252. /// </summary>
  253. /// <param name="va">GPU virtual address of the region</param>
  254. /// <param name="size">Size of the region</param>
  255. /// <returns>True if the region is contiguous, false otherwise</returns>
  256. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  257. private bool IsContiguous(ulong va, int size)
  258. {
  259. if (!ValidateAddress(va) || GetPte(va) == PteUnmapped)
  260. {
  261. return false;
  262. }
  263. ulong endVa = (va + (ulong)size + PageMask) & ~PageMask;
  264. va &= ~PageMask;
  265. int pages = (int)((endVa - va) / PageSize);
  266. for (int page = 0; page < pages - 1; page++)
  267. {
  268. if (!ValidateAddress(va + PageSize) || GetPte(va + PageSize) == PteUnmapped)
  269. {
  270. return false;
  271. }
  272. if (Translate(va) + PageSize != Translate(va + PageSize))
  273. {
  274. return false;
  275. }
  276. va += PageSize;
  277. }
  278. return true;
  279. }
  280. /// <summary>
  281. /// Gets the physical regions that make up the given virtual address region.
  282. /// </summary>
  283. /// <param name="va">Virtual address of the range</param>
  284. /// <param name="size">Size of the range</param>
  285. /// <returns>Multi-range with the physical regions</returns>
  286. /// <exception cref="InvalidMemoryRegionException">The memory region specified by <paramref name="va"/> and <paramref name="size"/> is not fully mapped</exception>
  287. public MultiRange GetPhysicalRegions(ulong va, ulong size)
  288. {
  289. if (IsContiguous(va, (int)size))
  290. {
  291. return new MultiRange(Translate(va), size);
  292. }
  293. if (!IsMapped(va))
  294. {
  295. throw new InvalidMemoryRegionException($"The specified GPU virtual address 0x{va:X} is not mapped.");
  296. }
  297. ulong regionStart = Translate(va);
  298. ulong regionSize = Math.Min(size, PageSize - (va & PageMask));
  299. ulong endVa = va + size;
  300. ulong endVaRounded = (endVa + PageMask) & ~PageMask;
  301. va &= ~PageMask;
  302. int pages = (int)((endVaRounded - va) / PageSize);
  303. var regions = new List<MemoryRange>();
  304. for (int page = 0; page < pages - 1; page++)
  305. {
  306. if (!IsMapped(va + PageSize))
  307. {
  308. throw new InvalidMemoryRegionException($"The specified GPU virtual memory range 0x{va:X}..0x{(va + size):X} is not fully mapped.");
  309. }
  310. ulong newPa = Translate(va + PageSize);
  311. if (Translate(va) + PageSize != newPa)
  312. {
  313. regions.Add(new MemoryRange(regionStart, regionSize));
  314. regionStart = newPa;
  315. regionSize = 0;
  316. }
  317. va += PageSize;
  318. regionSize += Math.Min(endVa - va, PageSize);
  319. }
  320. regions.Add(new MemoryRange(regionStart, regionSize));
  321. return new MultiRange(regions.ToArray());
  322. }
  323. /// <summary>
  324. /// Checks if a given GPU virtual memory range is mapped to the same physical regions
  325. /// as the specified physical memory multi-range.
  326. /// </summary>
  327. /// <param name="range">Physical memory multi-range</param>
  328. /// <param name="va">GPU virtual memory address</param>
  329. /// <returns>True if the virtual memory region is mapped into the specified physical one, false otherwise</returns>
  330. public bool CompareRange(MultiRange range, ulong va)
  331. {
  332. va &= ~PageMask;
  333. for (int i = 0; i < range.Count; i++)
  334. {
  335. MemoryRange currentRange = range.GetSubRange(i);
  336. ulong address = currentRange.Address & ~PageMask;
  337. ulong endAddress = (currentRange.EndAddress + PageMask) & ~PageMask;
  338. while (address < endAddress)
  339. {
  340. if (Translate(va) != address)
  341. {
  342. return false;
  343. }
  344. va += PageSize;
  345. address += PageSize;
  346. }
  347. }
  348. return true;
  349. }
  350. /// <summary>
  351. /// Validates a GPU virtual address.
  352. /// </summary>
  353. /// <param name="va">Address to validate</param>
  354. /// <returns>True if the address is valid, false otherwise</returns>
  355. private static bool ValidateAddress(ulong va)
  356. {
  357. return va < (1UL << AddressSpaceBits);
  358. }
  359. /// <summary>
  360. /// Checks if a given page is mapped.
  361. /// </summary>
  362. /// <param name="va">GPU virtual address of the page to check</param>
  363. /// <returns>True if the page is mapped, false otherwise</returns>
  364. public bool IsMapped(ulong va)
  365. {
  366. return Translate(va) != PteUnmapped;
  367. }
  368. /// <summary>
  369. /// Translates a GPU virtual address to a CPU virtual address.
  370. /// </summary>
  371. /// <param name="va">GPU virtual address to be translated</param>
  372. /// <returns>CPU virtual address, or <see cref="PteUnmapped"/> if unmapped</returns>
  373. public ulong Translate(ulong va)
  374. {
  375. if (!ValidateAddress(va))
  376. {
  377. return PteUnmapped;
  378. }
  379. ulong baseAddress = GetPte(va);
  380. if (baseAddress == PteUnmapped)
  381. {
  382. return PteUnmapped;
  383. }
  384. return baseAddress + (va & PageMask);
  385. }
  386. /// <summary>
  387. /// Gets the Page Table entry for a given GPU virtual address.
  388. /// </summary>
  389. /// <param name="va">GPU virtual address</param>
  390. /// <returns>Page table entry (CPU virtual address)</returns>
  391. private ulong GetPte(ulong va)
  392. {
  393. ulong l0 = (va >> PtLvl0Bit) & PtLvl0Mask;
  394. ulong l1 = (va >> PtLvl1Bit) & PtLvl1Mask;
  395. if (_pageTable[l0] == null)
  396. {
  397. return PteUnmapped;
  398. }
  399. return _pageTable[l0][l1];
  400. }
  401. /// <summary>
  402. /// Sets a Page Table entry at a given GPU virtual address.
  403. /// </summary>
  404. /// <param name="va">GPU virtual address</param>
  405. /// <param name="pte">Page table entry (CPU virtual address)</param>
  406. private void SetPte(ulong va, ulong pte)
  407. {
  408. ulong l0 = (va >> PtLvl0Bit) & PtLvl0Mask;
  409. ulong l1 = (va >> PtLvl1Bit) & PtLvl1Mask;
  410. if (_pageTable[l0] == null)
  411. {
  412. _pageTable[l0] = new ulong[PtLvl1Size];
  413. for (ulong index = 0; index < PtLvl1Size; index++)
  414. {
  415. _pageTable[l0][index] = PteUnmapped;
  416. }
  417. }
  418. _pageTable[l0][l1] = pte;
  419. }
  420. }
  421. }