CommandBufferPool.cs 11 KB

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