CommandBufferPool.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370
  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 List<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 List<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 AddInUseWaitable(MultiFenceHolder waitable)
  98. {
  99. lock (_commandBuffers)
  100. {
  101. for (int i = 0; i < _totalCommandBuffers; i++)
  102. {
  103. ref var entry = ref _commandBuffers[i];
  104. if (entry.InUse)
  105. {
  106. AddWaitable(i, waitable);
  107. }
  108. }
  109. }
  110. }
  111. public void AddDependency(int cbIndex, CommandBufferScoped dependencyCbs)
  112. {
  113. Debug.Assert(_commandBuffers[cbIndex].InUse);
  114. var semaphoreHolder = _commandBuffers[dependencyCbs.CommandBufferIndex].Semaphore;
  115. semaphoreHolder.Get();
  116. _commandBuffers[cbIndex].Dependencies.Add(semaphoreHolder);
  117. }
  118. public void AddWaitable(int cbIndex, MultiFenceHolder waitable)
  119. {
  120. ref var entry = ref _commandBuffers[cbIndex];
  121. if (waitable.AddFence(cbIndex, entry.Fence))
  122. {
  123. entry.Waitables.Add(waitable);
  124. }
  125. }
  126. public bool HasWaitableOnRentedCommandBuffer(MultiFenceHolder waitable, int offset, int size)
  127. {
  128. lock (_commandBuffers)
  129. {
  130. for (int i = 0; i < _totalCommandBuffers; i++)
  131. {
  132. ref var entry = ref _commandBuffers[i];
  133. if (entry.InUse &&
  134. waitable.HasFence(i) &&
  135. waitable.IsBufferRangeInUse(i, offset, size))
  136. {
  137. return true;
  138. }
  139. }
  140. }
  141. return false;
  142. }
  143. public bool IsFenceOnRentedCommandBuffer(FenceHolder fence)
  144. {
  145. lock (_commandBuffers)
  146. {
  147. for (int i = 0; i < _totalCommandBuffers; i++)
  148. {
  149. ref var entry = ref _commandBuffers[i];
  150. if (entry.InUse && entry.Fence == fence)
  151. {
  152. return true;
  153. }
  154. }
  155. }
  156. return false;
  157. }
  158. public FenceHolder GetFence(int cbIndex)
  159. {
  160. return _commandBuffers[cbIndex].Fence;
  161. }
  162. private int FreeConsumed(bool wait)
  163. {
  164. int freeEntry = 0;
  165. while (_queuedCount > 0)
  166. {
  167. int index = _queuedIndexes[_queuedIndexesPtr];
  168. ref var entry = ref _commandBuffers[index];
  169. if (wait || !entry.InConsumption || entry.Fence.IsSignaled())
  170. {
  171. WaitAndDecrementRef(index);
  172. wait = false;
  173. freeEntry = index;
  174. _queuedCount--;
  175. _queuedIndexesPtr = (_queuedIndexesPtr + 1) % _totalCommandBuffers;
  176. }
  177. else
  178. {
  179. break;
  180. }
  181. }
  182. return freeEntry;
  183. }
  184. public CommandBufferScoped ReturnAndRent(CommandBufferScoped cbs)
  185. {
  186. Return(cbs);
  187. return Rent();
  188. }
  189. public CommandBufferScoped Rent()
  190. {
  191. lock (_commandBuffers)
  192. {
  193. int cursor = FreeConsumed(_inUseCount + _queuedCount == _totalCommandBuffers);
  194. for (int i = 0; i < _totalCommandBuffers; i++)
  195. {
  196. ref var entry = ref _commandBuffers[cursor];
  197. if (!entry.InUse && !entry.InConsumption)
  198. {
  199. entry.InUse = true;
  200. _inUseCount++;
  201. var commandBufferBeginInfo = new CommandBufferBeginInfo()
  202. {
  203. SType = StructureType.CommandBufferBeginInfo
  204. };
  205. _api.BeginCommandBuffer(entry.CommandBuffer, commandBufferBeginInfo).ThrowOnError();
  206. return new CommandBufferScoped(this, entry.CommandBuffer, cursor);
  207. }
  208. cursor = (cursor + 1) & _totalCommandBuffersMask;
  209. }
  210. }
  211. throw new InvalidOperationException($"Out of command buffers (In use: {_inUseCount}, queued: {_queuedCount}, total: {_totalCommandBuffers})");
  212. }
  213. public void Return(CommandBufferScoped cbs)
  214. {
  215. Return(cbs, null, null, null);
  216. }
  217. public unsafe void Return(
  218. CommandBufferScoped cbs,
  219. ReadOnlySpan<Semaphore> waitSemaphores,
  220. ReadOnlySpan<PipelineStageFlags> waitDstStageMask,
  221. ReadOnlySpan<Semaphore> signalSemaphores)
  222. {
  223. lock (_commandBuffers)
  224. {
  225. int cbIndex = cbs.CommandBufferIndex;
  226. ref var entry = ref _commandBuffers[cbIndex];
  227. Debug.Assert(entry.InUse);
  228. Debug.Assert(entry.CommandBuffer.Handle == cbs.CommandBuffer.Handle);
  229. entry.InUse = false;
  230. entry.InConsumption = true;
  231. _inUseCount--;
  232. var commandBuffer = entry.CommandBuffer;
  233. _api.EndCommandBuffer(commandBuffer).ThrowOnError();
  234. fixed (Semaphore* pWaitSemaphores = waitSemaphores, pSignalSemaphores = signalSemaphores)
  235. {
  236. fixed (PipelineStageFlags* pWaitDstStageMask = waitDstStageMask)
  237. {
  238. SubmitInfo sInfo = new SubmitInfo()
  239. {
  240. SType = StructureType.SubmitInfo,
  241. WaitSemaphoreCount = waitSemaphores != null ? (uint)waitSemaphores.Length : 0,
  242. PWaitSemaphores = pWaitSemaphores,
  243. PWaitDstStageMask = pWaitDstStageMask,
  244. CommandBufferCount = 1,
  245. PCommandBuffers = &commandBuffer,
  246. SignalSemaphoreCount = signalSemaphores != null ? (uint)signalSemaphores.Length : 0,
  247. PSignalSemaphores = pSignalSemaphores
  248. };
  249. lock (_queueLock)
  250. {
  251. _api.QueueSubmit(_queue, 1, sInfo, entry.Fence.GetUnsafe()).ThrowOnError();
  252. }
  253. }
  254. }
  255. int ptr = (_queuedIndexesPtr + _queuedCount) % _totalCommandBuffers;
  256. _queuedIndexes[ptr] = cbIndex;
  257. _queuedCount++;
  258. }
  259. }
  260. private void WaitAndDecrementRef(int cbIndex, bool refreshFence = true)
  261. {
  262. ref var entry = ref _commandBuffers[cbIndex];
  263. if (entry.InConsumption)
  264. {
  265. entry.Fence.Wait();
  266. entry.InConsumption = false;
  267. }
  268. foreach (var dependant in entry.Dependants)
  269. {
  270. dependant.DecrementReferenceCount(cbIndex);
  271. }
  272. foreach (var waitable in entry.Waitables)
  273. {
  274. waitable.RemoveFence(cbIndex);
  275. waitable.RemoveBufferUses(cbIndex);
  276. }
  277. foreach (var dependency in entry.Dependencies)
  278. {
  279. dependency.Put();
  280. }
  281. entry.Dependants.Clear();
  282. entry.Waitables.Clear();
  283. entry.Dependencies.Clear();
  284. entry.Fence?.Dispose();
  285. if (refreshFence)
  286. {
  287. entry.Fence = new FenceHolder(_api, _device);
  288. }
  289. else
  290. {
  291. entry.Fence = null;
  292. }
  293. }
  294. public unsafe void Dispose()
  295. {
  296. for (int i = 0; i < _totalCommandBuffers; i++)
  297. {
  298. WaitAndDecrementRef(i, refreshFence: false);
  299. }
  300. _api.DestroyCommandPool(_device, _pool, null);
  301. }
  302. }
  303. }