CommandBufferPool.cs 12 KB

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