vk_scheduler.h 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250
  1. // SPDX-FileCopyrightText: Copyright 2019 yuzu Emulator Project
  2. // SPDX-License-Identifier: GPL-2.0-or-later
  3. #pragma once
  4. #include <condition_variable>
  5. #include <cstddef>
  6. #include <functional>
  7. #include <memory>
  8. #include <thread>
  9. #include <utility>
  10. #include <queue>
  11. #include "common/alignment.h"
  12. #include "common/common_types.h"
  13. #include "common/polyfill_thread.h"
  14. #include "video_core/renderer_vulkan/vk_master_semaphore.h"
  15. #include "video_core/vulkan_common/vulkan_wrapper.h"
  16. namespace VideoCommon {
  17. template <typename Trait>
  18. class QueryCacheBase;
  19. }
  20. namespace Vulkan {
  21. class CommandPool;
  22. class Device;
  23. class Framebuffer;
  24. class GraphicsPipeline;
  25. class StateTracker;
  26. struct QueryCacheParams;
  27. /// The scheduler abstracts command buffer and fence management with an interface that's able to do
  28. /// OpenGL-like operations on Vulkan command buffers.
  29. class Scheduler {
  30. public:
  31. explicit Scheduler(const Device& device, StateTracker& state_tracker);
  32. ~Scheduler();
  33. /// Sends the current execution context to the GPU.
  34. u64 Flush(VkSemaphore signal_semaphore = nullptr, VkSemaphore wait_semaphore = nullptr);
  35. /// Sends the current execution context to the GPU and waits for it to complete.
  36. void Finish(VkSemaphore signal_semaphore = nullptr, VkSemaphore wait_semaphore = nullptr);
  37. /// Waits for the worker thread to finish executing everything. After this function returns it's
  38. /// safe to touch worker resources.
  39. void WaitWorker();
  40. /// Sends currently recorded work to the worker thread.
  41. void DispatchWork();
  42. /// Requests to begin a renderpass.
  43. void RequestRenderpass(const Framebuffer* framebuffer);
  44. /// Requests the current executino context to be able to execute operations only allowed outside
  45. /// of a renderpass.
  46. void RequestOutsideRenderPassOperationContext();
  47. /// Update the pipeline to the current execution context.
  48. bool UpdateGraphicsPipeline(GraphicsPipeline* pipeline);
  49. /// Update the rescaling state. Returns true if the state has to be updated.
  50. bool UpdateRescaling(bool is_rescaling);
  51. /// Invalidates current command buffer state except for render passes
  52. void InvalidateState();
  53. /// Assigns the query cache.
  54. void SetQueryCache(VideoCommon::QueryCacheBase<QueryCacheParams>& query_cache_) {
  55. query_cache = &query_cache_;
  56. }
  57. // Registers a callback to perform on queue submission.
  58. void RegisterOnSubmit(std::function<void()>&& func) {
  59. on_submit = std::move(func);
  60. }
  61. /// Send work to a separate thread.
  62. template <typename T>
  63. void Record(T&& command) {
  64. if (chunk->Record(command)) {
  65. return;
  66. }
  67. DispatchWork();
  68. (void)chunk->Record(command);
  69. }
  70. /// Returns the current command buffer tick.
  71. [[nodiscard]] u64 CurrentTick() const noexcept {
  72. return master_semaphore->CurrentTick();
  73. }
  74. /// Returns true when a tick has been triggered by the GPU.
  75. [[nodiscard]] bool IsFree(u64 tick) const noexcept {
  76. return master_semaphore->IsFree(tick);
  77. }
  78. /// Waits for the given tick to trigger on the GPU.
  79. void Wait(u64 tick) {
  80. if (tick >= master_semaphore->CurrentTick()) {
  81. // Make sure we are not waiting for the current tick without signalling
  82. Flush();
  83. }
  84. master_semaphore->Wait(tick);
  85. }
  86. /// Returns the master timeline semaphore.
  87. [[nodiscard]] MasterSemaphore& GetMasterSemaphore() const noexcept {
  88. return *master_semaphore;
  89. }
  90. std::mutex submit_mutex;
  91. private:
  92. class Command {
  93. public:
  94. virtual ~Command() = default;
  95. virtual void Execute(vk::CommandBuffer cmdbuf) const = 0;
  96. Command* GetNext() const {
  97. return next;
  98. }
  99. void SetNext(Command* next_) {
  100. next = next_;
  101. }
  102. private:
  103. Command* next = nullptr;
  104. };
  105. template <typename T>
  106. class TypedCommand final : public Command {
  107. public:
  108. explicit TypedCommand(T&& command_) : command{std::move(command_)} {}
  109. ~TypedCommand() override = default;
  110. TypedCommand(TypedCommand&&) = delete;
  111. TypedCommand& operator=(TypedCommand&&) = delete;
  112. void Execute(vk::CommandBuffer cmdbuf) const override {
  113. command(cmdbuf);
  114. }
  115. private:
  116. T command;
  117. };
  118. class CommandChunk final {
  119. public:
  120. void ExecuteAll(vk::CommandBuffer cmdbuf);
  121. template <typename T>
  122. bool Record(T& command) {
  123. using FuncType = TypedCommand<T>;
  124. static_assert(sizeof(FuncType) < sizeof(data), "Lambda is too large");
  125. command_offset = Common::AlignUp(command_offset, alignof(FuncType));
  126. if (command_offset > sizeof(data) - sizeof(FuncType)) {
  127. return false;
  128. }
  129. Command* const current_last = last;
  130. last = new (data.data() + command_offset) FuncType(std::move(command));
  131. if (current_last) {
  132. current_last->SetNext(last);
  133. } else {
  134. first = last;
  135. }
  136. command_offset += sizeof(FuncType);
  137. return true;
  138. }
  139. void MarkSubmit() {
  140. submit = true;
  141. }
  142. bool Empty() const {
  143. return command_offset == 0;
  144. }
  145. bool HasSubmit() const {
  146. return submit;
  147. }
  148. private:
  149. Command* first = nullptr;
  150. Command* last = nullptr;
  151. size_t command_offset = 0;
  152. bool submit = false;
  153. alignas(std::max_align_t) std::array<u8, 0x8000> data{};
  154. };
  155. struct State {
  156. VkRenderPass renderpass = nullptr;
  157. VkFramebuffer framebuffer = nullptr;
  158. VkExtent2D render_area = {0, 0};
  159. GraphicsPipeline* graphics_pipeline = nullptr;
  160. bool is_rescaling = false;
  161. bool rescaling_defined = false;
  162. };
  163. void WorkerThread(std::stop_token stop_token);
  164. void AllocateWorkerCommandBuffer();
  165. u64 SubmitExecution(VkSemaphore signal_semaphore, VkSemaphore wait_semaphore);
  166. void AllocateNewContext();
  167. void EndPendingOperations();
  168. void EndRenderPass();
  169. void AcquireNewChunk();
  170. const Device& device;
  171. StateTracker& state_tracker;
  172. std::unique_ptr<MasterSemaphore> master_semaphore;
  173. std::unique_ptr<CommandPool> command_pool;
  174. VideoCommon::QueryCacheBase<QueryCacheParams>* query_cache = nullptr;
  175. vk::CommandBuffer current_cmdbuf;
  176. std::unique_ptr<CommandChunk> chunk;
  177. std::function<void()> on_submit;
  178. State state;
  179. u32 num_renderpass_images = 0;
  180. std::array<VkImage, 9> renderpass_images{};
  181. std::array<VkImageSubresourceRange, 9> renderpass_image_ranges{};
  182. std::queue<std::unique_ptr<CommandChunk>> work_queue;
  183. std::vector<std::unique_ptr<CommandChunk>> chunk_reserve;
  184. std::mutex execution_mutex;
  185. std::mutex reserve_mutex;
  186. std::mutex queue_mutex;
  187. std::condition_variable_any event_cv;
  188. std::jthread worker_thread;
  189. };
  190. } // namespace Vulkan