gpu.cpp 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912
  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/hardware_interrupt_manager.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/dma_pusher.h"
  20. #include "video_core/engines/fermi_2d.h"
  21. #include "video_core/engines/kepler_compute.h"
  22. #include "video_core/engines/kepler_memory.h"
  23. #include "video_core/engines/maxwell_3d.h"
  24. #include "video_core/engines/maxwell_dma.h"
  25. #include "video_core/gpu.h"
  26. #include "video_core/gpu_thread.h"
  27. #include "video_core/memory_manager.h"
  28. #include "video_core/renderer_base.h"
  29. #include "video_core/shader_notify.h"
  30. namespace Tegra {
  31. MICROPROFILE_DEFINE(GPU_wait, "GPU", "Wait for the GPU", MP_RGB(128, 128, 192));
  32. struct GPU::Impl {
  33. explicit Impl(GPU& gpu_, Core::System& system_, bool is_async_, bool use_nvdec_)
  34. : gpu{gpu_}, system{system_}, memory_manager{std::make_unique<Tegra::MemoryManager>(
  35. system)},
  36. dma_pusher{std::make_unique<Tegra::DmaPusher>(system, gpu)}, use_nvdec{use_nvdec_},
  37. maxwell_3d{std::make_unique<Engines::Maxwell3D>(system, *memory_manager)},
  38. fermi_2d{std::make_unique<Engines::Fermi2D>()},
  39. kepler_compute{std::make_unique<Engines::KeplerCompute>(system, *memory_manager)},
  40. maxwell_dma{std::make_unique<Engines::MaxwellDMA>(system, *memory_manager)},
  41. kepler_memory{std::make_unique<Engines::KeplerMemory>(system, *memory_manager)},
  42. shader_notify{std::make_unique<VideoCore::ShaderNotify>()}, is_async{is_async_},
  43. gpu_thread{system_, is_async_} {}
  44. ~Impl() = default;
  45. /// Binds a renderer to the GPU.
  46. void BindRenderer(std::unique_ptr<VideoCore::RendererBase> renderer_) {
  47. renderer = std::move(renderer_);
  48. rasterizer = renderer->ReadRasterizer();
  49. memory_manager->BindRasterizer(rasterizer);
  50. maxwell_3d->BindRasterizer(rasterizer);
  51. fermi_2d->BindRasterizer(rasterizer);
  52. kepler_compute->BindRasterizer(rasterizer);
  53. kepler_memory->BindRasterizer(rasterizer);
  54. maxwell_dma->BindRasterizer(rasterizer);
  55. }
  56. /// Calls a GPU method.
  57. void CallMethod(const GPU::MethodCall& method_call) {
  58. LOG_TRACE(HW_GPU, "Processing method {:08X} on subchannel {}", method_call.method,
  59. method_call.subchannel);
  60. ASSERT(method_call.subchannel < bound_engines.size());
  61. if (ExecuteMethodOnEngine(method_call.method)) {
  62. CallEngineMethod(method_call);
  63. } else {
  64. CallPullerMethod(method_call);
  65. }
  66. }
  67. /// Calls a GPU multivalue method.
  68. void CallMultiMethod(u32 method, u32 subchannel, const u32* base_start, u32 amount,
  69. u32 methods_pending) {
  70. LOG_TRACE(HW_GPU, "Processing method {:08X} on subchannel {}", method, subchannel);
  71. ASSERT(subchannel < bound_engines.size());
  72. if (ExecuteMethodOnEngine(method)) {
  73. CallEngineMultiMethod(method, subchannel, base_start, amount, methods_pending);
  74. } else {
  75. for (std::size_t i = 0; i < amount; i++) {
  76. CallPullerMethod(GPU::MethodCall{
  77. method,
  78. base_start[i],
  79. subchannel,
  80. methods_pending - static_cast<u32>(i),
  81. });
  82. }
  83. }
  84. }
  85. /// Flush all current written commands into the host GPU for execution.
  86. void FlushCommands() {
  87. rasterizer->FlushCommands();
  88. }
  89. /// Synchronizes CPU writes with Host GPU memory.
  90. void SyncGuestHost() {
  91. rasterizer->SyncGuestHost();
  92. }
  93. /// Signal the ending of command list.
  94. void OnCommandListEnd() {
  95. if (is_async) {
  96. // This command only applies to asynchronous GPU mode
  97. gpu_thread.OnCommandListEnd();
  98. }
  99. }
  100. /// Request a host GPU memory flush from the CPU.
  101. [[nodiscard]] u64 RequestFlush(VAddr addr, std::size_t size) {
  102. std::unique_lock lck{flush_request_mutex};
  103. const u64 fence = ++last_flush_fence;
  104. flush_requests.emplace_back(fence, addr, size);
  105. return fence;
  106. }
  107. /// Obtains current flush request fence id.
  108. [[nodiscard]] u64 CurrentFlushRequestFence() const {
  109. return current_flush_fence.load(std::memory_order_relaxed);
  110. }
  111. /// Tick pending requests within the GPU.
  112. void TickWork() {
  113. std::unique_lock lck{flush_request_mutex};
  114. while (!flush_requests.empty()) {
  115. auto& request = flush_requests.front();
  116. const u64 fence = request.fence;
  117. const VAddr addr = request.addr;
  118. const std::size_t size = request.size;
  119. flush_requests.pop_front();
  120. flush_request_mutex.unlock();
  121. rasterizer->FlushRegion(addr, size);
  122. current_flush_fence.store(fence);
  123. flush_request_mutex.lock();
  124. }
  125. }
  126. /// Returns a reference to the Maxwell3D GPU engine.
  127. [[nodiscard]] Engines::Maxwell3D& Maxwell3D() {
  128. return *maxwell_3d;
  129. }
  130. /// Returns a const reference to the Maxwell3D GPU engine.
  131. [[nodiscard]] const Engines::Maxwell3D& Maxwell3D() const {
  132. return *maxwell_3d;
  133. }
  134. /// Returns a reference to the KeplerCompute GPU engine.
  135. [[nodiscard]] Engines::KeplerCompute& KeplerCompute() {
  136. return *kepler_compute;
  137. }
  138. /// Returns a reference to the KeplerCompute GPU engine.
  139. [[nodiscard]] const Engines::KeplerCompute& KeplerCompute() const {
  140. return *kepler_compute;
  141. }
  142. /// Returns a reference to the GPU memory manager.
  143. [[nodiscard]] Tegra::MemoryManager& MemoryManager() {
  144. return *memory_manager;
  145. }
  146. /// Returns a const reference to the GPU memory manager.
  147. [[nodiscard]] const Tegra::MemoryManager& MemoryManager() const {
  148. return *memory_manager;
  149. }
  150. /// Returns a reference to the GPU DMA pusher.
  151. [[nodiscard]] Tegra::DmaPusher& DmaPusher() {
  152. return *dma_pusher;
  153. }
  154. /// Returns a const reference to the GPU DMA pusher.
  155. [[nodiscard]] const Tegra::DmaPusher& DmaPusher() const {
  156. return *dma_pusher;
  157. }
  158. /// Returns a reference to the underlying renderer.
  159. [[nodiscard]] VideoCore::RendererBase& Renderer() {
  160. return *renderer;
  161. }
  162. /// Returns a const reference to the underlying renderer.
  163. [[nodiscard]] const VideoCore::RendererBase& Renderer() const {
  164. return *renderer;
  165. }
  166. /// Returns a reference to the shader notifier.
  167. [[nodiscard]] VideoCore::ShaderNotify& ShaderNotify() {
  168. return *shader_notify;
  169. }
  170. /// Returns a const reference to the shader notifier.
  171. [[nodiscard]] const VideoCore::ShaderNotify& ShaderNotify() const {
  172. return *shader_notify;
  173. }
  174. /// Allows the CPU/NvFlinger to wait on the GPU before presenting a frame.
  175. void WaitFence(u32 syncpoint_id, u32 value) {
  176. // Synced GPU, is always in sync
  177. if (!is_async) {
  178. return;
  179. }
  180. if (syncpoint_id == UINT32_MAX) {
  181. // TODO: Research what this does.
  182. LOG_ERROR(HW_GPU, "Waiting for syncpoint -1 not implemented");
  183. return;
  184. }
  185. MICROPROFILE_SCOPE(GPU_wait);
  186. std::unique_lock lock{sync_mutex};
  187. sync_cv.wait(lock, [=, this] {
  188. if (shutting_down.load(std::memory_order_relaxed)) {
  189. // We're shutting down, ensure no threads continue to wait for the next syncpoint
  190. return true;
  191. }
  192. return syncpoints.at(syncpoint_id).load() >= value;
  193. });
  194. }
  195. void IncrementSyncPoint(u32 syncpoint_id) {
  196. auto& syncpoint = syncpoints.at(syncpoint_id);
  197. syncpoint++;
  198. std::scoped_lock lock{sync_mutex};
  199. sync_cv.notify_all();
  200. auto& interrupt = syncpt_interrupts.at(syncpoint_id);
  201. if (!interrupt.empty()) {
  202. u32 value = syncpoint.load();
  203. auto it = interrupt.begin();
  204. while (it != interrupt.end()) {
  205. if (value >= *it) {
  206. TriggerCpuInterrupt(syncpoint_id, *it);
  207. it = interrupt.erase(it);
  208. continue;
  209. }
  210. it++;
  211. }
  212. }
  213. }
  214. [[nodiscard]] u32 GetSyncpointValue(u32 syncpoint_id) const {
  215. return syncpoints.at(syncpoint_id).load();
  216. }
  217. void RegisterSyncptInterrupt(u32 syncpoint_id, u32 value) {
  218. std::scoped_lock lock{sync_mutex};
  219. auto& interrupt = syncpt_interrupts.at(syncpoint_id);
  220. bool contains = std::any_of(interrupt.begin(), interrupt.end(),
  221. [value](u32 in_value) { return in_value == value; });
  222. if (contains) {
  223. return;
  224. }
  225. interrupt.emplace_back(value);
  226. }
  227. [[nodiscard]] bool CancelSyncptInterrupt(u32 syncpoint_id, u32 value) {
  228. std::scoped_lock lock{sync_mutex};
  229. auto& interrupt = syncpt_interrupts.at(syncpoint_id);
  230. const auto iter =
  231. std::find_if(interrupt.begin(), interrupt.end(),
  232. [value](u32 interrupt_value) { return value == interrupt_value; });
  233. if (iter == interrupt.end()) {
  234. return false;
  235. }
  236. interrupt.erase(iter);
  237. return true;
  238. }
  239. [[nodiscard]] u64 GetTicks() const {
  240. // This values were reversed engineered by fincs from NVN
  241. // The gpu clock is reported in units of 385/625 nanoseconds
  242. constexpr u64 gpu_ticks_num = 384;
  243. constexpr u64 gpu_ticks_den = 625;
  244. u64 nanoseconds = system.CoreTiming().GetGlobalTimeNs().count();
  245. if (Settings::values.use_fast_gpu_time.GetValue()) {
  246. nanoseconds /= 256;
  247. }
  248. const u64 nanoseconds_num = nanoseconds / gpu_ticks_den;
  249. const u64 nanoseconds_rem = nanoseconds % gpu_ticks_den;
  250. return nanoseconds_num * gpu_ticks_num + (nanoseconds_rem * gpu_ticks_num) / gpu_ticks_den;
  251. }
  252. [[nodiscard]] bool IsAsync() const {
  253. return is_async;
  254. }
  255. [[nodiscard]] bool UseNvdec() const {
  256. return use_nvdec;
  257. }
  258. void RendererFrameEndNotify() {
  259. system.GetPerfStats().EndGameFrame();
  260. }
  261. /// Performs any additional setup necessary in order to begin GPU emulation.
  262. /// This can be used to launch any necessary threads and register any necessary
  263. /// core timing events.
  264. void Start() {
  265. gpu_thread.StartThread(*renderer, renderer->Context(), *dma_pusher);
  266. cpu_context = renderer->GetRenderWindow().CreateSharedContext();
  267. cpu_context->MakeCurrent();
  268. }
  269. void NotifyShutdown() {
  270. std::unique_lock lk{sync_mutex};
  271. shutting_down.store(true, std::memory_order::relaxed);
  272. sync_cv.notify_all();
  273. }
  274. /// Obtain the CPU Context
  275. void ObtainContext() {
  276. cpu_context->MakeCurrent();
  277. }
  278. /// Release the CPU Context
  279. void ReleaseContext() {
  280. cpu_context->DoneCurrent();
  281. }
  282. /// Push GPU command entries to be processed
  283. void PushGPUEntries(Tegra::CommandList&& entries) {
  284. gpu_thread.SubmitList(std::move(entries));
  285. }
  286. /// Push GPU command buffer entries to be processed
  287. void PushCommandBuffer(u32 id, Tegra::ChCommandHeaderList& entries) {
  288. if (!use_nvdec) {
  289. return;
  290. }
  291. if (!cdma_pushers.contains(id)) {
  292. cdma_pushers.insert_or_assign(id, std::make_unique<Tegra::CDmaPusher>(gpu));
  293. }
  294. // SubmitCommandBuffer would make the nvdec operations async, this is not currently working
  295. // TODO(ameerj): RE proper async nvdec operation
  296. // gpu_thread.SubmitCommandBuffer(std::move(entries));
  297. cdma_pushers[id]->ProcessEntries(std::move(entries));
  298. }
  299. /// Frees the CDMAPusher instance to free up resources
  300. void ClearCdmaInstance(u32 id) {
  301. const auto iter = cdma_pushers.find(id);
  302. if (iter != cdma_pushers.end()) {
  303. cdma_pushers.erase(iter);
  304. }
  305. }
  306. /// Swap buffers (render frame)
  307. void SwapBuffers(const Tegra::FramebufferConfig* framebuffer) {
  308. gpu_thread.SwapBuffers(framebuffer);
  309. }
  310. /// Notify rasterizer that any caches of the specified region should be flushed to Switch memory
  311. void FlushRegion(VAddr addr, u64 size) {
  312. gpu_thread.FlushRegion(addr, size);
  313. }
  314. /// Notify rasterizer that any caches of the specified region should be invalidated
  315. void InvalidateRegion(VAddr addr, u64 size) {
  316. gpu_thread.InvalidateRegion(addr, size);
  317. }
  318. /// Notify rasterizer that any caches of the specified region should be flushed and invalidated
  319. void FlushAndInvalidateRegion(VAddr addr, u64 size) {
  320. gpu_thread.FlushAndInvalidateRegion(addr, size);
  321. }
  322. void TriggerCpuInterrupt(u32 syncpoint_id, u32 value) const {
  323. auto& interrupt_manager = system.InterruptManager();
  324. interrupt_manager.GPUInterruptSyncpt(syncpoint_id, value);
  325. }
  326. void ProcessBindMethod(const GPU::MethodCall& method_call) {
  327. // Bind the current subchannel to the desired engine id.
  328. LOG_DEBUG(HW_GPU, "Binding subchannel {} to engine {}", method_call.subchannel,
  329. method_call.argument);
  330. const auto engine_id = static_cast<EngineID>(method_call.argument);
  331. bound_engines[method_call.subchannel] = static_cast<EngineID>(engine_id);
  332. switch (engine_id) {
  333. case EngineID::FERMI_TWOD_A:
  334. dma_pusher->BindSubchannel(fermi_2d.get(), method_call.subchannel);
  335. break;
  336. case EngineID::MAXWELL_B:
  337. dma_pusher->BindSubchannel(maxwell_3d.get(), method_call.subchannel);
  338. break;
  339. case EngineID::KEPLER_COMPUTE_B:
  340. dma_pusher->BindSubchannel(kepler_compute.get(), method_call.subchannel);
  341. break;
  342. case EngineID::MAXWELL_DMA_COPY_A:
  343. dma_pusher->BindSubchannel(maxwell_dma.get(), method_call.subchannel);
  344. break;
  345. case EngineID::KEPLER_INLINE_TO_MEMORY_B:
  346. dma_pusher->BindSubchannel(kepler_memory.get(), method_call.subchannel);
  347. break;
  348. default:
  349. UNIMPLEMENTED_MSG("Unimplemented engine {:04X}", engine_id);
  350. }
  351. }
  352. void ProcessFenceActionMethod() {
  353. switch (regs.fence_action.op) {
  354. case GPU::FenceOperation::Acquire:
  355. WaitFence(regs.fence_action.syncpoint_id, regs.fence_value);
  356. break;
  357. case GPU::FenceOperation::Increment:
  358. IncrementSyncPoint(regs.fence_action.syncpoint_id);
  359. break;
  360. default:
  361. UNIMPLEMENTED_MSG("Unimplemented operation {}", regs.fence_action.op.Value());
  362. }
  363. }
  364. void ProcessWaitForInterruptMethod() {
  365. // TODO(bunnei) ImplementMe
  366. LOG_WARNING(HW_GPU, "(STUBBED) called");
  367. }
  368. void ProcessSemaphoreTriggerMethod() {
  369. const auto semaphoreOperationMask = 0xF;
  370. const auto op =
  371. static_cast<GpuSemaphoreOperation>(regs.semaphore_trigger & semaphoreOperationMask);
  372. if (op == GpuSemaphoreOperation::WriteLong) {
  373. struct Block {
  374. u32 sequence;
  375. u32 zeros = 0;
  376. u64 timestamp;
  377. };
  378. Block block{};
  379. block.sequence = regs.semaphore_sequence;
  380. // TODO(Kmather73): Generate a real GPU timestamp and write it here instead of
  381. // CoreTiming
  382. block.timestamp = GetTicks();
  383. memory_manager->WriteBlock(regs.semaphore_address.SemaphoreAddress(), &block,
  384. sizeof(block));
  385. } else {
  386. const u32 word{memory_manager->Read<u32>(regs.semaphore_address.SemaphoreAddress())};
  387. if ((op == GpuSemaphoreOperation::AcquireEqual && word == regs.semaphore_sequence) ||
  388. (op == GpuSemaphoreOperation::AcquireGequal &&
  389. static_cast<s32>(word - regs.semaphore_sequence) > 0) ||
  390. (op == GpuSemaphoreOperation::AcquireMask && (word & regs.semaphore_sequence))) {
  391. // Nothing to do in this case
  392. } else {
  393. regs.acquire_source = true;
  394. regs.acquire_value = regs.semaphore_sequence;
  395. if (op == GpuSemaphoreOperation::AcquireEqual) {
  396. regs.acquire_active = true;
  397. regs.acquire_mode = false;
  398. } else if (op == GpuSemaphoreOperation::AcquireGequal) {
  399. regs.acquire_active = true;
  400. regs.acquire_mode = true;
  401. } else if (op == GpuSemaphoreOperation::AcquireMask) {
  402. // TODO(kemathe) The acquire mask operation waits for a value that, ANDed with
  403. // semaphore_sequence, gives a non-0 result
  404. LOG_ERROR(HW_GPU, "Invalid semaphore operation AcquireMask not implemented");
  405. } else {
  406. LOG_ERROR(HW_GPU, "Invalid semaphore operation");
  407. }
  408. }
  409. }
  410. }
  411. void ProcessSemaphoreRelease() {
  412. memory_manager->Write<u32>(regs.semaphore_address.SemaphoreAddress(),
  413. regs.semaphore_release);
  414. }
  415. void ProcessSemaphoreAcquire() {
  416. const u32 word = memory_manager->Read<u32>(regs.semaphore_address.SemaphoreAddress());
  417. const auto value = regs.semaphore_acquire;
  418. if (word != value) {
  419. regs.acquire_active = true;
  420. regs.acquire_value = value;
  421. // TODO(kemathe73) figure out how to do the acquire_timeout
  422. regs.acquire_mode = false;
  423. regs.acquire_source = false;
  424. }
  425. }
  426. /// Calls a GPU puller method.
  427. void CallPullerMethod(const GPU::MethodCall& method_call) {
  428. regs.reg_array[method_call.method] = method_call.argument;
  429. const auto method = static_cast<BufferMethods>(method_call.method);
  430. switch (method) {
  431. case BufferMethods::BindObject: {
  432. ProcessBindMethod(method_call);
  433. break;
  434. }
  435. case BufferMethods::Nop:
  436. case BufferMethods::SemaphoreAddressHigh:
  437. case BufferMethods::SemaphoreAddressLow:
  438. case BufferMethods::SemaphoreSequence:
  439. break;
  440. case BufferMethods::UnkCacheFlush:
  441. rasterizer->SyncGuestHost();
  442. break;
  443. case BufferMethods::WrcacheFlush:
  444. rasterizer->SignalReference();
  445. break;
  446. case BufferMethods::FenceValue:
  447. break;
  448. case BufferMethods::RefCnt:
  449. rasterizer->SignalReference();
  450. break;
  451. case BufferMethods::FenceAction:
  452. ProcessFenceActionMethod();
  453. break;
  454. case BufferMethods::WaitForInterrupt:
  455. rasterizer->WaitForIdle();
  456. break;
  457. case BufferMethods::SemaphoreTrigger: {
  458. ProcessSemaphoreTriggerMethod();
  459. break;
  460. }
  461. case BufferMethods::NotifyIntr: {
  462. // TODO(Kmather73): Research and implement this method.
  463. LOG_ERROR(HW_GPU, "Special puller engine method NotifyIntr not implemented");
  464. break;
  465. }
  466. case BufferMethods::Unk28: {
  467. // TODO(Kmather73): Research and implement this method.
  468. LOG_ERROR(HW_GPU, "Special puller engine method Unk28 not implemented");
  469. break;
  470. }
  471. case BufferMethods::SemaphoreAcquire: {
  472. ProcessSemaphoreAcquire();
  473. break;
  474. }
  475. case BufferMethods::SemaphoreRelease: {
  476. ProcessSemaphoreRelease();
  477. break;
  478. }
  479. case BufferMethods::Yield: {
  480. // TODO(Kmather73): Research and implement this method.
  481. LOG_ERROR(HW_GPU, "Special puller engine method Yield not implemented");
  482. break;
  483. }
  484. default:
  485. LOG_ERROR(HW_GPU, "Special puller engine method {:X} not implemented", method);
  486. break;
  487. }
  488. }
  489. /// Calls a GPU engine method.
  490. void CallEngineMethod(const GPU::MethodCall& method_call) {
  491. const EngineID engine = bound_engines[method_call.subchannel];
  492. switch (engine) {
  493. case EngineID::FERMI_TWOD_A:
  494. fermi_2d->CallMethod(method_call.method, method_call.argument,
  495. method_call.IsLastCall());
  496. break;
  497. case EngineID::MAXWELL_B:
  498. maxwell_3d->CallMethod(method_call.method, method_call.argument,
  499. method_call.IsLastCall());
  500. break;
  501. case EngineID::KEPLER_COMPUTE_B:
  502. kepler_compute->CallMethod(method_call.method, method_call.argument,
  503. method_call.IsLastCall());
  504. break;
  505. case EngineID::MAXWELL_DMA_COPY_A:
  506. maxwell_dma->CallMethod(method_call.method, method_call.argument,
  507. method_call.IsLastCall());
  508. break;
  509. case EngineID::KEPLER_INLINE_TO_MEMORY_B:
  510. kepler_memory->CallMethod(method_call.method, method_call.argument,
  511. method_call.IsLastCall());
  512. break;
  513. default:
  514. UNIMPLEMENTED_MSG("Unimplemented engine");
  515. }
  516. }
  517. /// Calls a GPU engine multivalue method.
  518. void CallEngineMultiMethod(u32 method, u32 subchannel, const u32* base_start, u32 amount,
  519. u32 methods_pending) {
  520. const EngineID engine = bound_engines[subchannel];
  521. switch (engine) {
  522. case EngineID::FERMI_TWOD_A:
  523. fermi_2d->CallMultiMethod(method, base_start, amount, methods_pending);
  524. break;
  525. case EngineID::MAXWELL_B:
  526. maxwell_3d->CallMultiMethod(method, base_start, amount, methods_pending);
  527. break;
  528. case EngineID::KEPLER_COMPUTE_B:
  529. kepler_compute->CallMultiMethod(method, base_start, amount, methods_pending);
  530. break;
  531. case EngineID::MAXWELL_DMA_COPY_A:
  532. maxwell_dma->CallMultiMethod(method, base_start, amount, methods_pending);
  533. break;
  534. case EngineID::KEPLER_INLINE_TO_MEMORY_B:
  535. kepler_memory->CallMultiMethod(method, base_start, amount, methods_pending);
  536. break;
  537. default:
  538. UNIMPLEMENTED_MSG("Unimplemented engine");
  539. }
  540. }
  541. /// Determines where the method should be executed.
  542. [[nodiscard]] bool ExecuteMethodOnEngine(u32 method) {
  543. const auto buffer_method = static_cast<BufferMethods>(method);
  544. return buffer_method >= BufferMethods::NonPullerMethods;
  545. }
  546. struct Regs {
  547. static constexpr size_t NUM_REGS = 0x40;
  548. union {
  549. struct {
  550. INSERT_PADDING_WORDS_NOINIT(0x4);
  551. struct {
  552. u32 address_high;
  553. u32 address_low;
  554. [[nodiscard]] GPUVAddr SemaphoreAddress() const {
  555. return static_cast<GPUVAddr>((static_cast<GPUVAddr>(address_high) << 32) |
  556. address_low);
  557. }
  558. } semaphore_address;
  559. u32 semaphore_sequence;
  560. u32 semaphore_trigger;
  561. INSERT_PADDING_WORDS_NOINIT(0xC);
  562. // The pusher and the puller share the reference counter, the pusher only has read
  563. // access
  564. u32 reference_count;
  565. INSERT_PADDING_WORDS_NOINIT(0x5);
  566. u32 semaphore_acquire;
  567. u32 semaphore_release;
  568. u32 fence_value;
  569. GPU::FenceAction fence_action;
  570. INSERT_PADDING_WORDS_NOINIT(0xE2);
  571. // Puller state
  572. u32 acquire_mode;
  573. u32 acquire_source;
  574. u32 acquire_active;
  575. u32 acquire_timeout;
  576. u32 acquire_value;
  577. };
  578. std::array<u32, NUM_REGS> reg_array;
  579. };
  580. } regs{};
  581. GPU& gpu;
  582. Core::System& system;
  583. std::unique_ptr<Tegra::MemoryManager> memory_manager;
  584. std::unique_ptr<Tegra::DmaPusher> dma_pusher;
  585. std::map<u32, std::unique_ptr<Tegra::CDmaPusher>> cdma_pushers;
  586. std::unique_ptr<VideoCore::RendererBase> renderer;
  587. VideoCore::RasterizerInterface* rasterizer = nullptr;
  588. const bool use_nvdec;
  589. /// Mapping of command subchannels to their bound engine ids
  590. std::array<EngineID, 8> bound_engines{};
  591. /// 3D engine
  592. std::unique_ptr<Engines::Maxwell3D> maxwell_3d;
  593. /// 2D engine
  594. std::unique_ptr<Engines::Fermi2D> fermi_2d;
  595. /// Compute engine
  596. std::unique_ptr<Engines::KeplerCompute> kepler_compute;
  597. /// DMA engine
  598. std::unique_ptr<Engines::MaxwellDMA> maxwell_dma;
  599. /// Inline memory engine
  600. std::unique_ptr<Engines::KeplerMemory> kepler_memory;
  601. /// Shader build notifier
  602. std::unique_ptr<VideoCore::ShaderNotify> shader_notify;
  603. /// When true, we are about to shut down emulation session, so terminate outstanding tasks
  604. std::atomic_bool shutting_down{};
  605. std::array<std::atomic<u32>, Service::Nvidia::MaxSyncPoints> syncpoints{};
  606. std::array<std::list<u32>, Service::Nvidia::MaxSyncPoints> syncpt_interrupts;
  607. std::mutex sync_mutex;
  608. std::mutex device_mutex;
  609. std::condition_variable sync_cv;
  610. struct FlushRequest {
  611. explicit FlushRequest(u64 fence_, VAddr addr_, std::size_t size_)
  612. : fence{fence_}, addr{addr_}, size{size_} {}
  613. u64 fence;
  614. VAddr addr;
  615. std::size_t size;
  616. };
  617. std::list<FlushRequest> flush_requests;
  618. std::atomic<u64> current_flush_fence{};
  619. u64 last_flush_fence{};
  620. std::mutex flush_request_mutex;
  621. const bool is_async;
  622. VideoCommon::GPUThread::ThreadManager gpu_thread;
  623. std::unique_ptr<Core::Frontend::GraphicsContext> cpu_context;
  624. #define ASSERT_REG_POSITION(field_name, position) \
  625. static_assert(offsetof(Regs, field_name) == position * 4, \
  626. "Field " #field_name " has invalid position")
  627. ASSERT_REG_POSITION(semaphore_address, 0x4);
  628. ASSERT_REG_POSITION(semaphore_sequence, 0x6);
  629. ASSERT_REG_POSITION(semaphore_trigger, 0x7);
  630. ASSERT_REG_POSITION(reference_count, 0x14);
  631. ASSERT_REG_POSITION(semaphore_acquire, 0x1A);
  632. ASSERT_REG_POSITION(semaphore_release, 0x1B);
  633. ASSERT_REG_POSITION(fence_value, 0x1C);
  634. ASSERT_REG_POSITION(fence_action, 0x1D);
  635. ASSERT_REG_POSITION(acquire_mode, 0x100);
  636. ASSERT_REG_POSITION(acquire_source, 0x101);
  637. ASSERT_REG_POSITION(acquire_active, 0x102);
  638. ASSERT_REG_POSITION(acquire_timeout, 0x103);
  639. ASSERT_REG_POSITION(acquire_value, 0x104);
  640. #undef ASSERT_REG_POSITION
  641. enum class GpuSemaphoreOperation {
  642. AcquireEqual = 0x1,
  643. WriteLong = 0x2,
  644. AcquireGequal = 0x4,
  645. AcquireMask = 0x8,
  646. };
  647. };
  648. GPU::GPU(Core::System& system, bool is_async, bool use_nvdec)
  649. : impl{std::make_unique<Impl>(*this, system, is_async, use_nvdec)} {}
  650. GPU::~GPU() = default;
  651. void GPU::BindRenderer(std::unique_ptr<VideoCore::RendererBase> renderer) {
  652. impl->BindRenderer(std::move(renderer));
  653. }
  654. void GPU::CallMethod(const MethodCall& method_call) {
  655. impl->CallMethod(method_call);
  656. }
  657. void GPU::CallMultiMethod(u32 method, u32 subchannel, const u32* base_start, u32 amount,
  658. u32 methods_pending) {
  659. impl->CallMultiMethod(method, subchannel, base_start, amount, methods_pending);
  660. }
  661. void GPU::FlushCommands() {
  662. impl->FlushCommands();
  663. }
  664. void GPU::SyncGuestHost() {
  665. impl->SyncGuestHost();
  666. }
  667. void GPU::OnCommandListEnd() {
  668. impl->OnCommandListEnd();
  669. }
  670. u64 GPU::RequestFlush(VAddr addr, std::size_t size) {
  671. return impl->RequestFlush(addr, size);
  672. }
  673. u64 GPU::CurrentFlushRequestFence() const {
  674. return impl->CurrentFlushRequestFence();
  675. }
  676. void GPU::TickWork() {
  677. impl->TickWork();
  678. }
  679. Engines::Maxwell3D& GPU::Maxwell3D() {
  680. return impl->Maxwell3D();
  681. }
  682. const Engines::Maxwell3D& GPU::Maxwell3D() const {
  683. return impl->Maxwell3D();
  684. }
  685. Engines::KeplerCompute& GPU::KeplerCompute() {
  686. return impl->KeplerCompute();
  687. }
  688. const Engines::KeplerCompute& GPU::KeplerCompute() const {
  689. return impl->KeplerCompute();
  690. }
  691. Tegra::MemoryManager& GPU::MemoryManager() {
  692. return impl->MemoryManager();
  693. }
  694. const Tegra::MemoryManager& GPU::MemoryManager() const {
  695. return impl->MemoryManager();
  696. }
  697. Tegra::DmaPusher& GPU::DmaPusher() {
  698. return impl->DmaPusher();
  699. }
  700. const Tegra::DmaPusher& GPU::DmaPusher() const {
  701. return impl->DmaPusher();
  702. }
  703. VideoCore::RendererBase& GPU::Renderer() {
  704. return impl->Renderer();
  705. }
  706. const VideoCore::RendererBase& GPU::Renderer() const {
  707. return impl->Renderer();
  708. }
  709. VideoCore::ShaderNotify& GPU::ShaderNotify() {
  710. return impl->ShaderNotify();
  711. }
  712. const VideoCore::ShaderNotify& GPU::ShaderNotify() const {
  713. return impl->ShaderNotify();
  714. }
  715. void GPU::WaitFence(u32 syncpoint_id, u32 value) {
  716. impl->WaitFence(syncpoint_id, value);
  717. }
  718. void GPU::IncrementSyncPoint(u32 syncpoint_id) {
  719. impl->IncrementSyncPoint(syncpoint_id);
  720. }
  721. u32 GPU::GetSyncpointValue(u32 syncpoint_id) const {
  722. return impl->GetSyncpointValue(syncpoint_id);
  723. }
  724. void GPU::RegisterSyncptInterrupt(u32 syncpoint_id, u32 value) {
  725. impl->RegisterSyncptInterrupt(syncpoint_id, value);
  726. }
  727. bool GPU::CancelSyncptInterrupt(u32 syncpoint_id, u32 value) {
  728. return impl->CancelSyncptInterrupt(syncpoint_id, value);
  729. }
  730. u64 GPU::GetTicks() const {
  731. return impl->GetTicks();
  732. }
  733. bool GPU::IsAsync() const {
  734. return impl->IsAsync();
  735. }
  736. bool GPU::UseNvdec() const {
  737. return impl->UseNvdec();
  738. }
  739. void GPU::RendererFrameEndNotify() {
  740. impl->RendererFrameEndNotify();
  741. }
  742. void GPU::Start() {
  743. impl->Start();
  744. }
  745. void GPU::NotifyShutdown() {
  746. impl->NotifyShutdown();
  747. }
  748. void GPU::ObtainContext() {
  749. impl->ObtainContext();
  750. }
  751. void GPU::ReleaseContext() {
  752. impl->ReleaseContext();
  753. }
  754. void GPU::PushGPUEntries(Tegra::CommandList&& entries) {
  755. impl->PushGPUEntries(std::move(entries));
  756. }
  757. void GPU::PushCommandBuffer(u32 id, Tegra::ChCommandHeaderList& entries) {
  758. impl->PushCommandBuffer(id, entries);
  759. }
  760. void GPU::ClearCdmaInstance(u32 id) {
  761. impl->ClearCdmaInstance(id);
  762. }
  763. void GPU::SwapBuffers(const Tegra::FramebufferConfig* framebuffer) {
  764. impl->SwapBuffers(framebuffer);
  765. }
  766. void GPU::FlushRegion(VAddr addr, u64 size) {
  767. impl->FlushRegion(addr, size);
  768. }
  769. void GPU::InvalidateRegion(VAddr addr, u64 size) {
  770. impl->InvalidateRegion(addr, size);
  771. }
  772. void GPU::FlushAndInvalidateRegion(VAddr addr, u64 size) {
  773. impl->FlushAndInvalidateRegion(addr, size);
  774. }
  775. } // namespace Tegra