MemoryManager.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394
  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. for (ulong offset = 0; offset < size; offset += PageSize)
  107. {
  108. SetPte(va + offset, pa + offset);
  109. }
  110. }
  111. return va;
  112. }
  113. /// <summary>
  114. /// Maps a given range of pages to an allocated GPU virtual address.
  115. /// The memory is automatically allocated by the memory manager.
  116. /// </summary>
  117. /// <param name="pa">CPU virtual address to map into</param>
  118. /// <param name="size">Size in bytes of the mapping</param>
  119. /// <param name="alignment">Required alignment of the GPU virtual address in bytes</param>
  120. /// <returns>GPU virtual address where the range was mapped, or an all ones mask in case of failure</returns>
  121. public ulong MapAllocate(ulong pa, ulong size, ulong alignment)
  122. {
  123. lock (_pageTable)
  124. {
  125. ulong va = GetFreePosition(size, alignment);
  126. if (va != PteUnmapped)
  127. {
  128. for (ulong offset = 0; offset < size; offset += PageSize)
  129. {
  130. SetPte(va + offset, pa + offset);
  131. }
  132. }
  133. return va;
  134. }
  135. }
  136. /// <summary>
  137. /// Maps a given range of pages to an allocated GPU virtual address.
  138. /// The memory is automatically allocated by the memory manager.
  139. /// This also ensures that the mapping is always done in the first 4GB of GPU address space.
  140. /// </summary>
  141. /// <param name="pa">CPU virtual address to map into</param>
  142. /// <param name="size">Size in bytes of the mapping</param>
  143. /// <returns>GPU virtual address where the range was mapped, or an all ones mask in case of failure</returns>
  144. public ulong MapLow(ulong pa, ulong size)
  145. {
  146. lock (_pageTable)
  147. {
  148. ulong va = GetFreePosition(size, 1, PageSize);
  149. if (va != PteUnmapped && va <= uint.MaxValue && (va + size) <= uint.MaxValue)
  150. {
  151. for (ulong offset = 0; offset < size; offset += PageSize)
  152. {
  153. SetPte(va + offset, pa + offset);
  154. }
  155. }
  156. else
  157. {
  158. va = PteUnmapped;
  159. }
  160. return va;
  161. }
  162. }
  163. /// <summary>
  164. /// Reserves memory at a fixed GPU memory location.
  165. /// This prevents the reserved region from being used for memory allocation for map.
  166. /// </summary>
  167. /// <param name="va">GPU virtual address to reserve</param>
  168. /// <param name="size">Size in bytes of the reservation</param>
  169. /// <returns>GPU virtual address of the reservation, or an all ones mask in case of failure</returns>
  170. public ulong ReserveFixed(ulong va, ulong size)
  171. {
  172. lock (_pageTable)
  173. {
  174. for (ulong offset = 0; offset < size; offset += PageSize)
  175. {
  176. if (IsPageInUse(va + offset))
  177. {
  178. return PteUnmapped;
  179. }
  180. }
  181. for (ulong offset = 0; offset < size; offset += PageSize)
  182. {
  183. SetPte(va + offset, PteReserved);
  184. }
  185. }
  186. return va;
  187. }
  188. /// <summary>
  189. /// Reserves memory at any GPU memory location.
  190. /// </summary>
  191. /// <param name="size">Size in bytes of the reservation</param>
  192. /// <param name="alignment">Reservation address alignment in bytes</param>
  193. /// <returns>GPU virtual address of the reservation, or an all ones mask in case of failure</returns>
  194. public ulong Reserve(ulong size, ulong alignment)
  195. {
  196. lock (_pageTable)
  197. {
  198. ulong address = GetFreePosition(size, alignment);
  199. if (address != PteUnmapped)
  200. {
  201. for (ulong offset = 0; offset < size; offset += PageSize)
  202. {
  203. SetPte(address + offset, PteReserved);
  204. }
  205. }
  206. return address;
  207. }
  208. }
  209. /// <summary>
  210. /// Frees memory that was previously allocated by a map or reserved.
  211. /// </summary>
  212. /// <param name="va">GPU virtual address to free</param>
  213. /// <param name="size">Size in bytes of the region being freed</param>
  214. public void Free(ulong va, ulong size)
  215. {
  216. lock (_pageTable)
  217. {
  218. // Event handlers are not expected to be thread safe.
  219. MemoryUnmapped?.Invoke(this, new UnmapEventArgs(va, size));
  220. for (ulong offset = 0; offset < size; offset += PageSize)
  221. {
  222. SetPte(va + offset, PteUnmapped);
  223. }
  224. }
  225. }
  226. /// <summary>
  227. /// Gets the address of an unused (free) region of the specified size.
  228. /// </summary>
  229. /// <param name="size">Size of the region in bytes</param>
  230. /// <param name="alignment">Required alignment of the region address in bytes</param>
  231. /// <param name="start">Start address of the search on the address space</param>
  232. /// <returns>GPU virtual address of the allocation, or an all ones mask in case of failure</returns>
  233. private ulong GetFreePosition(ulong size, ulong alignment = 1, ulong start = 1UL << 32)
  234. {
  235. // Note: Address 0 is not considered valid by the driver,
  236. // when 0 is returned it's considered a mapping error.
  237. ulong address = start;
  238. ulong freeSize = 0;
  239. if (alignment == 0)
  240. {
  241. alignment = 1;
  242. }
  243. alignment = (alignment + PageMask) & ~PageMask;
  244. while (address + freeSize < AddressSpaceSize)
  245. {
  246. if (!IsPageInUse(address + freeSize))
  247. {
  248. freeSize += PageSize;
  249. if (freeSize >= size)
  250. {
  251. return address;
  252. }
  253. }
  254. else
  255. {
  256. address += freeSize + PageSize;
  257. freeSize = 0;
  258. ulong remainder = address % alignment;
  259. if (remainder != 0)
  260. {
  261. address = (address - remainder) + alignment;
  262. }
  263. }
  264. }
  265. return PteUnmapped;
  266. }
  267. /// <summary>
  268. /// Translates a GPU virtual address to a CPU virtual address.
  269. /// </summary>
  270. /// <param name="gpuVa">GPU virtual address to be translated</param>
  271. /// <returns>CPU virtual address</returns>
  272. public ulong Translate(ulong gpuVa)
  273. {
  274. ulong baseAddress = GetPte(gpuVa);
  275. if (baseAddress == PteUnmapped || baseAddress == PteReserved)
  276. {
  277. return PteUnmapped;
  278. }
  279. return baseAddress + (gpuVa & PageMask);
  280. }
  281. /// <summary>
  282. /// Checks if a given memory page is mapped or reserved.
  283. /// </summary>
  284. /// <param name="gpuVa">GPU virtual address of the page</param>
  285. /// <returns>True if the page is mapped or reserved, false otherwise</returns>
  286. private bool IsPageInUse(ulong gpuVa)
  287. {
  288. if (gpuVa >> PtLvl0Bits + PtLvl1Bits + PtPageBits != 0)
  289. {
  290. return false;
  291. }
  292. ulong l0 = (gpuVa >> PtLvl0Bit) & PtLvl0Mask;
  293. ulong l1 = (gpuVa >> PtLvl1Bit) & PtLvl1Mask;
  294. if (_pageTable[l0] == null)
  295. {
  296. return false;
  297. }
  298. return _pageTable[l0][l1] != PteUnmapped;
  299. }
  300. /// <summary>
  301. /// Gets the Page Table entry for a given GPU virtual address.
  302. /// </summary>
  303. /// <param name="gpuVa">GPU virtual address</param>
  304. /// <returns>Page table entry (CPU virtual address)</returns>
  305. private ulong GetPte(ulong gpuVa)
  306. {
  307. ulong l0 = (gpuVa >> PtLvl0Bit) & PtLvl0Mask;
  308. ulong l1 = (gpuVa >> PtLvl1Bit) & PtLvl1Mask;
  309. if (_pageTable[l0] == null)
  310. {
  311. return PteUnmapped;
  312. }
  313. return _pageTable[l0][l1];
  314. }
  315. /// <summary>
  316. /// Sets a Page Table entry at a given GPU virtual address.
  317. /// </summary>
  318. /// <param name="gpuVa">GPU virtual address</param>
  319. /// <param name="pte">Page table entry (CPU virtual address)</param>
  320. private void SetPte(ulong gpuVa, ulong pte)
  321. {
  322. ulong l0 = (gpuVa >> PtLvl0Bit) & PtLvl0Mask;
  323. ulong l1 = (gpuVa >> PtLvl1Bit) & PtLvl1Mask;
  324. if (_pageTable[l0] == null)
  325. {
  326. _pageTable[l0] = new ulong[PtLvl1Size];
  327. for (ulong index = 0; index < PtLvl1Size; index++)
  328. {
  329. _pageTable[l0][index] = PteUnmapped;
  330. }
  331. }
  332. _pageTable[l0][l1] = pte;
  333. }
  334. }
  335. }