gpu.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552
  1. // SPDX-FileCopyrightText: Copyright 2018 yuzu Emulator Project
  2. // SPDX-License-Identifier: GPL-2.0-or-later
  3. #include <array>
  4. #include <atomic>
  5. #include <chrono>
  6. #include <condition_variable>
  7. #include <list>
  8. #include <memory>
  9. #include "common/assert.h"
  10. #include "common/microprofile.h"
  11. #include "common/settings.h"
  12. #include "core/core.h"
  13. #include "core/core_timing.h"
  14. #include "core/frontend/emu_window.h"
  15. #include "core/hle/service/nvdrv/nvdata.h"
  16. #include "core/perf_stats.h"
  17. #include "video_core/cdma_pusher.h"
  18. #include "video_core/control/channel_state.h"
  19. #include "video_core/control/scheduler.h"
  20. #include "video_core/dma_pusher.h"
  21. #include "video_core/engines/fermi_2d.h"
  22. #include "video_core/engines/kepler_compute.h"
  23. #include "video_core/engines/kepler_memory.h"
  24. #include "video_core/engines/maxwell_3d.h"
  25. #include "video_core/engines/maxwell_dma.h"
  26. #include "video_core/gpu.h"
  27. #include "video_core/gpu_thread.h"
  28. #include "video_core/host1x/host1x.h"
  29. #include "video_core/host1x/syncpoint_manager.h"
  30. #include "video_core/memory_manager.h"
  31. #include "video_core/renderer_base.h"
  32. #include "video_core/shader_notify.h"
  33. namespace Tegra {
  34. struct GPU::Impl {
  35. explicit Impl(GPU& gpu_, Core::System& system_, bool is_async_, bool use_nvdec_)
  36. : gpu{gpu_}, system{system_}, host1x{system.Host1x()}, use_nvdec{use_nvdec_},
  37. shader_notify{std::make_unique<VideoCore::ShaderNotify>()}, is_async{is_async_},
  38. gpu_thread{system_, is_async_}, scheduler{std::make_unique<Control::Scheduler>(gpu)} {}
  39. ~Impl() = default;
  40. std::shared_ptr<Control::ChannelState> CreateChannel(s32 channel_id) {
  41. auto channel_state = std::make_shared<Tegra::Control::ChannelState>(channel_id);
  42. channels.emplace(channel_id, channel_state);
  43. scheduler->DeclareChannel(channel_state);
  44. return channel_state;
  45. }
  46. void BindChannel(s32 channel_id) {
  47. if (bound_channel == channel_id) {
  48. return;
  49. }
  50. auto it = channels.find(channel_id);
  51. ASSERT(it != channels.end());
  52. bound_channel = channel_id;
  53. current_channel = it->second.get();
  54. rasterizer->BindChannel(*current_channel);
  55. }
  56. std::shared_ptr<Control::ChannelState> AllocateChannel() {
  57. return CreateChannel(new_channel_id++);
  58. }
  59. void InitChannel(Control::ChannelState& to_init) {
  60. to_init.Init(system, gpu);
  61. to_init.BindRasterizer(rasterizer);
  62. rasterizer->InitializeChannel(to_init);
  63. }
  64. void InitAddressSpace(Tegra::MemoryManager& memory_manager) {
  65. memory_manager.BindRasterizer(rasterizer);
  66. }
  67. void ReleaseChannel(Control::ChannelState& to_release) {
  68. UNIMPLEMENTED();
  69. }
  70. /// Binds a renderer to the GPU.
  71. void BindRenderer(std::unique_ptr<VideoCore::RendererBase> renderer_) {
  72. renderer = std::move(renderer_);
  73. rasterizer = renderer->ReadRasterizer();
  74. host1x.MemoryManager().BindRasterizer(rasterizer);
  75. }
  76. /// Flush all current written commands into the host GPU for execution.
  77. void FlushCommands() {
  78. rasterizer->FlushCommands();
  79. }
  80. /// Synchronizes CPU writes with Host GPU memory.
  81. void InvalidateGPUCache() {
  82. rasterizer->InvalidateGPUCache();
  83. }
  84. /// Signal the ending of command list.
  85. void OnCommandListEnd() {
  86. gpu_thread.OnCommandListEnd();
  87. }
  88. /// Request a host GPU memory flush from the CPU.
  89. template <typename Func>
  90. [[nodiscard]] u64 RequestSyncOperation(Func&& action) {
  91. std::unique_lock lck{sync_request_mutex};
  92. const u64 fence = ++last_sync_fence;
  93. sync_requests.emplace_back(action);
  94. return fence;
  95. }
  96. /// Obtains current flush request fence id.
  97. [[nodiscard]] u64 CurrentSyncRequestFence() const {
  98. return current_sync_fence.load(std::memory_order_relaxed);
  99. }
  100. void WaitForSyncOperation(const u64 fence) {
  101. std::unique_lock lck{sync_request_mutex};
  102. sync_request_cv.wait(lck, [this, fence] { return CurrentSyncRequestFence() >= fence; });
  103. }
  104. /// Tick pending requests within the GPU.
  105. void TickWork() {
  106. std::unique_lock lck{sync_request_mutex};
  107. while (!sync_requests.empty()) {
  108. auto request = std::move(sync_requests.front());
  109. sync_requests.pop_front();
  110. sync_request_mutex.unlock();
  111. request();
  112. current_sync_fence.fetch_add(1, std::memory_order_release);
  113. sync_request_mutex.lock();
  114. sync_request_cv.notify_all();
  115. }
  116. }
  117. /// Returns a reference to the Maxwell3D GPU engine.
  118. [[nodiscard]] Engines::Maxwell3D& Maxwell3D() {
  119. ASSERT(current_channel);
  120. return *current_channel->maxwell_3d;
  121. }
  122. /// Returns a const reference to the Maxwell3D GPU engine.
  123. [[nodiscard]] const Engines::Maxwell3D& Maxwell3D() const {
  124. ASSERT(current_channel);
  125. return *current_channel->maxwell_3d;
  126. }
  127. /// Returns a reference to the KeplerCompute GPU engine.
  128. [[nodiscard]] Engines::KeplerCompute& KeplerCompute() {
  129. ASSERT(current_channel);
  130. return *current_channel->kepler_compute;
  131. }
  132. /// Returns a reference to the KeplerCompute GPU engine.
  133. [[nodiscard]] const Engines::KeplerCompute& KeplerCompute() const {
  134. ASSERT(current_channel);
  135. return *current_channel->kepler_compute;
  136. }
  137. /// Returns a reference to the GPU DMA pusher.
  138. [[nodiscard]] Tegra::DmaPusher& DmaPusher() {
  139. ASSERT(current_channel);
  140. return *current_channel->dma_pusher;
  141. }
  142. /// Returns a const reference to the GPU DMA pusher.
  143. [[nodiscard]] const Tegra::DmaPusher& DmaPusher() const {
  144. ASSERT(current_channel);
  145. return *current_channel->dma_pusher;
  146. }
  147. /// Returns a reference to the underlying renderer.
  148. [[nodiscard]] VideoCore::RendererBase& Renderer() {
  149. return *renderer;
  150. }
  151. /// Returns a const reference to the underlying renderer.
  152. [[nodiscard]] const VideoCore::RendererBase& Renderer() const {
  153. return *renderer;
  154. }
  155. /// Returns a reference to the shader notifier.
  156. [[nodiscard]] VideoCore::ShaderNotify& ShaderNotify() {
  157. return *shader_notify;
  158. }
  159. /// Returns a const reference to the shader notifier.
  160. [[nodiscard]] const VideoCore::ShaderNotify& ShaderNotify() const {
  161. return *shader_notify;
  162. }
  163. [[nodiscard]] u64 GetTicks() const {
  164. // This values were reversed engineered by fincs from NVN
  165. // The gpu clock is reported in units of 385/625 nanoseconds
  166. constexpr u64 gpu_ticks_num = 384;
  167. constexpr u64 gpu_ticks_den = 625;
  168. u64 nanoseconds = system.CoreTiming().GetGlobalTimeNs().count();
  169. if (Settings::values.use_fast_gpu_time.GetValue()) {
  170. nanoseconds /= 256;
  171. }
  172. const u64 nanoseconds_num = nanoseconds / gpu_ticks_den;
  173. const u64 nanoseconds_rem = nanoseconds % gpu_ticks_den;
  174. return nanoseconds_num * gpu_ticks_num + (nanoseconds_rem * gpu_ticks_num) / gpu_ticks_den;
  175. }
  176. [[nodiscard]] bool IsAsync() const {
  177. return is_async;
  178. }
  179. [[nodiscard]] bool UseNvdec() const {
  180. return use_nvdec;
  181. }
  182. void RendererFrameEndNotify() {
  183. system.GetPerfStats().EndGameFrame();
  184. }
  185. /// Performs any additional setup necessary in order to begin GPU emulation.
  186. /// This can be used to launch any necessary threads and register any necessary
  187. /// core timing events.
  188. void Start() {
  189. gpu_thread.StartThread(*renderer, renderer->Context(), *scheduler);
  190. cpu_context = renderer->GetRenderWindow().CreateSharedContext();
  191. cpu_context->MakeCurrent();
  192. }
  193. void NotifyShutdown() {
  194. std::unique_lock lk{sync_mutex};
  195. shutting_down.store(true, std::memory_order::relaxed);
  196. sync_cv.notify_all();
  197. }
  198. /// Obtain the CPU Context
  199. void ObtainContext() {
  200. cpu_context->MakeCurrent();
  201. }
  202. /// Release the CPU Context
  203. void ReleaseContext() {
  204. cpu_context->DoneCurrent();
  205. }
  206. /// Push GPU command entries to be processed
  207. void PushGPUEntries(s32 channel, Tegra::CommandList&& entries) {
  208. gpu_thread.SubmitList(channel, std::move(entries));
  209. }
  210. /// Push GPU command buffer entries to be processed
  211. void PushCommandBuffer(u32 id, Tegra::ChCommandHeaderList& entries) {
  212. if (!use_nvdec) {
  213. return;
  214. }
  215. if (!cdma_pushers.contains(id)) {
  216. cdma_pushers.insert_or_assign(id, std::make_unique<Tegra::CDmaPusher>(host1x));
  217. }
  218. // SubmitCommandBuffer would make the nvdec operations async, this is not currently working
  219. // TODO(ameerj): RE proper async nvdec operation
  220. // gpu_thread.SubmitCommandBuffer(std::move(entries));
  221. cdma_pushers[id]->ProcessEntries(std::move(entries));
  222. }
  223. /// Frees the CDMAPusher instance to free up resources
  224. void ClearCdmaInstance(u32 id) {
  225. const auto iter = cdma_pushers.find(id);
  226. if (iter != cdma_pushers.end()) {
  227. cdma_pushers.erase(iter);
  228. }
  229. }
  230. /// Swap buffers (render frame)
  231. void SwapBuffers(const Tegra::FramebufferConfig* framebuffer) {
  232. gpu_thread.SwapBuffers(framebuffer);
  233. }
  234. /// Notify rasterizer that any caches of the specified region should be flushed to Switch memory
  235. void FlushRegion(VAddr addr, u64 size) {
  236. gpu_thread.FlushRegion(addr, size);
  237. }
  238. /// Notify rasterizer that any caches of the specified region should be invalidated
  239. void InvalidateRegion(VAddr addr, u64 size) {
  240. gpu_thread.InvalidateRegion(addr, size);
  241. }
  242. /// Notify rasterizer that any caches of the specified region should be flushed and invalidated
  243. void FlushAndInvalidateRegion(VAddr addr, u64 size) {
  244. gpu_thread.FlushAndInvalidateRegion(addr, size);
  245. }
  246. void RequestSwapBuffers(const Tegra::FramebufferConfig* framebuffer,
  247. std::array<Service::Nvidia::NvFence, 4>& fences, size_t num_fences) {
  248. size_t current_request_counter{};
  249. {
  250. std::unique_lock<std::mutex> lk(request_swap_mutex);
  251. if (free_swap_counters.empty()) {
  252. current_request_counter = request_swap_counters.size();
  253. request_swap_counters.emplace_back(num_fences);
  254. } else {
  255. current_request_counter = free_swap_counters.front();
  256. request_swap_counters[current_request_counter] = num_fences;
  257. free_swap_counters.pop_front();
  258. }
  259. }
  260. const auto wait_fence =
  261. RequestSyncOperation([this, current_request_counter, framebuffer, fences, num_fences] {
  262. auto& syncpoint_manager = host1x.GetSyncpointManager();
  263. if (num_fences == 0) {
  264. renderer->SwapBuffers(framebuffer);
  265. }
  266. const auto executer = [this, current_request_counter,
  267. framebuffer_copy = *framebuffer]() {
  268. {
  269. std::unique_lock<std::mutex> lk(request_swap_mutex);
  270. if (--request_swap_counters[current_request_counter] != 0) {
  271. return;
  272. }
  273. free_swap_counters.push_back(current_request_counter);
  274. }
  275. renderer->SwapBuffers(&framebuffer_copy);
  276. };
  277. for (size_t i = 0; i < num_fences; i++) {
  278. syncpoint_manager.RegisterGuestAction(fences[i].id, fences[i].value, executer);
  279. }
  280. });
  281. gpu_thread.TickGPU();
  282. WaitForSyncOperation(wait_fence);
  283. }
  284. GPU& gpu;
  285. Core::System& system;
  286. Host1x::Host1x& host1x;
  287. std::map<u32, std::unique_ptr<Tegra::CDmaPusher>> cdma_pushers;
  288. std::unique_ptr<VideoCore::RendererBase> renderer;
  289. VideoCore::RasterizerInterface* rasterizer = nullptr;
  290. const bool use_nvdec;
  291. s32 new_channel_id{1};
  292. /// Shader build notifier
  293. std::unique_ptr<VideoCore::ShaderNotify> shader_notify;
  294. /// When true, we are about to shut down emulation session, so terminate outstanding tasks
  295. std::atomic_bool shutting_down{};
  296. std::array<std::atomic<u32>, Service::Nvidia::MaxSyncPoints> syncpoints{};
  297. std::array<std::list<u32>, Service::Nvidia::MaxSyncPoints> syncpt_interrupts;
  298. std::mutex sync_mutex;
  299. std::mutex device_mutex;
  300. std::condition_variable sync_cv;
  301. std::list<std::function<void()>> sync_requests;
  302. std::atomic<u64> current_sync_fence{};
  303. u64 last_sync_fence{};
  304. std::mutex sync_request_mutex;
  305. std::condition_variable sync_request_cv;
  306. const bool is_async;
  307. VideoCommon::GPUThread::ThreadManager gpu_thread;
  308. std::unique_ptr<Core::Frontend::GraphicsContext> cpu_context;
  309. std::unique_ptr<Tegra::Control::Scheduler> scheduler;
  310. std::unordered_map<s32, std::shared_ptr<Tegra::Control::ChannelState>> channels;
  311. Tegra::Control::ChannelState* current_channel;
  312. s32 bound_channel{-1};
  313. std::deque<size_t> free_swap_counters;
  314. std::deque<size_t> request_swap_counters;
  315. std::mutex request_swap_mutex;
  316. };
  317. GPU::GPU(Core::System& system, bool is_async, bool use_nvdec)
  318. : impl{std::make_unique<Impl>(*this, system, is_async, use_nvdec)} {}
  319. GPU::~GPU() = default;
  320. std::shared_ptr<Control::ChannelState> GPU::AllocateChannel() {
  321. return impl->AllocateChannel();
  322. }
  323. void GPU::InitChannel(Control::ChannelState& to_init) {
  324. impl->InitChannel(to_init);
  325. }
  326. void GPU::BindChannel(s32 channel_id) {
  327. impl->BindChannel(channel_id);
  328. }
  329. void GPU::ReleaseChannel(Control::ChannelState& to_release) {
  330. impl->ReleaseChannel(to_release);
  331. }
  332. void GPU::InitAddressSpace(Tegra::MemoryManager& memory_manager) {
  333. impl->InitAddressSpace(memory_manager);
  334. }
  335. void GPU::BindRenderer(std::unique_ptr<VideoCore::RendererBase> renderer) {
  336. impl->BindRenderer(std::move(renderer));
  337. }
  338. void GPU::FlushCommands() {
  339. impl->FlushCommands();
  340. }
  341. void GPU::InvalidateGPUCache() {
  342. impl->InvalidateGPUCache();
  343. }
  344. void GPU::OnCommandListEnd() {
  345. impl->OnCommandListEnd();
  346. }
  347. u64 GPU::RequestFlush(VAddr addr, std::size_t size) {
  348. return impl->RequestSyncOperation(
  349. [this, addr, size]() { impl->rasterizer->FlushRegion(addr, size); });
  350. }
  351. u64 GPU::CurrentSyncRequestFence() const {
  352. return impl->CurrentSyncRequestFence();
  353. }
  354. void GPU::WaitForSyncOperation(u64 fence) {
  355. return impl->WaitForSyncOperation(fence);
  356. }
  357. void GPU::TickWork() {
  358. impl->TickWork();
  359. }
  360. /// Gets a mutable reference to the Host1x interface
  361. Host1x::Host1x& GPU::Host1x() {
  362. return impl->host1x;
  363. }
  364. /// Gets an immutable reference to the Host1x interface.
  365. const Host1x::Host1x& GPU::Host1x() const {
  366. return impl->host1x;
  367. }
  368. Engines::Maxwell3D& GPU::Maxwell3D() {
  369. return impl->Maxwell3D();
  370. }
  371. const Engines::Maxwell3D& GPU::Maxwell3D() const {
  372. return impl->Maxwell3D();
  373. }
  374. Engines::KeplerCompute& GPU::KeplerCompute() {
  375. return impl->KeplerCompute();
  376. }
  377. const Engines::KeplerCompute& GPU::KeplerCompute() const {
  378. return impl->KeplerCompute();
  379. }
  380. Tegra::DmaPusher& GPU::DmaPusher() {
  381. return impl->DmaPusher();
  382. }
  383. const Tegra::DmaPusher& GPU::DmaPusher() const {
  384. return impl->DmaPusher();
  385. }
  386. VideoCore::RendererBase& GPU::Renderer() {
  387. return impl->Renderer();
  388. }
  389. const VideoCore::RendererBase& GPU::Renderer() const {
  390. return impl->Renderer();
  391. }
  392. VideoCore::ShaderNotify& GPU::ShaderNotify() {
  393. return impl->ShaderNotify();
  394. }
  395. const VideoCore::ShaderNotify& GPU::ShaderNotify() const {
  396. return impl->ShaderNotify();
  397. }
  398. void GPU::RequestSwapBuffers(const Tegra::FramebufferConfig* framebuffer,
  399. std::array<Service::Nvidia::NvFence, 4>& fences, size_t num_fences) {
  400. impl->RequestSwapBuffers(framebuffer, fences, num_fences);
  401. }
  402. u64 GPU::GetTicks() const {
  403. return impl->GetTicks();
  404. }
  405. bool GPU::IsAsync() const {
  406. return impl->IsAsync();
  407. }
  408. bool GPU::UseNvdec() const {
  409. return impl->UseNvdec();
  410. }
  411. void GPU::RendererFrameEndNotify() {
  412. impl->RendererFrameEndNotify();
  413. }
  414. void GPU::Start() {
  415. impl->Start();
  416. }
  417. void GPU::NotifyShutdown() {
  418. impl->NotifyShutdown();
  419. }
  420. void GPU::ObtainContext() {
  421. impl->ObtainContext();
  422. }
  423. void GPU::ReleaseContext() {
  424. impl->ReleaseContext();
  425. }
  426. void GPU::PushGPUEntries(s32 channel, Tegra::CommandList&& entries) {
  427. impl->PushGPUEntries(channel, std::move(entries));
  428. }
  429. void GPU::PushCommandBuffer(u32 id, Tegra::ChCommandHeaderList& entries) {
  430. impl->PushCommandBuffer(id, entries);
  431. }
  432. void GPU::ClearCdmaInstance(u32 id) {
  433. impl->ClearCdmaInstance(id);
  434. }
  435. void GPU::SwapBuffers(const Tegra::FramebufferConfig* framebuffer) {
  436. impl->SwapBuffers(framebuffer);
  437. }
  438. void GPU::FlushRegion(VAddr addr, u64 size) {
  439. impl->FlushRegion(addr, size);
  440. }
  441. void GPU::InvalidateRegion(VAddr addr, u64 size) {
  442. impl->InvalidateRegion(addr, size);
  443. }
  444. void GPU::FlushAndInvalidateRegion(VAddr addr, u64 size) {
  445. impl->FlushAndInvalidateRegion(addr, size);
  446. }
  447. } // namespace Tegra