gpu.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568
  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. rasterizer->InvalidateGPUCache();
  84. }
  85. /// Signal the ending of command list.
  86. void OnCommandListEnd() {
  87. rasterizer->ReleaseFences();
  88. }
  89. /// Request a host GPU memory flush from the CPU.
  90. template <typename Func>
  91. [[nodiscard]] u64 RequestSyncOperation(Func&& action) {
  92. std::unique_lock lck{sync_request_mutex};
  93. const u64 fence = ++last_sync_fence;
  94. sync_requests.emplace_back(action);
  95. return fence;
  96. }
  97. /// Obtains current flush request fence id.
  98. [[nodiscard]] u64 CurrentSyncRequestFence() const {
  99. return current_sync_fence.load(std::memory_order_relaxed);
  100. }
  101. void WaitForSyncOperation(const u64 fence) {
  102. std::unique_lock lck{sync_request_mutex};
  103. sync_request_cv.wait(lck, [this, fence] { return CurrentSyncRequestFence() >= fence; });
  104. }
  105. /// Tick pending requests within the GPU.
  106. void TickWork() {
  107. std::unique_lock lck{sync_request_mutex};
  108. while (!sync_requests.empty()) {
  109. auto request = std::move(sync_requests.front());
  110. sync_requests.pop_front();
  111. sync_request_mutex.unlock();
  112. request();
  113. current_sync_fence.fetch_add(1, std::memory_order_release);
  114. sync_request_mutex.lock();
  115. sync_request_cv.notify_all();
  116. }
  117. }
  118. /// Returns a reference to the Maxwell3D GPU engine.
  119. [[nodiscard]] Engines::Maxwell3D& Maxwell3D() {
  120. ASSERT(current_channel);
  121. return *current_channel->maxwell_3d;
  122. }
  123. /// Returns a const reference to the Maxwell3D GPU engine.
  124. [[nodiscard]] const Engines::Maxwell3D& Maxwell3D() const {
  125. ASSERT(current_channel);
  126. return *current_channel->maxwell_3d;
  127. }
  128. /// Returns a reference to the KeplerCompute GPU engine.
  129. [[nodiscard]] Engines::KeplerCompute& KeplerCompute() {
  130. ASSERT(current_channel);
  131. return *current_channel->kepler_compute;
  132. }
  133. /// Returns a reference to the KeplerCompute GPU engine.
  134. [[nodiscard]] const Engines::KeplerCompute& KeplerCompute() const {
  135. ASSERT(current_channel);
  136. return *current_channel->kepler_compute;
  137. }
  138. /// Returns a reference to the GPU DMA pusher.
  139. [[nodiscard]] Tegra::DmaPusher& DmaPusher() {
  140. ASSERT(current_channel);
  141. return *current_channel->dma_pusher;
  142. }
  143. /// Returns a const reference to the GPU DMA pusher.
  144. [[nodiscard]] const Tegra::DmaPusher& DmaPusher() const {
  145. ASSERT(current_channel);
  146. return *current_channel->dma_pusher;
  147. }
  148. /// Returns a reference to the underlying renderer.
  149. [[nodiscard]] VideoCore::RendererBase& Renderer() {
  150. return *renderer;
  151. }
  152. /// Returns a const reference to the underlying renderer.
  153. [[nodiscard]] const VideoCore::RendererBase& Renderer() const {
  154. return *renderer;
  155. }
  156. /// Returns a reference to the shader notifier.
  157. [[nodiscard]] VideoCore::ShaderNotify& ShaderNotify() {
  158. return *shader_notify;
  159. }
  160. /// Returns a const reference to the shader notifier.
  161. [[nodiscard]] const VideoCore::ShaderNotify& ShaderNotify() const {
  162. return *shader_notify;
  163. }
  164. [[nodiscard]] u64 GetTicks() const {
  165. u64 gpu_tick = system.CoreTiming().GetGPUTicks();
  166. if (Settings::values.use_fast_gpu_time.GetValue()) {
  167. gpu_tick /= 256;
  168. }
  169. return gpu_tick;
  170. }
  171. [[nodiscard]] bool IsAsync() const {
  172. return is_async;
  173. }
  174. [[nodiscard]] bool UseNvdec() const {
  175. return use_nvdec;
  176. }
  177. void RendererFrameEndNotify() {
  178. system.GetPerfStats().EndGameFrame();
  179. }
  180. /// Performs any additional setup necessary in order to begin GPU emulation.
  181. /// This can be used to launch any necessary threads and register any necessary
  182. /// core timing events.
  183. void Start() {
  184. gpu_thread.StartThread(*renderer, renderer->Context(), *scheduler);
  185. }
  186. void NotifyShutdown() {
  187. std::unique_lock lk{sync_mutex};
  188. shutting_down.store(true, std::memory_order::relaxed);
  189. sync_cv.notify_all();
  190. }
  191. /// Obtain the CPU Context
  192. void ObtainContext() {
  193. if (!cpu_context) {
  194. cpu_context = renderer->GetRenderWindow().CreateSharedContext();
  195. }
  196. cpu_context->MakeCurrent();
  197. }
  198. /// Release the CPU Context
  199. void ReleaseContext() {
  200. cpu_context->DoneCurrent();
  201. }
  202. /// Push GPU command entries to be processed
  203. void PushGPUEntries(s32 channel, Tegra::CommandList&& entries) {
  204. gpu_thread.SubmitList(channel, std::move(entries));
  205. }
  206. /// Push GPU command buffer entries to be processed
  207. void PushCommandBuffer(u32 id, Tegra::ChCommandHeaderList& entries) {
  208. if (!use_nvdec) {
  209. return;
  210. }
  211. if (!cdma_pushers.contains(id)) {
  212. cdma_pushers.insert_or_assign(id, std::make_unique<Tegra::CDmaPusher>(host1x));
  213. }
  214. // SubmitCommandBuffer would make the nvdec operations async, this is not currently working
  215. // TODO(ameerj): RE proper async nvdec operation
  216. // gpu_thread.SubmitCommandBuffer(std::move(entries));
  217. cdma_pushers[id]->ProcessEntries(std::move(entries));
  218. }
  219. /// Frees the CDMAPusher instance to free up resources
  220. void ClearCdmaInstance(u32 id) {
  221. const auto iter = cdma_pushers.find(id);
  222. if (iter != cdma_pushers.end()) {
  223. cdma_pushers.erase(iter);
  224. }
  225. }
  226. /// Swap buffers (render frame)
  227. void SwapBuffers(const Tegra::FramebufferConfig* framebuffer) {
  228. gpu_thread.SwapBuffers(framebuffer);
  229. }
  230. /// Notify rasterizer that any caches of the specified region should be flushed to Switch memory
  231. void FlushRegion(VAddr addr, u64 size) {
  232. gpu_thread.FlushRegion(addr, size);
  233. }
  234. VideoCore::RasterizerDownloadArea OnCPURead(VAddr addr, u64 size) {
  235. auto raster_area = rasterizer->GetFlushArea(addr, size);
  236. if (raster_area.preemtive) {
  237. return raster_area;
  238. }
  239. raster_area.preemtive = true;
  240. const u64 fence = RequestSyncOperation([this, &raster_area]() {
  241. rasterizer->FlushRegion(raster_area.start_address,
  242. raster_area.end_address - raster_area.start_address);
  243. });
  244. gpu_thread.TickGPU();
  245. WaitForSyncOperation(fence);
  246. return raster_area;
  247. }
  248. /// Notify rasterizer that any caches of the specified region should be invalidated
  249. void InvalidateRegion(VAddr addr, u64 size) {
  250. gpu_thread.InvalidateRegion(addr, size);
  251. }
  252. /// Notify rasterizer that any caches of the specified region should be flushed and invalidated
  253. void FlushAndInvalidateRegion(VAddr addr, u64 size) {
  254. gpu_thread.FlushAndInvalidateRegion(addr, size);
  255. }
  256. void RequestSwapBuffers(const Tegra::FramebufferConfig* framebuffer,
  257. std::array<Service::Nvidia::NvFence, 4>& fences, size_t num_fences) {
  258. size_t current_request_counter{};
  259. {
  260. std::unique_lock<std::mutex> lk(request_swap_mutex);
  261. if (free_swap_counters.empty()) {
  262. current_request_counter = request_swap_counters.size();
  263. request_swap_counters.emplace_back(num_fences);
  264. } else {
  265. current_request_counter = free_swap_counters.front();
  266. request_swap_counters[current_request_counter] = num_fences;
  267. free_swap_counters.pop_front();
  268. }
  269. }
  270. const auto wait_fence =
  271. RequestSyncOperation([this, current_request_counter, framebuffer, fences, num_fences] {
  272. auto& syncpoint_manager = host1x.GetSyncpointManager();
  273. if (num_fences == 0) {
  274. renderer->SwapBuffers(framebuffer);
  275. }
  276. const auto executer = [this, current_request_counter,
  277. framebuffer_copy = *framebuffer]() {
  278. {
  279. std::unique_lock<std::mutex> lk(request_swap_mutex);
  280. if (--request_swap_counters[current_request_counter] != 0) {
  281. return;
  282. }
  283. free_swap_counters.push_back(current_request_counter);
  284. }
  285. renderer->SwapBuffers(&framebuffer_copy);
  286. };
  287. for (size_t i = 0; i < num_fences; i++) {
  288. syncpoint_manager.RegisterGuestAction(fences[i].id, fences[i].value, executer);
  289. }
  290. });
  291. gpu_thread.TickGPU();
  292. WaitForSyncOperation(wait_fence);
  293. }
  294. GPU& gpu;
  295. Core::System& system;
  296. Host1x::Host1x& host1x;
  297. std::map<u32, std::unique_ptr<Tegra::CDmaPusher>> cdma_pushers;
  298. std::unique_ptr<VideoCore::RendererBase> renderer;
  299. VideoCore::RasterizerInterface* rasterizer = nullptr;
  300. const bool use_nvdec;
  301. s32 new_channel_id{1};
  302. /// Shader build notifier
  303. std::unique_ptr<VideoCore::ShaderNotify> shader_notify;
  304. /// When true, we are about to shut down emulation session, so terminate outstanding tasks
  305. std::atomic_bool shutting_down{};
  306. std::array<std::atomic<u32>, Service::Nvidia::MaxSyncPoints> syncpoints{};
  307. std::array<std::list<u32>, Service::Nvidia::MaxSyncPoints> syncpt_interrupts;
  308. std::mutex sync_mutex;
  309. std::mutex device_mutex;
  310. std::condition_variable sync_cv;
  311. std::list<std::function<void()>> sync_requests;
  312. std::atomic<u64> current_sync_fence{};
  313. u64 last_sync_fence{};
  314. std::mutex sync_request_mutex;
  315. std::condition_variable sync_request_cv;
  316. const bool is_async;
  317. VideoCommon::GPUThread::ThreadManager gpu_thread;
  318. std::unique_ptr<Core::Frontend::GraphicsContext> cpu_context;
  319. std::unique_ptr<Tegra::Control::Scheduler> scheduler;
  320. std::unordered_map<s32, std::shared_ptr<Tegra::Control::ChannelState>> channels;
  321. Tegra::Control::ChannelState* current_channel;
  322. s32 bound_channel{-1};
  323. std::deque<size_t> free_swap_counters;
  324. std::deque<size_t> request_swap_counters;
  325. std::mutex request_swap_mutex;
  326. };
  327. GPU::GPU(Core::System& system, bool is_async, bool use_nvdec)
  328. : impl{std::make_unique<Impl>(*this, system, is_async, use_nvdec)} {}
  329. GPU::~GPU() = default;
  330. std::shared_ptr<Control::ChannelState> GPU::AllocateChannel() {
  331. return impl->AllocateChannel();
  332. }
  333. void GPU::InitChannel(Control::ChannelState& to_init) {
  334. impl->InitChannel(to_init);
  335. }
  336. void GPU::BindChannel(s32 channel_id) {
  337. impl->BindChannel(channel_id);
  338. }
  339. void GPU::ReleaseChannel(Control::ChannelState& to_release) {
  340. impl->ReleaseChannel(to_release);
  341. }
  342. void GPU::InitAddressSpace(Tegra::MemoryManager& memory_manager) {
  343. impl->InitAddressSpace(memory_manager);
  344. }
  345. void GPU::BindRenderer(std::unique_ptr<VideoCore::RendererBase> renderer) {
  346. impl->BindRenderer(std::move(renderer));
  347. }
  348. void GPU::FlushCommands() {
  349. impl->FlushCommands();
  350. }
  351. void GPU::InvalidateGPUCache() {
  352. impl->InvalidateGPUCache();
  353. }
  354. void GPU::OnCommandListEnd() {
  355. impl->OnCommandListEnd();
  356. }
  357. u64 GPU::RequestFlush(VAddr addr, std::size_t size) {
  358. return impl->RequestSyncOperation(
  359. [this, addr, size]() { impl->rasterizer->FlushRegion(addr, size); });
  360. }
  361. u64 GPU::CurrentSyncRequestFence() const {
  362. return impl->CurrentSyncRequestFence();
  363. }
  364. void GPU::WaitForSyncOperation(u64 fence) {
  365. return impl->WaitForSyncOperation(fence);
  366. }
  367. void GPU::TickWork() {
  368. impl->TickWork();
  369. }
  370. /// Gets a mutable reference to the Host1x interface
  371. Host1x::Host1x& GPU::Host1x() {
  372. return impl->host1x;
  373. }
  374. /// Gets an immutable reference to the Host1x interface.
  375. const Host1x::Host1x& GPU::Host1x() const {
  376. return impl->host1x;
  377. }
  378. Engines::Maxwell3D& GPU::Maxwell3D() {
  379. return impl->Maxwell3D();
  380. }
  381. const Engines::Maxwell3D& GPU::Maxwell3D() const {
  382. return impl->Maxwell3D();
  383. }
  384. Engines::KeplerCompute& GPU::KeplerCompute() {
  385. return impl->KeplerCompute();
  386. }
  387. const Engines::KeplerCompute& GPU::KeplerCompute() const {
  388. return impl->KeplerCompute();
  389. }
  390. Tegra::DmaPusher& GPU::DmaPusher() {
  391. return impl->DmaPusher();
  392. }
  393. const Tegra::DmaPusher& GPU::DmaPusher() const {
  394. return impl->DmaPusher();
  395. }
  396. VideoCore::RendererBase& GPU::Renderer() {
  397. return impl->Renderer();
  398. }
  399. const VideoCore::RendererBase& GPU::Renderer() const {
  400. return impl->Renderer();
  401. }
  402. VideoCore::ShaderNotify& GPU::ShaderNotify() {
  403. return impl->ShaderNotify();
  404. }
  405. const VideoCore::ShaderNotify& GPU::ShaderNotify() const {
  406. return impl->ShaderNotify();
  407. }
  408. void GPU::RequestSwapBuffers(const Tegra::FramebufferConfig* framebuffer,
  409. std::array<Service::Nvidia::NvFence, 4>& fences, size_t num_fences) {
  410. impl->RequestSwapBuffers(framebuffer, fences, num_fences);
  411. }
  412. u64 GPU::GetTicks() const {
  413. return impl->GetTicks();
  414. }
  415. bool GPU::IsAsync() const {
  416. return impl->IsAsync();
  417. }
  418. bool GPU::UseNvdec() const {
  419. return impl->UseNvdec();
  420. }
  421. void GPU::RendererFrameEndNotify() {
  422. impl->RendererFrameEndNotify();
  423. }
  424. void GPU::Start() {
  425. impl->Start();
  426. }
  427. void GPU::NotifyShutdown() {
  428. impl->NotifyShutdown();
  429. }
  430. void GPU::ObtainContext() {
  431. impl->ObtainContext();
  432. }
  433. void GPU::ReleaseContext() {
  434. impl->ReleaseContext();
  435. }
  436. void GPU::PushGPUEntries(s32 channel, Tegra::CommandList&& entries) {
  437. impl->PushGPUEntries(channel, std::move(entries));
  438. }
  439. void GPU::PushCommandBuffer(u32 id, Tegra::ChCommandHeaderList& entries) {
  440. impl->PushCommandBuffer(id, entries);
  441. }
  442. void GPU::ClearCdmaInstance(u32 id) {
  443. impl->ClearCdmaInstance(id);
  444. }
  445. void GPU::SwapBuffers(const Tegra::FramebufferConfig* framebuffer) {
  446. impl->SwapBuffers(framebuffer);
  447. }
  448. VideoCore::RasterizerDownloadArea GPU::OnCPURead(VAddr addr, u64 size) {
  449. return impl->OnCPURead(addr, size);
  450. }
  451. void GPU::FlushRegion(VAddr addr, u64 size) {
  452. impl->FlushRegion(addr, size);
  453. }
  454. void GPU::InvalidateRegion(VAddr addr, u64 size) {
  455. impl->InvalidateRegion(addr, size);
  456. }
  457. void GPU::FlushAndInvalidateRegion(VAddr addr, u64 size) {
  458. impl->FlushAndInvalidateRegion(addr, size);
  459. }
  460. } // namespace Tegra