CommandBufferPool.cs 12 KB

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