MemoryManager.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571
  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 = ulong.MaxValue;
  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="va">Start address of the range</param>
  130. /// <param name="size">Size in bytes to be range</param>
  131. /// <param name="tracked">True if write tracking is triggered on the span</param>
  132. /// <returns>A writable region with the data at the specified memory location</returns>
  133. public WritableRegion GetWritableRegion(ulong va, int size, bool tracked = false)
  134. {
  135. if (IsContiguous(va, size))
  136. {
  137. return Physical.GetWritableRegion(Translate(va), size, tracked);
  138. }
  139. else
  140. {
  141. Memory<byte> memory = new byte[size];
  142. GetSpan(va, size).CopyTo(memory.Span);
  143. return new WritableRegion(this, va, memory, tracked);
  144. }
  145. }
  146. /// <summary>
  147. /// Writes data to GPU mapped memory.
  148. /// </summary>
  149. /// <typeparam name="T">Type of the data</typeparam>
  150. /// <param name="va">GPU virtual address to write the value into</param>
  151. /// <param name="value">The value to be written</param>
  152. public void Write<T>(ulong va, T value) where T : unmanaged
  153. {
  154. Write(va, MemoryMarshal.Cast<T, byte>(MemoryMarshal.CreateSpan(ref value, 1)));
  155. }
  156. /// <summary>
  157. /// Writes data to GPU mapped memory.
  158. /// </summary>
  159. /// <param name="va">GPU virtual address to write the data into</param>
  160. /// <param name="data">The data to be written</param>
  161. public void Write(ulong va, ReadOnlySpan<byte> data)
  162. {
  163. WriteImpl(va, data, Physical.Write);
  164. }
  165. /// <summary>
  166. /// Writes data to GPU mapped memory, destined for a tracked resource.
  167. /// </summary>
  168. /// <param name="va">GPU virtual address to write the data into</param>
  169. /// <param name="data">The data to be written</param>
  170. public void WriteTrackedResource(ulong va, ReadOnlySpan<byte> data)
  171. {
  172. WriteImpl(va, data, Physical.WriteTrackedResource);
  173. }
  174. /// <summary>
  175. /// Writes data to GPU mapped memory without write tracking.
  176. /// </summary>
  177. /// <param name="va">GPU virtual address to write the data into</param>
  178. /// <param name="data">The data to be written</param>
  179. public void WriteUntracked(ulong va, ReadOnlySpan<byte> data)
  180. {
  181. WriteImpl(va, data, Physical.WriteUntracked);
  182. }
  183. private delegate void WriteCallback(ulong address, ReadOnlySpan<byte> data);
  184. /// <summary>
  185. /// Writes data to possibly non-contiguous GPU mapped memory.
  186. /// </summary>
  187. /// <param name="va">GPU virtual address of the region to write into</param>
  188. /// <param name="data">Data to be written</param>
  189. /// <param name="writeCallback">Write callback</param>
  190. private void WriteImpl(ulong va, ReadOnlySpan<byte> data, WriteCallback writeCallback)
  191. {
  192. if (IsContiguous(va, data.Length))
  193. {
  194. writeCallback(Translate(va), data);
  195. }
  196. else
  197. {
  198. int offset = 0, size;
  199. if ((va & PageMask) != 0)
  200. {
  201. ulong pa = Translate(va);
  202. size = Math.Min(data.Length, (int)PageSize - (int)(va & PageMask));
  203. writeCallback(pa, data.Slice(0, size));
  204. offset += size;
  205. }
  206. for (; offset < data.Length; offset += size)
  207. {
  208. ulong pa = Translate(va + (ulong)offset);
  209. size = Math.Min(data.Length - offset, (int)PageSize);
  210. writeCallback(pa, data.Slice(offset, size));
  211. }
  212. }
  213. }
  214. /// <summary>
  215. /// Maps a given range of pages to the specified CPU virtual address.
  216. /// </summary>
  217. /// <remarks>
  218. /// All addresses and sizes must be page aligned.
  219. /// </remarks>
  220. /// <param name="pa">CPU virtual address to map into</param>
  221. /// <param name="va">GPU virtual address to be mapped</param>
  222. /// <param name="size">Size in bytes of the mapping</param>
  223. /// <param name="kind">Kind of the resource located at the mapping</param>
  224. public void Map(ulong pa, ulong va, ulong size, PteKind kind)
  225. {
  226. lock (_pageTable)
  227. {
  228. MemoryUnmapped?.Invoke(this, new UnmapEventArgs(va, size));
  229. for (ulong offset = 0; offset < size; offset += PageSize)
  230. {
  231. SetPte(va + offset, PackPte(pa + offset, kind));
  232. }
  233. }
  234. }
  235. /// <summary>
  236. /// Unmaps a given range of pages at the specified GPU virtual memory region.
  237. /// </summary>
  238. /// <param name="va">GPU virtual address to unmap</param>
  239. /// <param name="size">Size in bytes of the region being unmapped</param>
  240. public void Unmap(ulong va, ulong size)
  241. {
  242. lock (_pageTable)
  243. {
  244. // Event handlers are not expected to be thread safe.
  245. MemoryUnmapped?.Invoke(this, new UnmapEventArgs(va, size));
  246. for (ulong offset = 0; offset < size; offset += PageSize)
  247. {
  248. SetPte(va + offset, PteUnmapped);
  249. }
  250. }
  251. }
  252. /// <summary>
  253. /// Checks if a region of GPU mapped memory is contiguous.
  254. /// </summary>
  255. /// <param name="va">GPU virtual address of the region</param>
  256. /// <param name="size">Size of the region</param>
  257. /// <returns>True if the region is contiguous, false otherwise</returns>
  258. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  259. private bool IsContiguous(ulong va, int size)
  260. {
  261. if (!ValidateAddress(va) || GetPte(va) == PteUnmapped)
  262. {
  263. return false;
  264. }
  265. ulong endVa = (va + (ulong)size + PageMask) & ~PageMask;
  266. va &= ~PageMask;
  267. int pages = (int)((endVa - va) / PageSize);
  268. for (int page = 0; page < pages - 1; page++)
  269. {
  270. if (!ValidateAddress(va + PageSize) || GetPte(va + PageSize) == PteUnmapped)
  271. {
  272. return false;
  273. }
  274. if (Translate(va) + PageSize != Translate(va + PageSize))
  275. {
  276. return false;
  277. }
  278. va += PageSize;
  279. }
  280. return true;
  281. }
  282. /// <summary>
  283. /// Gets the physical regions that make up the given virtual address region.
  284. /// </summary>
  285. /// <param name="va">Virtual address of the range</param>
  286. /// <param name="size">Size of the range</param>
  287. /// <returns>Multi-range with the physical regions</returns>
  288. public MultiRange GetPhysicalRegions(ulong va, ulong size)
  289. {
  290. if (IsContiguous(va, (int)size))
  291. {
  292. return new MultiRange(Translate(va), size);
  293. }
  294. ulong regionStart = Translate(va);
  295. ulong regionSize = Math.Min(size, PageSize - (va & PageMask));
  296. ulong endVa = va + size;
  297. ulong endVaRounded = (endVa + PageMask) & ~PageMask;
  298. va &= ~PageMask;
  299. int pages = (int)((endVaRounded - va) / PageSize);
  300. var regions = new List<MemoryRange>();
  301. for (int page = 0; page < pages - 1; page++)
  302. {
  303. ulong currPa = Translate(va);
  304. ulong newPa = Translate(va + PageSize);
  305. if ((currPa != PteUnmapped || newPa != PteUnmapped) && currPa + PageSize != newPa)
  306. {
  307. regions.Add(new MemoryRange(regionStart, regionSize));
  308. regionStart = newPa;
  309. regionSize = 0;
  310. }
  311. va += PageSize;
  312. regionSize += Math.Min(endVa - va, PageSize);
  313. }
  314. regions.Add(new MemoryRange(regionStart, regionSize));
  315. return new MultiRange(regions.ToArray());
  316. }
  317. /// <summary>
  318. /// Checks if a given GPU virtual memory range is mapped to the same physical regions
  319. /// as the specified physical memory multi-range.
  320. /// </summary>
  321. /// <param name="range">Physical memory multi-range</param>
  322. /// <param name="va">GPU virtual memory address</param>
  323. /// <returns>True if the virtual memory region is mapped into the specified physical one, false otherwise</returns>
  324. public bool CompareRange(MultiRange range, ulong va)
  325. {
  326. va &= ~PageMask;
  327. for (int i = 0; i < range.Count; i++)
  328. {
  329. MemoryRange currentRange = range.GetSubRange(i);
  330. if (currentRange.Address != PteUnmapped)
  331. {
  332. ulong address = currentRange.Address & ~PageMask;
  333. ulong endAddress = (currentRange.EndAddress + PageMask) & ~PageMask;
  334. while (address < endAddress)
  335. {
  336. if (Translate(va) != address)
  337. {
  338. return false;
  339. }
  340. va += PageSize;
  341. address += PageSize;
  342. }
  343. }
  344. else
  345. {
  346. ulong endVa = va + (((currentRange.Size) + PageMask) & ~PageMask);
  347. while (va < endVa)
  348. {
  349. if (Translate(va) != PteUnmapped)
  350. {
  351. return false;
  352. }
  353. va += PageSize;
  354. }
  355. }
  356. }
  357. return true;
  358. }
  359. /// <summary>
  360. /// Validates a GPU virtual address.
  361. /// </summary>
  362. /// <param name="va">Address to validate</param>
  363. /// <returns>True if the address is valid, false otherwise</returns>
  364. private static bool ValidateAddress(ulong va)
  365. {
  366. return va < (1UL << AddressSpaceBits);
  367. }
  368. /// <summary>
  369. /// Checks if a given page is mapped.
  370. /// </summary>
  371. /// <param name="va">GPU virtual address of the page to check</param>
  372. /// <returns>True if the page is mapped, false otherwise</returns>
  373. public bool IsMapped(ulong va)
  374. {
  375. return Translate(va) != PteUnmapped;
  376. }
  377. /// <summary>
  378. /// Translates a GPU virtual address to a CPU virtual address.
  379. /// </summary>
  380. /// <param name="va">GPU virtual address to be translated</param>
  381. /// <returns>CPU virtual address, or <see cref="PteUnmapped"/> if unmapped</returns>
  382. public ulong Translate(ulong va)
  383. {
  384. if (!ValidateAddress(va))
  385. {
  386. return PteUnmapped;
  387. }
  388. ulong pte = GetPte(va);
  389. if (pte == PteUnmapped)
  390. {
  391. return PteUnmapped;
  392. }
  393. return UnpackPaFromPte(pte) + (va & PageMask);
  394. }
  395. /// <summary>
  396. /// Gets the kind of a given memory page.
  397. /// This might indicate the type of resource that can be allocated on the page, and also texture tiling.
  398. /// </summary>
  399. /// <param name="va">GPU virtual address</param>
  400. /// <returns>Kind of the memory page</returns>
  401. public PteKind GetKind(ulong va)
  402. {
  403. if (!ValidateAddress(va))
  404. {
  405. return PteKind.Invalid;
  406. }
  407. ulong pte = GetPte(va);
  408. if (pte == PteUnmapped)
  409. {
  410. return PteKind.Invalid;
  411. }
  412. return UnpackKindFromPte(pte);
  413. }
  414. /// <summary>
  415. /// Gets the Page Table entry for a given GPU virtual address.
  416. /// </summary>
  417. /// <param name="va">GPU virtual address</param>
  418. /// <returns>Page table entry (CPU virtual address)</returns>
  419. private ulong GetPte(ulong va)
  420. {
  421. ulong l0 = (va >> PtLvl0Bit) & PtLvl0Mask;
  422. ulong l1 = (va >> PtLvl1Bit) & PtLvl1Mask;
  423. if (_pageTable[l0] == null)
  424. {
  425. return PteUnmapped;
  426. }
  427. return _pageTable[l0][l1];
  428. }
  429. /// <summary>
  430. /// Sets a Page Table entry at a given GPU virtual address.
  431. /// </summary>
  432. /// <param name="va">GPU virtual address</param>
  433. /// <param name="pte">Page table entry (CPU virtual address)</param>
  434. private void SetPte(ulong va, ulong pte)
  435. {
  436. ulong l0 = (va >> PtLvl0Bit) & PtLvl0Mask;
  437. ulong l1 = (va >> PtLvl1Bit) & PtLvl1Mask;
  438. if (_pageTable[l0] == null)
  439. {
  440. _pageTable[l0] = new ulong[PtLvl1Size];
  441. for (ulong index = 0; index < PtLvl1Size; index++)
  442. {
  443. _pageTable[l0][index] = PteUnmapped;
  444. }
  445. }
  446. _pageTable[l0][l1] = pte;
  447. }
  448. /// <summary>
  449. /// Creates a page table entry from a physical address and kind.
  450. /// </summary>
  451. /// <param name="pa">Physical address</param>
  452. /// <param name="kind">Kind</param>
  453. /// <returns>Page table entry</returns>
  454. private static ulong PackPte(ulong pa, PteKind kind)
  455. {
  456. return pa | ((ulong)kind << 56);
  457. }
  458. /// <summary>
  459. /// Unpacks kind from a page table entry.
  460. /// </summary>
  461. /// <param name="pte">Page table entry</param>
  462. /// <returns>Kind</returns>
  463. private static PteKind UnpackKindFromPte(ulong pte)
  464. {
  465. return (PteKind)(pte >> 56);
  466. }
  467. /// <summary>
  468. /// Unpacks physical address from a page table entry.
  469. /// </summary>
  470. /// <param name="pte">Page table entry</param>
  471. /// <returns>Physical address</returns>
  472. private static ulong UnpackPaFromPte(ulong pte)
  473. {
  474. return pte & 0xffffffffffffffUL;
  475. }
  476. }
  477. }