NvMemoryAllocator.cs 15 KB

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