NvMemoryAllocator.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310
  1. using Ryujinx.Common.Collections;
  2. using System.Collections.Generic;
  3. using System;
  4. using Ryujinx.Graphics.Gpu.Memory;
  5. using Ryujinx.Common.Logging;
  6. namespace Ryujinx.HLE.HOS.Services.Nv
  7. {
  8. class NvMemoryAllocator
  9. {
  10. private const ulong AddressSpaceSize = 1UL << 40;
  11. private const ulong DefaultStart = 1UL << 32;
  12. private const ulong InvalidAddress = 0;
  13. private const ulong PageSize = MemoryManager.PageSize;
  14. private const ulong PageMask = MemoryManager.PageMask;
  15. public const ulong PteUnmapped = MemoryManager.PteUnmapped;
  16. // Key --> Start Address of Region
  17. // Value --> End Address of Region
  18. private readonly TreeDictionary<ulong, ulong> _tree = new TreeDictionary<ulong, ulong>();
  19. private readonly Dictionary<ulong, LinkedListNode<ulong>> _dictionary = new Dictionary<ulong, LinkedListNode<ulong>>();
  20. private readonly LinkedList<ulong> _list = new LinkedList<ulong>();
  21. public NvMemoryAllocator()
  22. {
  23. _tree.Add(PageSize, AddressSpaceSize);
  24. LinkedListNode<ulong> node = _list.AddFirst(PageSize);
  25. _dictionary[PageSize] = node;
  26. }
  27. /// <summary>
  28. /// Marks a range of memory as consumed by removing it from the tree.
  29. /// This function will split memory regions if there is available space.
  30. /// </summary>
  31. /// <param name="va">Virtual address at which to allocate</param>
  32. /// <param name="size">Size of the allocation in bytes</param>
  33. /// <param name="referenceAddress">Reference to the address of memory where the allocation can take place</param>
  34. #region Memory Allocation
  35. public void AllocateRange(ulong va, ulong size, ulong referenceAddress = InvalidAddress)
  36. {
  37. lock (_tree)
  38. {
  39. Logger.Debug?.Print(LogClass.ServiceNv, $"Allocating range from 0x{va:X} to 0x{(va + size):X}.");
  40. if (referenceAddress != InvalidAddress)
  41. {
  42. ulong endAddress = va + size;
  43. ulong referenceEndAddress = _tree.Get(referenceAddress);
  44. if (va >= referenceAddress)
  45. {
  46. // Need Left Node
  47. if (va > referenceAddress)
  48. {
  49. ulong leftEndAddress = va;
  50. // Overwrite existing block with its new smaller range.
  51. _tree.Add(referenceAddress, leftEndAddress);
  52. Logger.Debug?.Print(LogClass.ServiceNv, $"Created smaller address range from 0x{referenceAddress:X} to 0x{leftEndAddress:X}.");
  53. }
  54. else
  55. {
  56. // We need to get rid of the large chunk.
  57. _tree.Remove(referenceAddress);
  58. }
  59. ulong rightSize = referenceEndAddress - endAddress;
  60. // If leftover space, create a right node.
  61. if (rightSize > 0)
  62. {
  63. Logger.Debug?.Print(LogClass.ServiceNv, $"Created smaller address range from 0x{endAddress:X} to 0x{referenceEndAddress:X}.");
  64. _tree.Add(endAddress, referenceEndAddress);
  65. LinkedListNode<ulong> node = _list.AddAfter(_dictionary[referenceAddress], endAddress);
  66. _dictionary[endAddress] = node;
  67. }
  68. if (va == referenceAddress)
  69. {
  70. _list.Remove(_dictionary[referenceAddress]);
  71. _dictionary.Remove(referenceAddress);
  72. }
  73. }
  74. }
  75. }
  76. }
  77. /// <summary>
  78. /// Marks a range of memory as free by adding it to the tree.
  79. /// This function will automatically compact the tree when it determines there are multiple ranges of free memory adjacent to each other.
  80. /// </summary>
  81. /// <param name="va">Virtual address at which to deallocate</param>
  82. /// <param name="size">Size of the allocation in bytes</param>
  83. public void DeallocateRange(ulong va, ulong size)
  84. {
  85. lock (_tree)
  86. {
  87. Logger.Debug?.Print(LogClass.ServiceNv, $"Deallocating address range from 0x{va:X} to 0x{(va + size):X}.");
  88. ulong freeAddressStartPosition = _tree.Floor(va);
  89. if (freeAddressStartPosition != InvalidAddress)
  90. {
  91. LinkedListNode<ulong> node = _dictionary[freeAddressStartPosition];
  92. ulong targetPrevAddress = _dictionary[freeAddressStartPosition].Previous != null ? _dictionary[_dictionary[freeAddressStartPosition].Previous.Value].Value : InvalidAddress;
  93. ulong targetNextAddress = _dictionary[freeAddressStartPosition].Next != null ? _dictionary[_dictionary[freeAddressStartPosition].Next.Value].Value : InvalidAddress;
  94. ulong expandedStart = va;
  95. ulong expandedEnd = va + size;
  96. while (targetPrevAddress != InvalidAddress)
  97. {
  98. ulong prevAddress = targetPrevAddress;
  99. ulong prevEndAddress = _tree.Get(targetPrevAddress);
  100. if (prevEndAddress >= expandedStart)
  101. {
  102. expandedStart = targetPrevAddress;
  103. LinkedListNode<ulong> prevPtr = _dictionary[prevAddress];
  104. if (prevPtr.Previous != null)
  105. {
  106. targetPrevAddress = prevPtr.Previous.Value;
  107. }
  108. else
  109. {
  110. targetPrevAddress = InvalidAddress;
  111. }
  112. node = node.Previous;
  113. _tree.Remove(prevAddress);
  114. _list.Remove(_dictionary[prevAddress]);
  115. _dictionary.Remove(prevAddress);
  116. }
  117. else
  118. {
  119. break;
  120. }
  121. }
  122. while (targetNextAddress != InvalidAddress)
  123. {
  124. ulong nextAddress = targetNextAddress;
  125. ulong nextEndAddress = _tree.Get(targetNextAddress);
  126. if (nextAddress <= expandedEnd)
  127. {
  128. expandedEnd = Math.Max(expandedEnd, nextEndAddress);
  129. LinkedListNode<ulong> nextPtr = _dictionary[nextAddress];
  130. if (nextPtr.Next != null)
  131. {
  132. targetNextAddress = nextPtr.Next.Value;
  133. }
  134. else
  135. {
  136. targetNextAddress = InvalidAddress;
  137. }
  138. _tree.Remove(nextAddress);
  139. _list.Remove(_dictionary[nextAddress]);
  140. _dictionary.Remove(nextAddress);
  141. }
  142. else
  143. {
  144. break;
  145. }
  146. }
  147. Logger.Debug?.Print(LogClass.ServiceNv, $"Deallocation resulted in new free range from 0x{expandedStart:X} to 0x{expandedEnd:X}.");
  148. _tree.Add(expandedStart, expandedEnd);
  149. LinkedListNode<ulong> nodePtr = _list.AddAfter(node, expandedStart);
  150. _dictionary[expandedStart] = nodePtr;
  151. }
  152. }
  153. }
  154. /// <summary>
  155. /// Gets the address of an unused (free) region of the specified size.
  156. /// </summary>
  157. /// <param name="size">Size of the region in bytes</param>
  158. /// <param name="freeAddressStartPosition">Position at which memory can be allocated</param>
  159. /// <param name="alignment">Required alignment of the region address in bytes</param>
  160. /// <param name="start">Start address of the search on the address space</param>
  161. /// <returns>GPU virtual address of the allocation, or an all ones mask in case of failure</returns>
  162. public ulong GetFreeAddress(ulong size, out ulong freeAddressStartPosition, ulong alignment = 1, ulong start = DefaultStart)
  163. {
  164. // Note: Address 0 is not considered valid by the driver,
  165. // when 0 is returned it's considered a mapping error.
  166. lock (_tree)
  167. {
  168. Logger.Debug?.Print(LogClass.ServiceNv, $"Searching for a free address @ 0x{start:X} of size 0x{size:X}.");
  169. ulong address = start;
  170. if (alignment == 0)
  171. {
  172. alignment = 1;
  173. }
  174. alignment = (alignment + PageMask) & ~PageMask;
  175. if (address < AddressSpaceSize)
  176. {
  177. bool reachedEndOfAddresses = false;
  178. ulong targetAddress;
  179. if (start == DefaultStart)
  180. {
  181. Logger.Debug?.Print(LogClass.ServiceNv, $"Target address set to start of the last available range: 0x{_list.Last.Value:X}.");
  182. targetAddress = _list.Last.Value;
  183. }
  184. else
  185. {
  186. targetAddress = _tree.Floor(address);
  187. Logger.Debug?.Print(LogClass.ServiceNv, $"Target address set to floor of 0x{address:X}; resulted in 0x{targetAddress:X}.");
  188. if (targetAddress == InvalidAddress)
  189. {
  190. targetAddress = _tree.Ceiling(address);
  191. Logger.Debug?.Print(LogClass.ServiceNv, $"Target address was invalid, set to ceiling of 0x{address:X}; resulted in 0x{targetAddress:X}");
  192. }
  193. }
  194. while (address < AddressSpaceSize)
  195. {
  196. if (targetAddress != InvalidAddress)
  197. {
  198. if (address >= targetAddress)
  199. {
  200. if (address + size <= _tree.Get(targetAddress))
  201. {
  202. Logger.Debug?.Print(LogClass.ServiceNv, $"Found a suitable free address range from 0x{targetAddress:X} to 0x{_tree.Get(targetAddress):X} for 0x{address:X}.");
  203. freeAddressStartPosition = targetAddress;
  204. return address;
  205. }
  206. else
  207. {
  208. Logger.Debug?.Print(LogClass.ServiceNv, "Address requirements exceeded the available space in the target range.");
  209. LinkedListNode<ulong> nextPtr = _dictionary[targetAddress];
  210. if (nextPtr.Next != null)
  211. {
  212. targetAddress = nextPtr.Next.Value;
  213. Logger.Debug?.Print(LogClass.ServiceNv, $"Moved search to successor range starting at 0x{targetAddress:X}.");
  214. }
  215. else
  216. {
  217. if (reachedEndOfAddresses)
  218. {
  219. Logger.Debug?.Print(LogClass.ServiceNv, "Exiting loop, a full pass has already been completed w/ no suitable free address range.");
  220. break;
  221. }
  222. else
  223. {
  224. reachedEndOfAddresses = true;
  225. address = start;
  226. targetAddress = _tree.Floor(address);
  227. Logger.Debug?.Print(LogClass.ServiceNv, $"Reached the end of the available free ranges, restarting loop @ 0x{targetAddress:X} for 0x{address:X}.");
  228. }
  229. }
  230. }
  231. }
  232. else
  233. {
  234. address += PageSize * (targetAddress / PageSize - (address / PageSize));
  235. ulong remainder = address % alignment;
  236. if (remainder != 0)
  237. {
  238. address = (address - remainder) + alignment;
  239. }
  240. Logger.Debug?.Print(LogClass.ServiceNv, $"Reset and aligned address to {address:X}.");
  241. if (address + size > AddressSpaceSize && !reachedEndOfAddresses)
  242. {
  243. reachedEndOfAddresses = true;
  244. address = start;
  245. targetAddress = _tree.Floor(address);
  246. Logger.Debug?.Print(LogClass.ServiceNv, $"Address requirements exceeded the capacity of available address space, restarting loop @ 0x{targetAddress:X} for 0x{address:X}.");
  247. }
  248. }
  249. }
  250. else
  251. {
  252. break;
  253. }
  254. }
  255. }
  256. Logger.Debug?.Print(LogClass.ServiceNv, $"No suitable address range found; returning: 0x{InvalidAddress:X}.");
  257. freeAddressStartPosition = InvalidAddress;
  258. }
  259. return PteUnmapped;
  260. }
  261. /// <summary>
  262. /// Checks if a given memory region is mapped or reserved.
  263. /// </summary>
  264. /// <param name="gpuVa">GPU virtual address of the page</param>
  265. /// <param name="size">Size of the allocation in bytes</param>
  266. /// <param name="freeAddressStartPosition">Nearest lower address that memory can be allocated</param>
  267. /// <returns>True if the page is mapped or reserved, false otherwise</returns>
  268. public bool IsRegionInUse(ulong gpuVa, ulong size, out ulong freeAddressStartPosition)
  269. {
  270. lock (_tree)
  271. {
  272. ulong floorAddress = _tree.Floor(gpuVa);
  273. freeAddressStartPosition = floorAddress;
  274. if (floorAddress != InvalidAddress)
  275. {
  276. return !(gpuVa >= floorAddress && ((gpuVa + size) <= _tree.Get(floorAddress)));
  277. }
  278. }
  279. return true;
  280. }
  281. #endregion
  282. }
  283. }