#include "graphics/host_gpu/renderer/renderContext.h" #include "common/assert.h" #include "common/emulatorConfig.h" #include "common/logging/log.h" #include "graphics/guest_gpu/graphicsRun.h" #include "graphics/presentation/videoOut.h" #include "libs/errno.h" #include namespace Libs::Graphics { RenderContext::RenderContext(GraphicContext& graphics, const std::filesystem::path& shader_store) : m_graphics(graphics), m_render_executor(*this), m_command_scheduler(*this, graphics), m_descriptor_heap(graphics, m_command_scheduler.GetMasterSemaphore()), m_sampler_cache(graphics), m_buffer_cache(graphics, m_command_scheduler, m_page_manager, m_texture_cache), m_texture_cache(graphics, m_command_scheduler, m_page_manager, m_buffer_cache), m_image_heap(*this, m_page_manager), m_pipeline_cache(graphics, &m_image_heap, shader_store.empty() ? ShaderStorePath(&graphics) : shader_store), m_occlusion_queries(graphics, m_command_scheduler), m_skip_redundant_unmap_drains(Config::SkipRedundantUnmapDrainsEnabled()) { EXIT_NOT_IMPLEMENTED(!Common::Thread::IsMainThread()); if (graphics.ray_query_enabled) { m_ray_tracing = std::make_unique(*this); } } RenderContext::~RenderContext() { ShutdownGpu(); m_command_scheduler.Shutdown(); } void RenderContext::InitializeGpu(VideoOut::VideoOutDriver* video_out) { EXIT_IF(m_gpu != nullptr); m_video_out = video_out; m_gpu = std::make_unique(*this); } void RenderContext::ShutdownGpu() { if (m_gpu != nullptr) { m_gpu->Shutdown(); m_gpu.reset(); } if (m_video_out != nullptr) { if (m_command_scheduler.Active()) { m_command_scheduler.Finish(); } m_command_scheduler.DrainPriorityOperations(); m_video_out = nullptr; } } GuestGpu& RenderContext::GetGpu() const { EXIT_IF(m_gpu == nullptr); return *m_gpu; } VideoOut::VideoOutDriver& RenderContext::GetVideoOut() const { EXIT_IF(m_video_out == nullptr); return *m_video_out; } bool RenderContext::HandleFault(PageFaultAccess access, uint64_t fault_vaddr) noexcept { // The host reports the faulting byte, not the instruction's access width. Both caches // resolve its page; guessing a width can cross the end of a valid guest mapping. constexpr uint64_t fault_size = 1; if (!IsMapped(fault_vaddr, fault_size)) { return false; } // The access retries once the image write-backs over its page land. if (WaitWriteBacks(fault_vaddr, fault_size)) { return true; } if (access == PageFaultAccess::Write) { m_buffer_cache.InvalidateMemory(fault_vaddr, fault_size); m_texture_cache.InvalidateMemory(fault_vaddr, fault_size); m_image_heap.InvalidateMemory(fault_vaddr, fault_size); } else { m_buffer_cache.ReadMemory(fault_vaddr, fault_size); } return true; } bool RenderContext::WaitWriteBacks(uint64_t vaddr, uint64_t size) { const auto tick = m_texture_cache.WriteBackTick(vaddr, size); if (tick == 0) { return false; } // The GPU thread can fault inside a draw, so it submits without running deferred operations. if (GuestGpu::IsGpuThread()) { m_command_scheduler.Wait(tick); } else if (tick == m_command_scheduler.CurrentTick()) { GetGpu().SendCommandSync([this, tick] { m_command_scheduler.Wait(tick); }); } m_command_scheduler.WaitPriorityOperations(tick); return true; } bool RenderContext::InvalidateMemory(uint64_t vaddr, uint64_t size) { // Host I/O into the range, even one running past its mapping, would fail on its inaccessible // pages, and a later write-back would overwrite it. (void)WaitWriteBacks(vaddr, size); if (!IsMapped(vaddr, size)) { return false; } m_buffer_cache.InvalidateMemory(vaddr, size); m_texture_cache.InvalidateMemory(vaddr, size); m_image_heap.InvalidateMemory(vaddr, size); return true; } bool RenderContext::InvalidateSequentialWrite(uint64_t vaddr, uint64_t size) { if (!IsMapped(vaddr, size)) { return false; } m_buffer_cache.InvalidateMemory(vaddr, size); m_texture_cache.InvalidateSequentialWrite(vaddr, size); m_image_heap.InvalidateMemory(vaddr, size); return true; } bool RenderContext::IsMapped(uint64_t vaddr, uint64_t size) const noexcept { if (!GuestRange {vaddr, size}.Valid()) { return false; } std::shared_lock lock(m_mapped_ranges_mutex); return m_mapped_ranges.Contains(vaddr, size); } bool RenderContext::IsAnyMapped(uint64_t vaddr, uint64_t size) const noexcept { if (!GuestRange {vaddr, size}.Valid()) { return false; } std::shared_lock lock(m_mapped_ranges_mutex); return m_mapped_ranges.Intersects(vaddr, size); } // Reports whether the whole range is suspended. bool RenderContext::IsSuspended(uint64_t vaddr, uint64_t size) const { std::shared_lock lock(m_mapped_ranges_mutex); return m_suspended.Contains(vaddr, size); } // Records a range as mapped and queues its BDA sync. Suspended parts are cancelled first. void RenderContext::MapMemory(uint64_t vaddr, uint64_t size) { // A new mapping over suspended memory cannot be a verified resume, so its cache is dropped // first. The cancel needs the GPU thread, which the guest thread calling here is not. Checking // and then cancelling is race free because the kernel holds g_memory_operation_mutex and only // the GPU thread writes m_suspended. bool overlaps_suspended = false; { std::shared_lock lock(m_mapped_ranges_mutex); overlaps_suspended = m_suspended.Intersects(vaddr, size); } if (overlaps_suspended) { m_suspended_map_cancels.fetch_add(1, std::memory_order_relaxed); LOGF("GPU: map over suspended memory cancelled its cache, addr=0x%016" PRIx64 " size=0x%016" PRIx64 "\n", vaddr, size); CancelSuspendedMemory(vaddr, size); } std::lock_guard lock(m_mapped_ranges_mutex); m_mapped_ranges.Add(vaddr, size); m_buffer_cache.QueueBdaSync(vaddr, size); } /// Returns true when the range is not mapped and has no image, GPU-written byte or priority /// operation. bool RenderContext::IsUnmapDrainRedundant(uint64_t vaddr, uint64_t size) { { std::shared_lock lock(m_mapped_ranges_mutex); if (m_mapped_ranges.Intersects(vaddr, size)) { return false; } } // The GPU-dirty checks are a conservative choice. The flush in InvalidateMemory waits on // its own before it publishes, and the view is already gone for an unmapped range. Only the // pair of checks is tested, not each one alone. return !m_texture_cache.IsRegionRegistered(vaddr, size) && !m_buffer_cache.HasGpuDirtyBytes(vaddr, size) && !m_buffer_cache.IsRegionGpuModified(vaddr, size) && !m_command_scheduler.HasPendingPriorityOperations(); } /// Returns true when unmapping the range must first drain the GPU queue and priority operations. bool RenderContext::NeedsUnmapDrain(uint64_t vaddr, uint64_t size) { if (!m_command_scheduler.Active()) { return false; } // Check cache ownership on the GPU thread. Guest-memory callbacks can still // access a range with no cached data, so they must finish before it is unmapped. if (!m_buffer_cache.IsRegionRegistered(vaddr, size) && !m_texture_cache.IsRegionRegistered(vaddr, size) && !m_command_scheduler.HasPendingPriorityOperations()) { return false; } // A fixed remap unmaps the range a second time right after the release did. By then the // host view is gone and no image or GPU-written byte remains, so a full GPU drain would // wait on nothing that depends on the view. Buffers stay registered after an unmap, which // is why the registration check above cannot tell the two apart. The deferred // non-priority operations that a drain would also run only release resources, apart from // the page-fault scan that may look up a buffer, and that lookup is already unguarded // for ranges that never had a buffer. return !(m_skip_redundant_unmap_drains && IsUnmapDrainRedundant(vaddr, size)); } // Runs a memory operation on the GPU thread, or inline when shutdown has closed the command lane. void RenderContext::RunMemoryOperation(const char* name, uint64_t vaddr, uint64_t size, Common::UniqueFunction&& operation) { if (CommandScheduler::InDeferredOperation()) { EXIT("unsupported memory %s from an asynchronous GPU completion, " "addr=0x%016" PRIx64 " size=0x%016" PRIx64 "\n", name, vaddr, size); } // Shutdown still owns the GPU while queued rendering drains, but its command lane no // longer accepts external work. Use the guest GPU's state for the teardown route. if (m_gpu == nullptr || m_gpu->IsStopping()) { operation(); return; } m_gpu->SendCommandSync(std::move(operation)); } // Waits for native work and priority operations when the range has cached data or work is pending. void RenderContext::DrainBeforeUnmap(uint64_t vaddr, uint64_t size) { if (NeedsUnmapDrain(vaddr, size)) { const auto tick = m_command_scheduler.CurrentTick(); m_command_scheduler.Finish(); m_command_scheduler.WaitPriorityOperations(tick); } } // Unmaps a range and fully invalidates its caches, including any suspension over it. void RenderContext::UnmapMemory(uint64_t vaddr, uint64_t size) { RunMemoryOperation("unmap", vaddr, size, [this, vaddr, size] { UnmapNow(vaddr, size); }); } // The body of UnmapMemory, shared with a suspend that finds shutdown already under way. void RenderContext::UnmapNow(uint64_t vaddr, uint64_t size) { DrainBeforeUnmap(vaddr, size); m_buffer_cache.InvalidateMemory(vaddr, size); m_texture_cache.UnmapMemory(vaddr, size); m_image_heap.UnmapMemory(vaddr, size); std::lock_guard lock(m_mapped_ranges_mutex); m_mapped_ranges.Subtract(vaddr, size); // Nothing is suspended unless a release was suspended earlier, so this is usually a no-op. // The invalidate above already covered any suspended cache here. m_suspended.Subtract(vaddr, size); } // Unmaps a range like UnmapMemory but keeps its buffer cache valid for a later exact resume. void RenderContext::SuspendMemory(uint64_t vaddr, uint64_t size) { // Suspending at shutdown is pointless, and the waits it needs are unsafe off the GPU thread. if (m_gpu == nullptr || m_gpu->IsStopping()) { UnmapMemory(vaddr, size); return; } RunMemoryOperation("suspend", vaddr, size, [this, vaddr, size] { SuspendNow(vaddr, size); }); } // The body of SuspendMemory. Shutdown can begin after SuspendMemory's own check. The body then // runs on the calling thread with the GPU stopping or already gone, or on the GPU thread while // queued commands drain. A suspension during teardown is pointless and its waits are unsafe off // the GPU thread, so in every such case it unmaps the way UnmapMemory does. void RenderContext::SuspendNow(uint64_t vaddr, uint64_t size) { if (m_gpu == nullptr || m_gpu->IsStopping()) { UnmapNow(vaddr, size); return; } DrainBeforeUnmap(vaddr, size); // The host view is about to go away, so GPU-written bytes must reach it first. m_buffer_cache.FlushGpuDirtyForSuspend(vaddr, size); m_texture_cache.UnmapMemory(vaddr, size); m_image_heap.UnmapMemory(vaddr, size); std::lock_guard lock(m_mapped_ranges_mutex); m_mapped_ranges.Subtract(vaddr, size); m_suspended.Add(vaddr, size); } // Maps a suspended range back after the same memory was mapped at the same address read-write. void RenderContext::ResumeMemory(uint64_t vaddr, uint64_t size) { RunMemoryOperation("resume", vaddr, size, [this, vaddr, size] { { std::lock_guard lock(m_mapped_ranges_mutex); if (!m_suspended.Contains(vaddr, size)) { EXIT("RenderContext: resume of memory that is not suspended, " "addr=0x%016" PRIx64 " size=0x%016" PRIx64 "\n", vaddr, size); } m_suspended.Subtract(vaddr, size); m_mapped_ranges.Add(vaddr, size); } // The fresh view is read-write, so watched pages need their protection back before the // guest can run. This must not hold the address-space mutex, and no lock is held here. m_page_manager.ReapplyProtection(vaddr, size); m_buffer_cache.QueueBdaSync(vaddr, size); }); } // Applies the full invalidation that an UnmapMemory would have done to the suspended parts. // Normally the range is unmapped, so protection changes skip it. As a last resort the MapMemory // safety net also calls this with a fresh view already present, where the invalidate may loosen // a guest read-only mapping to read-write. The kernel cancels earlier than that. void RenderContext::CancelSuspendedMemory(uint64_t vaddr, uint64_t size) { RunMemoryOperation("cancel", vaddr, size, [this, vaddr, size] { std::vector> parts; { std::shared_lock lock(m_mapped_ranges_mutex); m_suspended.ForEachInRange(vaddr, size, [&parts](uint64_t begin, uint64_t end) { parts.emplace_back(begin, end - begin); }); } for (const auto& [begin, bytes]: parts) { m_buffer_cache.InvalidateMemory(begin, bytes); } std::lock_guard lock(m_mapped_ranges_mutex); m_suspended.Subtract(vaddr, size); }); } void RenderContext::PrepareBda() { [[maybe_unused]] static const bool logged = [] { Log::WriteToConsoleAndLog("GPU: using buffer device address (BDA) shader memory access.\n"); return true; }(); std::shared_lock lock(m_mapped_ranges_mutex); m_buffer_cache.SynchronizeBda(m_mapped_ranges); m_fault_process_pending = true; } void RenderContext::RunGarbageCollector() { if (m_fault_process_pending) { m_fault_process_pending = false; m_buffer_cache.ProcessFaultBuffer(); } m_image_heap.RunGarbageCollector(); m_texture_cache.ProcessDownloadImages(); m_texture_cache.RunGarbageCollector(); m_buffer_cache.RunGarbageCollector(); if (m_ray_tracing) { m_ray_tracing->RunGarbageCollector(); } } void RenderContext::AddInterruptEq(LibKernel::EventQueue::KernelEqueue eq, int event_id) { Common::LockGuard lock(m_interrupt_mutex); auto it = std::find_if( m_interrupt_eqs.begin(), m_interrupt_eqs.end(), [eq, event_id](const auto& entry) { return entry.eq == eq && entry.event_id == event_id; }); if (it != m_interrupt_eqs.end()) { return; } m_interrupt_eqs.push_back({eq, event_id}); } void RenderContext::DeleteInterruptEq(LibKernel::EventQueue::KernelEqueue eq, int event_id) { Common::LockGuard lock(m_interrupt_mutex); auto it = std::find_if( m_interrupt_eqs.begin(), m_interrupt_eqs.end(), [eq, event_id](const auto& entry) { return entry.eq == eq && entry.event_id == event_id; }); if (it == m_interrupt_eqs.end()) { return; } m_interrupt_eqs.erase(it); } void RenderContext::TriggerInterrupt(int event_id, uint32_t context_id) { std::vector registrations; { Common::LockGuard lock(m_interrupt_mutex); for (const auto& registration: m_interrupt_eqs) { if (registration.event_id == event_id) { registrations.push_back(registration); } } } for (const auto& registration: registrations) { const auto result = LibKernel::EventQueue::KernelTriggerEvent( registration.eq, static_cast(registration.event_id), LibKernel::EventQueue::KERNEL_EVFILT_GRAPHICS, reinterpret_cast(static_cast(context_id))); if (result == LibKernel::KERNEL_ERROR_EBADF || result == LibKernel::KERNEL_ERROR_ENOENT) { DeleteInterruptEq(registration.eq, registration.event_id); continue; } EXIT_NOT_IMPLEMENTED(result != OK); } } } // namespace Libs::Graphics