CommandBufferPool.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378
  1. using Silk.NET.Vulkan;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Diagnostics;
  5. using System.Threading;
  6. using Semaphore = Silk.NET.Vulkan.Semaphore;
  7. namespace Ryujinx.Graphics.Vulkan
  8. {
  9. class CommandBufferPool : IDisposable
  10. {
  11. public const int MaxCommandBuffers = 16;
  12. private readonly int _totalCommandBuffers;
  13. private readonly int _totalCommandBuffersMask;
  14. private readonly Vk _api;
  15. private readonly Device _device;
  16. private readonly Queue _queue;
  17. private readonly object _queueLock;
  18. private readonly CommandPool _pool;
  19. private readonly Thread _owner;
  20. public bool OwnedByCurrentThread => _owner == Thread.CurrentThread;
  21. private struct ReservedCommandBuffer
  22. {
  23. public bool InUse;
  24. public bool InConsumption;
  25. public int SubmissionCount;
  26. public CommandBuffer CommandBuffer;
  27. public FenceHolder Fence;
  28. public SemaphoreHolder Semaphore;
  29. public List<IAuto> Dependants;
  30. public List<MultiFenceHolder> Waitables;
  31. public HashSet<SemaphoreHolder> Dependencies;
  32. public void Initialize(Vk api, Device device, CommandPool pool)
  33. {
  34. var allocateInfo = new CommandBufferAllocateInfo
  35. {
  36. SType = StructureType.CommandBufferAllocateInfo,
  37. CommandBufferCount = 1,
  38. CommandPool = pool,
  39. Level = CommandBufferLevel.Primary,
  40. };
  41. api.AllocateCommandBuffers(device, allocateInfo, out CommandBuffer);
  42. Dependants = new List<IAuto>();
  43. Waitables = new List<MultiFenceHolder>();
  44. Dependencies = new HashSet<SemaphoreHolder>();
  45. }
  46. }
  47. private readonly ReservedCommandBuffer[] _commandBuffers;
  48. private readonly int[] _queuedIndexes;
  49. private int _queuedIndexesPtr;
  50. private int _queuedCount;
  51. private int _inUseCount;
  52. public unsafe CommandBufferPool(Vk api, Device device, Queue queue, object queueLock, uint queueFamilyIndex, bool isLight = false)
  53. {
  54. _api = api;
  55. _device = device;
  56. _queue = queue;
  57. _queueLock = queueLock;
  58. _owner = Thread.CurrentThread;
  59. var commandPoolCreateInfo = new CommandPoolCreateInfo
  60. {
  61. SType = StructureType.CommandPoolCreateInfo,
  62. QueueFamilyIndex = queueFamilyIndex,
  63. Flags = CommandPoolCreateFlags.TransientBit |
  64. CommandPoolCreateFlags.ResetCommandBufferBit,
  65. };
  66. api.CreateCommandPool(device, commandPoolCreateInfo, null, out _pool).ThrowOnError();
  67. // We need at least 2 command buffers to get texture data in some cases.
  68. _totalCommandBuffers = isLight ? 2 : MaxCommandBuffers;
  69. _totalCommandBuffersMask = _totalCommandBuffers - 1;
  70. _commandBuffers = new ReservedCommandBuffer[_totalCommandBuffers];
  71. _queuedIndexes = new int[_totalCommandBuffers];
  72. _queuedIndexesPtr = 0;
  73. _queuedCount = 0;
  74. for (int i = 0; i < _totalCommandBuffers; i++)
  75. {
  76. _commandBuffers[i].Initialize(api, device, _pool);
  77. WaitAndDecrementRef(i);
  78. }
  79. }
  80. public void AddDependant(int cbIndex, IAuto dependant)
  81. {
  82. dependant.IncrementReferenceCount();
  83. _commandBuffers[cbIndex].Dependants.Add(dependant);
  84. }
  85. public void AddWaitable(MultiFenceHolder waitable)
  86. {
  87. lock (_commandBuffers)
  88. {
  89. for (int i = 0; i < _totalCommandBuffers; i++)
  90. {
  91. ref var entry = ref _commandBuffers[i];
  92. if (entry.InConsumption)
  93. {
  94. AddWaitable(i, waitable);
  95. }
  96. }
  97. }
  98. }
  99. public void AddInUseWaitable(MultiFenceHolder waitable)
  100. {
  101. lock (_commandBuffers)
  102. {
  103. for (int i = 0; i < _totalCommandBuffers; i++)
  104. {
  105. ref var entry = ref _commandBuffers[i];
  106. if (entry.InUse)
  107. {
  108. AddWaitable(i, waitable);
  109. }
  110. }
  111. }
  112. }
  113. public void AddDependency(int cbIndex, CommandBufferScoped dependencyCbs)
  114. {
  115. Debug.Assert(_commandBuffers[cbIndex].InUse);
  116. var semaphoreHolder = _commandBuffers[dependencyCbs.CommandBufferIndex].Semaphore;
  117. semaphoreHolder.Get();
  118. _commandBuffers[cbIndex].Dependencies.Add(semaphoreHolder);
  119. }
  120. public void AddWaitable(int cbIndex, MultiFenceHolder waitable)
  121. {
  122. ref var entry = ref _commandBuffers[cbIndex];
  123. if (waitable.AddFence(cbIndex, entry.Fence))
  124. {
  125. entry.Waitables.Add(waitable);
  126. }
  127. }
  128. public bool HasWaitableOnRentedCommandBuffer(MultiFenceHolder waitable, int offset, int size)
  129. {
  130. lock (_commandBuffers)
  131. {
  132. for (int i = 0; i < _totalCommandBuffers; i++)
  133. {
  134. ref var entry = ref _commandBuffers[i];
  135. if (entry.InUse &&
  136. waitable.HasFence(i) &&
  137. waitable.IsBufferRangeInUse(i, offset, size))
  138. {
  139. return true;
  140. }
  141. }
  142. }
  143. return false;
  144. }
  145. public bool IsFenceOnRentedCommandBuffer(FenceHolder fence)
  146. {
  147. lock (_commandBuffers)
  148. {
  149. for (int i = 0; i < _totalCommandBuffers; i++)
  150. {
  151. ref var entry = ref _commandBuffers[i];
  152. if (entry.InUse && entry.Fence == fence)
  153. {
  154. return true;
  155. }
  156. }
  157. }
  158. return false;
  159. }
  160. public FenceHolder GetFence(int cbIndex)
  161. {
  162. return _commandBuffers[cbIndex].Fence;
  163. }
  164. public int GetSubmissionCount(int cbIndex)
  165. {
  166. return _commandBuffers[cbIndex].SubmissionCount;
  167. }
  168. private int FreeConsumed(bool wait)
  169. {
  170. int freeEntry = 0;
  171. while (_queuedCount > 0)
  172. {
  173. int index = _queuedIndexes[_queuedIndexesPtr];
  174. ref var entry = ref _commandBuffers[index];
  175. if (wait || !entry.InConsumption || entry.Fence.IsSignaled())
  176. {
  177. WaitAndDecrementRef(index);
  178. wait = false;
  179. freeEntry = index;
  180. _queuedCount--;
  181. _queuedIndexesPtr = (_queuedIndexesPtr + 1) % _totalCommandBuffers;
  182. }
  183. else
  184. {
  185. break;
  186. }
  187. }
  188. return freeEntry;
  189. }
  190. public CommandBufferScoped ReturnAndRent(CommandBufferScoped cbs)
  191. {
  192. Return(cbs);
  193. return Rent();
  194. }
  195. public CommandBufferScoped Rent()
  196. {
  197. lock (_commandBuffers)
  198. {
  199. int cursor = FreeConsumed(_inUseCount + _queuedCount == _totalCommandBuffers);
  200. for (int i = 0; i < _totalCommandBuffers; i++)
  201. {
  202. ref var entry = ref _commandBuffers[cursor];
  203. if (!entry.InUse && !entry.InConsumption)
  204. {
  205. entry.InUse = true;
  206. _inUseCount++;
  207. var commandBufferBeginInfo = new CommandBufferBeginInfo
  208. {
  209. SType = StructureType.CommandBufferBeginInfo,
  210. };
  211. _api.BeginCommandBuffer(entry.CommandBuffer, commandBufferBeginInfo).ThrowOnError();
  212. return new CommandBufferScoped(this, entry.CommandBuffer, cursor);
  213. }
  214. cursor = (cursor + 1) & _totalCommandBuffersMask;
  215. }
  216. }
  217. throw new InvalidOperationException($"Out of command buffers (In use: {_inUseCount}, queued: {_queuedCount}, total: {_totalCommandBuffers})");
  218. }
  219. public void Return(CommandBufferScoped cbs)
  220. {
  221. Return(cbs, null, null, null);
  222. }
  223. public unsafe void Return(
  224. CommandBufferScoped cbs,
  225. ReadOnlySpan<Semaphore> waitSemaphores,
  226. ReadOnlySpan<PipelineStageFlags> waitDstStageMask,
  227. ReadOnlySpan<Semaphore> signalSemaphores)
  228. {
  229. lock (_commandBuffers)
  230. {
  231. int cbIndex = cbs.CommandBufferIndex;
  232. ref var entry = ref _commandBuffers[cbIndex];
  233. Debug.Assert(entry.InUse);
  234. Debug.Assert(entry.CommandBuffer.Handle == cbs.CommandBuffer.Handle);
  235. entry.InUse = false;
  236. entry.InConsumption = true;
  237. entry.SubmissionCount++;
  238. _inUseCount--;
  239. var commandBuffer = entry.CommandBuffer;
  240. _api.EndCommandBuffer(commandBuffer).ThrowOnError();
  241. fixed (Semaphore* pWaitSemaphores = waitSemaphores, pSignalSemaphores = signalSemaphores)
  242. {
  243. fixed (PipelineStageFlags* pWaitDstStageMask = waitDstStageMask)
  244. {
  245. SubmitInfo sInfo = new()
  246. {
  247. SType = StructureType.SubmitInfo,
  248. WaitSemaphoreCount = waitSemaphores != null ? (uint)waitSemaphores.Length : 0,
  249. PWaitSemaphores = pWaitSemaphores,
  250. PWaitDstStageMask = pWaitDstStageMask,
  251. CommandBufferCount = 1,
  252. PCommandBuffers = &commandBuffer,
  253. SignalSemaphoreCount = signalSemaphores != null ? (uint)signalSemaphores.Length : 0,
  254. PSignalSemaphores = pSignalSemaphores,
  255. };
  256. lock (_queueLock)
  257. {
  258. _api.QueueSubmit(_queue, 1, sInfo, entry.Fence.GetUnsafe()).ThrowOnError();
  259. }
  260. }
  261. }
  262. int ptr = (_queuedIndexesPtr + _queuedCount) % _totalCommandBuffers;
  263. _queuedIndexes[ptr] = cbIndex;
  264. _queuedCount++;
  265. }
  266. }
  267. private void WaitAndDecrementRef(int cbIndex, bool refreshFence = true)
  268. {
  269. ref var entry = ref _commandBuffers[cbIndex];
  270. if (entry.InConsumption)
  271. {
  272. entry.Fence.Wait();
  273. entry.InConsumption = false;
  274. }
  275. foreach (var dependant in entry.Dependants)
  276. {
  277. dependant.DecrementReferenceCount(cbIndex);
  278. }
  279. foreach (var waitable in entry.Waitables)
  280. {
  281. waitable.RemoveFence(cbIndex);
  282. waitable.RemoveBufferUses(cbIndex);
  283. }
  284. foreach (var dependency in entry.Dependencies)
  285. {
  286. dependency.Put();
  287. }
  288. entry.Dependants.Clear();
  289. entry.Waitables.Clear();
  290. entry.Dependencies.Clear();
  291. entry.Fence?.Dispose();
  292. if (refreshFence)
  293. {
  294. entry.Fence = new FenceHolder(_api, _device);
  295. }
  296. else
  297. {
  298. entry.Fence = null;
  299. }
  300. }
  301. public unsafe void Dispose()
  302. {
  303. for (int i = 0; i < _totalCommandBuffers; i++)
  304. {
  305. WaitAndDecrementRef(i, refreshFence: false);
  306. }
  307. _api.DestroyCommandPool(_device, _pool, null);
  308. }
  309. }
  310. }