gpu.cpp 18 KB

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