MemoryManager.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408
  1. using Ryujinx.Cpu;
  2. using System;
  3. using System.Runtime.CompilerServices;
  4. using System.Runtime.InteropServices;
  5. namespace Ryujinx.Graphics.Gpu.Memory
  6. {
  7. /// <summary>
  8. /// GPU memory manager.
  9. /// </summary>
  10. public class MemoryManager
  11. {
  12. private const ulong AddressSpaceSize = 1UL << 40;
  13. public const ulong BadAddress = ulong.MaxValue;
  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 ulong PteUnmapped = 0xffffffff_ffffffff;
  26. private const ulong PteReserved = 0xffffffff_fffffffe;
  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="gpuVa">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 gpuVa) where T : unmanaged
  45. {
  46. ulong processVa = Translate(gpuVa);
  47. return MemoryMarshal.Cast<byte, T>(_context.PhysicalMemory.GetSpan(processVa, Unsafe.SizeOf<T>()))[0];
  48. }
  49. /// <summary>
  50. /// Gets a read-only span of data from GPU mapped memory.
  51. /// </summary>
  52. /// <param name="gpuVa">GPU virtual address where the data is located</param>
  53. /// <param name="size">Size of the data</param>
  54. /// <returns>The span of the data at the specified memory location</returns>
  55. public ReadOnlySpan<byte> GetSpan(ulong gpuVa, int size)
  56. {
  57. ulong processVa = Translate(gpuVa);
  58. return _context.PhysicalMemory.GetSpan(processVa, size);
  59. }
  60. /// <summary>
  61. /// Gets a writable region from GPU mapped memory.
  62. /// </summary>
  63. /// <param name="address">Start address of the range</param>
  64. /// <param name="size">Size in bytes to be range</param>
  65. /// <returns>A writable region with the data at the specified memory location</returns>
  66. public WritableRegion GetWritableRegion(ulong gpuVa, int size)
  67. {
  68. ulong processVa = Translate(gpuVa);
  69. return _context.PhysicalMemory.GetWritableRegion(processVa, size);
  70. }
  71. /// <summary>
  72. /// Writes data to GPU mapped memory.
  73. /// </summary>
  74. /// <typeparam name="T">Type of the data</typeparam>
  75. /// <param name="gpuVa">GPU virtual address to write the value into</param>
  76. /// <param name="value">The value to be written</param>
  77. public void Write<T>(ulong gpuVa, T value) where T : unmanaged
  78. {
  79. ulong processVa = Translate(gpuVa);
  80. _context.PhysicalMemory.Write(processVa, MemoryMarshal.Cast<T, byte>(MemoryMarshal.CreateSpan(ref value, 1)));
  81. }
  82. /// <summary>
  83. /// Writes data to GPU mapped memory.
  84. /// </summary>
  85. /// <param name="gpuVa">GPU virtual address to write the data into</param>
  86. /// <param name="data">The data to be written</param>
  87. public void Write(ulong gpuVa, ReadOnlySpan<byte> data)
  88. {
  89. ulong processVa = Translate(gpuVa);
  90. _context.PhysicalMemory.Write(processVa, data);
  91. }
  92. /// <summary>
  93. /// Maps a given range of pages to the specified CPU virtual address.
  94. /// </summary>
  95. /// <remarks>
  96. /// All addresses and sizes must be page aligned.
  97. /// </remarks>
  98. /// <param name="pa">CPU virtual address to map into</param>
  99. /// <param name="va">GPU virtual address to be mapped</param>
  100. /// <param name="size">Size in bytes of the mapping</param>
  101. /// <returns>GPU virtual address of the mapping</returns>
  102. public ulong Map(ulong pa, ulong va, ulong size)
  103. {
  104. lock (_pageTable)
  105. {
  106. MemoryUnmapped?.Invoke(this, new UnmapEventArgs(va, size));
  107. for (ulong offset = 0; offset < size; offset += PageSize)
  108. {
  109. SetPte(va + offset, pa + offset);
  110. }
  111. }
  112. return va;
  113. }
  114. /// <summary>
  115. /// Maps a given range of pages to an allocated GPU virtual address.
  116. /// The memory is automatically allocated by the memory manager.
  117. /// </summary>
  118. /// <param name="pa">CPU virtual address to map into</param>
  119. /// <param name="size">Size in bytes of the mapping</param>
  120. /// <param name="alignment">Required alignment of the GPU virtual address in bytes</param>
  121. /// <returns>GPU virtual address where the range was mapped, or an all ones mask in case of failure</returns>
  122. public ulong MapAllocate(ulong pa, ulong size, ulong alignment)
  123. {
  124. lock (_pageTable)
  125. {
  126. ulong va = GetFreePosition(size, alignment);
  127. if (va != PteUnmapped)
  128. {
  129. for (ulong offset = 0; offset < size; offset += PageSize)
  130. {
  131. SetPte(va + offset, pa + offset);
  132. }
  133. }
  134. return va;
  135. }
  136. }
  137. /// <summary>
  138. /// Maps a given range of pages to an allocated GPU virtual address.
  139. /// The memory is automatically allocated by the memory manager.
  140. /// This also ensures that the mapping is always done in the first 4GB of GPU address space.
  141. /// </summary>
  142. /// <param name="pa">CPU virtual address to map into</param>
  143. /// <param name="size">Size in bytes of the mapping</param>
  144. /// <returns>GPU virtual address where the range was mapped, or an all ones mask in case of failure</returns>
  145. public ulong MapLow(ulong pa, ulong size)
  146. {
  147. lock (_pageTable)
  148. {
  149. ulong va = GetFreePosition(size, 1, PageSize);
  150. if (va != PteUnmapped && va <= uint.MaxValue && (va + size) <= uint.MaxValue)
  151. {
  152. for (ulong offset = 0; offset < size; offset += PageSize)
  153. {
  154. SetPte(va + offset, pa + offset);
  155. }
  156. }
  157. else
  158. {
  159. va = PteUnmapped;
  160. }
  161. return va;
  162. }
  163. }
  164. /// <summary>
  165. /// Reserves memory at a fixed GPU memory location.
  166. /// This prevents the reserved region from being used for memory allocation for map.
  167. /// </summary>
  168. /// <param name="va">GPU virtual address to reserve</param>
  169. /// <param name="size">Size in bytes of the reservation</param>
  170. /// <returns>GPU virtual address of the reservation, or an all ones mask in case of failure</returns>
  171. public ulong ReserveFixed(ulong va, ulong size)
  172. {
  173. lock (_pageTable)
  174. {
  175. MemoryUnmapped?.Invoke(this, new UnmapEventArgs(va, size));
  176. for (ulong offset = 0; offset < size; offset += PageSize)
  177. {
  178. if (IsPageInUse(va + offset))
  179. {
  180. return PteUnmapped;
  181. }
  182. }
  183. for (ulong offset = 0; offset < size; offset += PageSize)
  184. {
  185. SetPte(va + offset, PteReserved);
  186. }
  187. }
  188. return va;
  189. }
  190. /// <summary>
  191. /// Reserves memory at any GPU memory location.
  192. /// </summary>
  193. /// <param name="size">Size in bytes of the reservation</param>
  194. /// <param name="alignment">Reservation address alignment in bytes</param>
  195. /// <returns>GPU virtual address of the reservation, or an all ones mask in case of failure</returns>
  196. public ulong Reserve(ulong size, ulong alignment)
  197. {
  198. lock (_pageTable)
  199. {
  200. ulong address = GetFreePosition(size, alignment);
  201. if (address != PteUnmapped)
  202. {
  203. for (ulong offset = 0; offset < size; offset += PageSize)
  204. {
  205. SetPte(address + offset, PteReserved);
  206. }
  207. }
  208. return address;
  209. }
  210. }
  211. /// <summary>
  212. /// Frees memory that was previously allocated by a map or reserved.
  213. /// </summary>
  214. /// <param name="va">GPU virtual address to free</param>
  215. /// <param name="size">Size in bytes of the region being freed</param>
  216. public void Free(ulong va, ulong size)
  217. {
  218. lock (_pageTable)
  219. {
  220. // Event handlers are not expected to be thread safe.
  221. MemoryUnmapped?.Invoke(this, new UnmapEventArgs(va, size));
  222. for (ulong offset = 0; offset < size; offset += PageSize)
  223. {
  224. SetPte(va + offset, PteUnmapped);
  225. }
  226. }
  227. }
  228. /// <summary>
  229. /// Gets the address of an unused (free) region of the specified size.
  230. /// </summary>
  231. /// <param name="size">Size of the region in bytes</param>
  232. /// <param name="alignment">Required alignment of the region address in bytes</param>
  233. /// <param name="start">Start address of the search on the address space</param>
  234. /// <returns>GPU virtual address of the allocation, or an all ones mask in case of failure</returns>
  235. private ulong GetFreePosition(ulong size, ulong alignment = 1, ulong start = 1UL << 32)
  236. {
  237. // Note: Address 0 is not considered valid by the driver,
  238. // when 0 is returned it's considered a mapping error.
  239. ulong address = start;
  240. ulong freeSize = 0;
  241. if (alignment == 0)
  242. {
  243. alignment = 1;
  244. }
  245. alignment = (alignment + PageMask) & ~PageMask;
  246. while (address + freeSize < AddressSpaceSize)
  247. {
  248. if (!IsPageInUse(address + freeSize))
  249. {
  250. freeSize += PageSize;
  251. if (freeSize >= size)
  252. {
  253. return address;
  254. }
  255. }
  256. else
  257. {
  258. address += freeSize + PageSize;
  259. freeSize = 0;
  260. ulong remainder = address % alignment;
  261. if (remainder != 0)
  262. {
  263. address = (address - remainder) + alignment;
  264. }
  265. }
  266. }
  267. return PteUnmapped;
  268. }
  269. /// <summary>
  270. /// Checks if a given page is mapped.
  271. /// </summary>
  272. /// <param name="gpuVa">GPU virtual address of the page to check</param>
  273. /// <returns>True if the page is mapped, false otherwise</returns>
  274. public bool IsMapped(ulong gpuVa)
  275. {
  276. return Translate(gpuVa) != PteUnmapped;
  277. }
  278. /// <summary>
  279. /// Translates a GPU virtual address to a CPU virtual address.
  280. /// </summary>
  281. /// <param name="gpuVa">GPU virtual address to be translated</param>
  282. /// <returns>CPU virtual address</returns>
  283. public ulong Translate(ulong gpuVa)
  284. {
  285. ulong baseAddress = GetPte(gpuVa);
  286. if (baseAddress == PteUnmapped || baseAddress == PteReserved)
  287. {
  288. return PteUnmapped;
  289. }
  290. return baseAddress + (gpuVa & PageMask);
  291. }
  292. /// <summary>
  293. /// Checks if a given memory page is mapped or reserved.
  294. /// </summary>
  295. /// <param name="gpuVa">GPU virtual address of the page</param>
  296. /// <returns>True if the page is mapped or reserved, false otherwise</returns>
  297. private bool IsPageInUse(ulong gpuVa)
  298. {
  299. if (gpuVa >> PtLvl0Bits + PtLvl1Bits + PtPageBits != 0)
  300. {
  301. return false;
  302. }
  303. ulong l0 = (gpuVa >> PtLvl0Bit) & PtLvl0Mask;
  304. ulong l1 = (gpuVa >> PtLvl1Bit) & PtLvl1Mask;
  305. if (_pageTable[l0] == null)
  306. {
  307. return false;
  308. }
  309. return _pageTable[l0][l1] != PteUnmapped;
  310. }
  311. /// <summary>
  312. /// Gets the Page Table entry for a given GPU virtual address.
  313. /// </summary>
  314. /// <param name="gpuVa">GPU virtual address</param>
  315. /// <returns>Page table entry (CPU virtual address)</returns>
  316. private ulong GetPte(ulong gpuVa)
  317. {
  318. ulong l0 = (gpuVa >> PtLvl0Bit) & PtLvl0Mask;
  319. ulong l1 = (gpuVa >> PtLvl1Bit) & PtLvl1Mask;
  320. if (_pageTable[l0] == null)
  321. {
  322. return PteUnmapped;
  323. }
  324. return _pageTable[l0][l1];
  325. }
  326. /// <summary>
  327. /// Sets a Page Table entry at a given GPU virtual address.
  328. /// </summary>
  329. /// <param name="gpuVa">GPU virtual address</param>
  330. /// <param name="pte">Page table entry (CPU virtual address)</param>
  331. private void SetPte(ulong gpuVa, ulong pte)
  332. {
  333. ulong l0 = (gpuVa >> PtLvl0Bit) & PtLvl0Mask;
  334. ulong l1 = (gpuVa >> PtLvl1Bit) & PtLvl1Mask;
  335. if (_pageTable[l0] == null)
  336. {
  337. _pageTable[l0] = new ulong[PtLvl1Size];
  338. for (ulong index = 0; index < PtLvl1Size; index++)
  339. {
  340. _pageTable[l0][index] = PteUnmapped;
  341. }
  342. }
  343. _pageTable[l0][l1] = pte;
  344. }
  345. }
  346. }