gpu.cpp 17 KB

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