gpu.cpp 31 KB

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