ExtractArgs(EmitContext& ctx, Id offset, u32 mask, u32 count)
} // Anonymous namespace
Id EmitLoadSharedU8(EmitContext& ctx, Id offset) {
+ offset = ctx.BoundSharedOffset(offset, 1);
if (ctx.uses_explicit_workgroup_layout) {
const Id pointer{
ctx.OpAccessChain(ctx.shared_u8, ctx.shared_memory_u8, ctx.u32_zero_value, offset)};
@@ -42,6 +43,7 @@ Id EmitLoadSharedU8(EmitContext& ctx, Id offset) {
}
Id EmitLoadSharedS8(EmitContext& ctx, Id offset) {
+ offset = ctx.BoundSharedOffset(offset, 1);
if (ctx.uses_explicit_workgroup_layout) {
const Id pointer{
ctx.OpAccessChain(ctx.shared_u8, ctx.shared_memory_u8, ctx.u32_zero_value, offset)};
@@ -53,6 +55,7 @@ Id EmitLoadSharedS8(EmitContext& ctx, Id offset) {
}
Id EmitLoadSharedU16(EmitContext& ctx, Id offset) {
+ offset = ctx.BoundSharedOffset(offset, 2);
if (ctx.uses_explicit_workgroup_layout) {
const Id pointer{Pointer(ctx, ctx.shared_u16, ctx.shared_memory_u16, offset, 1)};
return ctx.OpUConvert(ctx.U32[1], ctx.OpLoad(ctx.U16, pointer));
@@ -63,6 +66,7 @@ Id EmitLoadSharedU16(EmitContext& ctx, Id offset) {
}
Id EmitLoadSharedS16(EmitContext& ctx, Id offset) {
+ offset = ctx.BoundSharedOffset(offset, 2);
if (ctx.uses_explicit_workgroup_layout) {
const Id pointer{Pointer(ctx, ctx.shared_u16, ctx.shared_memory_u16, offset, 1)};
return ctx.OpSConvert(ctx.U32[1], ctx.OpLoad(ctx.U16, pointer));
@@ -73,6 +77,7 @@ Id EmitLoadSharedS16(EmitContext& ctx, Id offset) {
}
Id EmitLoadSharedU32(EmitContext& ctx, Id offset) {
+ offset = ctx.BoundSharedOffset(offset, 4);
if (ctx.uses_explicit_workgroup_layout) {
const Id pointer{Pointer(ctx, ctx.shared_u32, ctx.shared_memory_u32, offset, 2)};
return ctx.OpLoad(ctx.U32[1], pointer);
@@ -82,6 +87,7 @@ Id EmitLoadSharedU32(EmitContext& ctx, Id offset) {
}
Id EmitLoadSharedU64(EmitContext& ctx, Id offset) {
+ offset = ctx.BoundSharedOffset(offset, 8);
if (ctx.uses_explicit_workgroup_layout) {
const Id pointer{Pointer(ctx, ctx.shared_u32x2, ctx.shared_memory_u32x2, offset, 3)};
return ctx.OpLoad(ctx.U32[2], pointer);
@@ -97,6 +103,7 @@ Id EmitLoadSharedU64(EmitContext& ctx, Id offset) {
}
Id EmitLoadSharedU128(EmitContext& ctx, Id offset) {
+ offset = ctx.BoundSharedOffset(offset, 16);
if (ctx.uses_explicit_workgroup_layout) {
const Id pointer{Pointer(ctx, ctx.shared_u32x4, ctx.shared_memory_u32x4, offset, 4)};
return ctx.OpLoad(ctx.U32[4], pointer);
@@ -113,6 +120,7 @@ Id EmitLoadSharedU128(EmitContext& ctx, Id offset) {
}
void EmitWriteSharedU8(EmitContext& ctx, Id offset, Id value) {
+ offset = ctx.BoundSharedOffset(offset, 1);
if (ctx.uses_explicit_workgroup_layout) {
const Id pointer{
ctx.OpAccessChain(ctx.shared_u8, ctx.shared_memory_u8, ctx.u32_zero_value, offset)};
@@ -123,6 +131,7 @@ void EmitWriteSharedU8(EmitContext& ctx, Id offset, Id value) {
}
void EmitWriteSharedU16(EmitContext& ctx, Id offset, Id value) {
+ offset = ctx.BoundSharedOffset(offset, 2);
if (ctx.uses_explicit_workgroup_layout) {
const Id pointer{Pointer(ctx, ctx.shared_u16, ctx.shared_memory_u16, offset, 1)};
ctx.OpStore(pointer, ctx.OpUConvert(ctx.U16, value));
@@ -132,6 +141,7 @@ void EmitWriteSharedU16(EmitContext& ctx, Id offset, Id value) {
}
void EmitWriteSharedU32(EmitContext& ctx, Id offset, Id value) {
+ offset = ctx.BoundSharedOffset(offset, 4);
Id pointer{};
if (ctx.uses_explicit_workgroup_layout) {
pointer = Pointer(ctx, ctx.shared_u32, ctx.shared_memory_u32, offset, 2);
@@ -144,6 +154,7 @@ void EmitWriteSharedU32(EmitContext& ctx, Id offset, Id value) {
}
void EmitWriteSharedU64(EmitContext& ctx, Id offset, Id value) {
+ offset = ctx.BoundSharedOffset(offset, 8);
if (ctx.uses_explicit_workgroup_layout) {
const Id pointer{Pointer(ctx, ctx.shared_u32x2, ctx.shared_memory_u32x2, offset, 3)};
ctx.OpStore(pointer, value);
@@ -159,6 +170,7 @@ void EmitWriteSharedU64(EmitContext& ctx, Id offset, Id value) {
}
void EmitWriteSharedU128(EmitContext& ctx, Id offset, Id value) {
+ offset = ctx.BoundSharedOffset(offset, 16);
if (ctx.uses_explicit_workgroup_layout) {
const Id pointer{Pointer(ctx, ctx.shared_u32x4, ctx.shared_memory_u32x4, offset, 4)};
ctx.OpStore(pointer, value);
diff --git a/src/shader_recompiler/backend/spirv/spirv_emit_context.cpp b/src/shader_recompiler/backend/spirv/spirv_emit_context.cpp
index b562e82983..94b878ed51 100644
--- a/src/shader_recompiler/backend/spirv/spirv_emit_context.cpp
+++ b/src/shader_recompiler/backend/spirv/spirv_emit_context.cpp
@@ -600,6 +600,16 @@ void EmitContext::DefineLocalMemory(const IR::Program& program) {
}
}
+Id EmitContext::BoundSharedOffset(Id offset, u32 access_bytes) {
+ if (shared_memory_declared_bytes == 0) {
+ return offset;
+ }
+ const u32 last_valid{shared_memory_declared_bytes > access_bytes
+ ? shared_memory_declared_bytes - access_bytes
+ : 0U};
+ return OpUMin(U32[1], offset, Const(last_valid));
+}
+
void EmitContext::DefineSharedMemory(const IR::Program& program) {
uses_explicit_workgroup_layout =
profile.support_explicit_workgroup_layout &&
@@ -608,8 +618,15 @@ void EmitContext::DefineSharedMemory(const IR::Program& program) {
if (program.shared_memory_size == 0) {
return;
}
+ const u32 device_limit{profile.max_shared_memory_size};
+ const u32 shared_memory_size{device_limit != 0 && program.shared_memory_size > device_limit
+ ? device_limit
+ : program.shared_memory_size};
+ if (shared_memory_size != program.shared_memory_size) {
+ shared_memory_declared_bytes = shared_memory_size;
+ }
const auto make{[&](Id element_type, u32 element_size) {
- const u32 num_elements{Common::DivCeil(program.shared_memory_size, element_size)};
+ const u32 num_elements{Common::DivCeil(shared_memory_size, element_size)};
const Id array_type{TypeArray(element_type, Const(num_elements))};
Decorate(array_type, spv::Decoration::ArrayStride, element_size);
@@ -644,7 +661,7 @@ void EmitContext::DefineSharedMemory(const IR::Program& program) {
std::tie(shared_memory_u32x4, shared_u32x4, std::ignore) = make(U32[4], 16);
return;
}
- const u32 num_elements{Common::DivCeil(program.shared_memory_size, 4U)};
+ const u32 num_elements{Common::DivCeil(shared_memory_size, 4U)};
const Id type{TypeArray(U32[1], Const(num_elements))};
shared_memory_u32_type = TypePointer(spv::StorageClass::Workgroup, type);
diff --git a/src/shader_recompiler/backend/spirv/spirv_emit_context.h b/src/shader_recompiler/backend/spirv/spirv_emit_context.h
index 7edc104708..e186fce4d1 100644
--- a/src/shader_recompiler/backend/spirv/spirv_emit_context.h
+++ b/src/shader_recompiler/backend/spirv/spirv_emit_context.h
@@ -312,6 +312,8 @@ public:
Id local_memory{};
bool uses_explicit_workgroup_layout{};
+ u32 shared_memory_declared_bytes{};
+ [[nodiscard]] Id BoundSharedOffset(Id offset, u32 access_bytes);
Id shared_memory_u8{};
Id shared_memory_u16{};
Id shared_memory_u32{};
diff --git a/src/shader_recompiler/profile.h b/src/shader_recompiler/profile.h
index d2ac480ab8..9dedf556d6 100644
--- a/src/shader_recompiler/profile.h
+++ b/src/shader_recompiler/profile.h
@@ -105,6 +105,9 @@ struct Profile {
u32 gl_max_compute_smem_size{};
+ /// Largest workgroup shared memory allocation the device accepts, 0 when unconstrained
+ u32 max_shared_memory_size{};
+
/// Maxwell and earlier nVidia architectures have broken robust support
bool has_broken_robust{};
diff --git a/src/video_core/buffer_cache/buffer_cache.h b/src/video_core/buffer_cache/buffer_cache.h
index 4c345dd213..b09f26f4f1 100644
--- a/src/video_core/buffer_cache/buffer_cache.h
+++ b/src/video_core/buffer_cache/buffer_cache.h
@@ -78,6 +78,11 @@ void BufferCache::TickFrame() {
return;
}
runtime.TickFrame(slot_buffers);
+ if constexpr (USE_UNIFIED_MEMORY) {
+ if (!unified_written_ranges.Empty() && runtime.KnownGpuTick() >= unified_write_tick) {
+ unified_written_ranges.Clear();
+ }
+ }
// Calculate hits and shots and move hit bits to the right
const u32 hits = std::reduce(channel_state->uniform_cache_hits.begin(),
@@ -565,7 +570,8 @@ void BufferCache
::FlushCachedWrites() {
template
bool BufferCache::HasUncommittedFlushes() const noexcept {
- return !uncommitted_gpu_modified_ranges.Empty() || !committed_gpu_modified_ranges.empty();
+ return !uncommitted_gpu_modified_ranges.Empty() || !committed_gpu_modified_ranges.empty() ||
+ uncommitted_unified_writes;
}
template
@@ -578,14 +584,22 @@ void BufferCache::AccumulateFlushes() {
template
bool BufferCache::ShouldWaitAsyncFlushes() const noexcept {
- return (!async_buffers.empty() && async_buffers.front().has_value());
+ if (async_buffers.empty()) {
+ return false;
+ }
+ return async_buffers.front().has_value() ||
+ !pending_downloads.front().unified_copies.empty() ||
+ pending_downloads.front().unified_writes;
}
template
void BufferCache::CommitAsyncFlushesHigh() {
AccumulateFlushes();
+ const bool unified_writes = uncommitted_unified_writes;
+ uncommitted_unified_writes = false;
if (committed_gpu_modified_ranges.empty()) {
+ pending_downloads.emplace_back(AsyncDownloadBatch{.unified_writes = unified_writes});
async_buffers.emplace_back(std::optional{});
return;
}
@@ -645,27 +659,85 @@ void BufferCache::CommitAsyncFlushesHigh() {
}
committed_gpu_modified_ranges.clear();
if (downloads.empty()) {
+ pending_downloads.emplace_back(AsyncDownloadBatch{.unified_writes = unified_writes});
async_buffers.emplace_back(std::optional{});
return;
}
- auto download_staging = runtime.DownloadStagingBuffer(total_size_bytes, true);
- boost::container::small_vector normalized_copies;
- runtime.PreCopyBarrier();
+
+ struct QueuedUnifiedCopy {
+ u64 window;
+ BufferId buffer_id;
+ boost::container::small_vector copies;
+ };
+
+ AsyncDownloadBatch batch;
+ boost::container::small_vector, 16> staging_downloads;
+ boost::container::small_vector unified_copy_queue;
+ boost::container::small_vector window_ids;
+ UnifiedWindowGroups groups;
+ u64 staging_size_bytes = 0;
for (auto& [copy, buffer_id] : downloads) {
- copy.dst_offset += download_staging.offset;
- const std::array copies{copy};
- BufferCopy second_copy{copy};
Buffer& buffer = slot_buffers[buffer_id];
- second_copy.src_offset = static_cast(buffer.CpuAddr()) + copy.src_offset;
- const DAddr orig_device_addr = static_cast(second_copy.src_offset);
+ const DAddr orig_device_addr = buffer.CpuAddr() + copy.src_offset;
+ bool unified = false;
+ if constexpr (USE_UNIFIED_MEMORY) {
+ if (runtime.HasUnifiedMemory()) {
+ window_ids.clear();
+ groups.clear();
+ unified = ResolveUnifiedWindows(orig_device_addr, copy.src_offset, copy.size,
+ window_ids, groups);
+ }
+ }
+ BufferCopy record{copy};
+ record.src_offset = static_cast(orig_device_addr);
+ if (unified) {
+ async_downloads.Add(orig_device_addr, copy.size);
+ buffer.MarkUsage(copy.src_offset, copy.size);
+ for (size_t i = 0; i < window_ids.size(); ++i) {
+ unified_copy_queue.push_back(
+ QueuedUnifiedCopy{window_ids[i], buffer_id, std::move(groups[i])});
+ }
+ batch.unified_copies.push_back(record);
+ continue;
+ }
+ copy.dst_offset = staging_size_bytes;
+ constexpr u64 align = 64ULL;
+ staging_size_bytes += (copy.size + align - 1) & ~(align - 1ULL);
+ staging_downloads.push_back({copy, buffer_id});
+ }
+
+ std::optional download_staging;
+ if (!staging_downloads.empty()) {
+ download_staging = runtime.DownloadStagingBuffer(staging_size_bytes, true);
+ }
+ runtime.PreCopyBarrier();
+ for (auto& [copy, buffer_id] : staging_downloads) {
+ copy.dst_offset += download_staging->offset;
+ const std::array copies{copy};
+ Buffer& buffer = slot_buffers[buffer_id];
+ BufferCopy record{copy};
+ record.src_offset = static_cast(buffer.CpuAddr()) + copy.src_offset;
+ const DAddr orig_device_addr = static_cast(record.src_offset);
async_downloads.Add(orig_device_addr, copy.size);
buffer.MarkUsage(copy.src_offset, copy.size);
- runtime.CopyBuffer(download_staging.buffer, buffer, copies, false);
- normalized_copies.push_back(second_copy);
+ runtime.CopyBuffer(download_staging->buffer, buffer, copies, false);
+ batch.staging_copies.push_back(record);
+ }
+ if constexpr (USE_UNIFIED_MEMORY) {
+ for (const auto& queued : unified_copy_queue) {
+ const std::span group_span(queued.copies.data(),
+ queued.copies.size());
+ runtime.CopyToUnifiedMemory(queued.window, slot_buffers[queued.buffer_id], group_span);
+ }
+ if (!unified_copy_queue.empty()) {
+ runtime.FlushUnifiedMemoryCopies();
+ runtime.UnifiedMemoryHostBarrier();
+ }
}
runtime.PostCopyBarrier();
- pending_downloads.emplace_back(std::move(normalized_copies));
- async_buffers.emplace_back(download_staging);
+ batch.unified_writes = unified_writes;
+ pending_downloads.emplace_back(std::move(batch));
+ async_buffers.emplace_back(std::move(download_staging));
}
template
@@ -680,32 +752,49 @@ void BufferCache::PopAsyncFlushes() {
template
void BufferCache::PopAsyncBuffers() {
+ struct Writeback {
+ DAddr addr;
+ const u8* src;
+ u64 size;
+ };
+ boost::container::small_vector writebacks;
+ {
+ std::scoped_lock lock{mutex};
if (async_buffers.empty()) {
return;
}
- if (!async_buffers.front().has_value()) {
- async_buffers.pop_front();
- return;
- }
- auto& downloads = pending_downloads.front();
+ auto& batch = pending_downloads.front();
auto& async_buffer = async_buffers.front();
- u8* base = async_buffer->mapped_span.data();
+ if (async_buffer.has_value()) {
+ const u8* base = async_buffer->mapped_span.data();
const size_t base_offset = async_buffer->offset;
- for (const auto& copy : downloads) {
+ for (const auto& copy : batch.staging_copies) {
const DAddr device_addr = static_cast(copy.src_offset);
const u64 dst_offset = copy.dst_offset - base_offset;
const u8* read_mapped_memory = base + dst_offset;
- async_downloads.ForEachInRange(device_addr, copy.size, [&](DAddr start, DAddr end, s32) {
- device_memory.WriteBlockUnsafe(start, &read_mapped_memory[start - device_addr],
- end - start);
+ async_downloads.ForEachInRange(
+ device_addr, copy.size, [&](DAddr start, DAddr end, s32) {
+ writebacks.push_back(
+ {start, &read_mapped_memory[start - device_addr], end - start});
});
async_downloads.Subtract(device_addr, copy.size, [&](DAddr start, DAddr end) {
gpu_modified_ranges.Subtract(start, end - start);
});
}
async_buffers_death_ring.emplace_back(*async_buffer);
+ }
+ for (const auto& copy : batch.unified_copies) {
+ const DAddr device_addr = static_cast(copy.src_offset);
+ async_downloads.Subtract(device_addr, copy.size, [&](DAddr start, DAddr end) {
+ gpu_modified_ranges.Subtract(start, end - start);
+ });
+ }
async_buffers.pop_front();
pending_downloads.pop_front();
+ }
+ for (const auto& wb : writebacks) {
+ device_memory.WriteBlockUnsafe(wb.addr, wb.src, wb.size);
+ }
}
template
@@ -749,6 +838,9 @@ void BufferCache::BindHostIndexBuffer() {
const u32 size = channel_state->index_buffer.size;
const auto& draw_state = maxwell3d->draw_manager.draw_state;
if (draw_state.inline_index_draw_indexes.empty()) {
+ if (BindVirtualIndexBuffer()) {
+ return;
+ }
SynchronizeBuffer(buffer, channel_state->index_buffer.device_addr, size);
} else {
if constexpr (USE_MEMORY_MAPS_FOR_UPLOADS) {
@@ -802,6 +894,7 @@ void BufferCache
::UpdateVertexBufferSlot(u32 index, const Binding& binding) {
enabled_vertex_buffers_mask |= (1u << index);
} else {
enabled_vertex_buffers_mask &= ~(1u << index);
+ virtual_vertex_buffers_mask &= ~(1u << index);
}
}
@@ -834,8 +927,16 @@ void BufferCache
::BindHostVertexBuffers() {
const Binding& binding = VertexBufferSlot(index);
Buffer& buffer = slot_buffers[binding.buffer_id];
TouchBuffer(buffer, binding.buffer_id);
+ if (StageVirtualVertexBuffer(index, binding, false)) {
+ continue;
+ }
+ bool needs_bind = flags[Dirty::VertexBuffer0 + index];
+ if (((virtual_vertex_buffers_mask >> index) & 1) != 0) {
+ virtual_vertex_buffers_mask &= ~(1u << index);
+ needs_bind = true;
+ }
SynchronizeBuffer(buffer, binding.device_addr, binding.size);
- if (!flags[Dirty::VertexBuffer0 + index]) {
+ if (!needs_bind) {
flush_bindings();
continue;
}
@@ -856,6 +957,7 @@ void BufferCache
::BindHostVertexBuffers() {
last_index = index;
}
flush_bindings();
+ BindStagedVertexBuffers();
} else {
HostBindings host_bindings;
bool any_valid{false};
@@ -864,8 +966,17 @@ void BufferCache::BindHostVertexBuffers() {
const Binding& binding = channel_state->vertex_buffers[index];
Buffer& buffer = slot_buffers[binding.buffer_id];
TouchBuffer(buffer, binding.buffer_id);
+ if (((enabled_vertex_buffers_mask >> index) & 1) != 0 &&
+ StageVirtualVertexBuffer(index, binding, true)) {
+ continue;
+ }
+ bool needs_bind = flags[Dirty::VertexBuffer0 + index];
+ if (((virtual_vertex_buffers_mask >> index) & 1) != 0) {
+ virtual_vertex_buffers_mask &= ~(1u << index);
+ needs_bind = true;
+ }
SynchronizeBuffer(buffer, binding.device_addr, binding.size);
- if (!flags[Dirty::VertexBuffer0 + index]) {
+ if (!needs_bind) {
continue;
}
flags[Dirty::VertexBuffer0 + index] = false;
@@ -894,6 +1005,7 @@ void BufferCache
::BindHostVertexBuffers() {
}
runtime.BindVertexBuffers(host_bindings);
}
+ BindStagedVertexBuffers();
}
}
@@ -949,8 +1061,12 @@ void BufferCache
::BindHostGraphicsUniformBuffer(size_t stage, u32 index, u32
}();
const bool use_fast_buffer = needs_alignment_stream
|| (has_host_buffer && size <= channel_state->uniform_buffer_skip_cache_size
- && !memory_tracker.IsRegionGpuModified(device_addr, size));
+ && !memory_tracker.IsRegionGpuModified(device_addr, size)
+ && !HasPendingUnifiedWrites(device_addr, size));
if (use_fast_buffer) {
+ if (needs_alignment_stream) {
+ WaitForUnifiedWrites(device_addr, size);
+ }
if constexpr (IS_OPENGL) {
if (runtime.HasFastBufferSubData()) {
// Fast path for Nvidia
@@ -1046,6 +1162,34 @@ void BufferCache
::ResolveMultiRangeStorage(Binding& binding, bool is_written,
template
bool BufferCache::BindMultiRangeStorage(const Binding& binding, bool is_written,
std::span pool) {
+ if constexpr (requires { runtime.BindMultiRangeStorageBuffer(u64{}, bool{}); }) {
+ const u64 key = GeometryKey(binding.gpu_addr, 0);
+ if (!PushMultiRangeSources(binding, is_written, pool, key)) {
+ return false;
+ }
+ return runtime.BindMultiRangeStorageBuffer(key, is_written);
+ } else {
+ return false;
+ }
+}
+
+template
+u64 BufferCache::GeometryKey(GPUVAddr gpu_addr, u64 salt) const {
+ return ((static_cast(gpu_memory->GetID()) << 48) ^ gpu_addr) ^ salt;
+}
+
+template
+u32 BufferCache::ClampToMappedRange(GPUVAddr gpu_addr, u32 size) const {
+ const size_t mapped = gpu_memory->MaxMappedRange(gpu_addr, size);
+ if (mapped == 0 || mapped >= size) {
+ return size;
+ }
+ return static_cast(mapped);
+}
+
+template
+bool BufferCache::PushMultiRangeSources(const Binding& binding, bool is_written,
+ std::span pool, u64 key) {
if constexpr (requires { runtime.BindMultiRangeStorageBuffer(u64{}, bool{}); }) {
if (binding.segment_count < 2) {
return false;
@@ -1053,23 +1197,273 @@ bool BufferCache::BindMultiRangeStorage(const Binding& binding, bool is_writt
if (binding.segment_first + binding.segment_count > pool.size()) {
return false;
}
- const u64 key = (static_cast(gpu_memory->GetID()) << 48) ^ binding.gpu_addr;
+ const std::span segments =
+ pool.subspan(binding.segment_first, binding.segment_count);
+ boost::container::small_vector buffer_ids;
+ for (const MultiRangeSegment& segment : segments) {
+ BufferId buffer_id = segment.buffer_id;
+ if (!buffer_id) {
+ buffer_id = page_table[segment.device_addr >> CACHING_PAGEBITS];
+ }
+ if (!buffer_id ||
+ !slot_buffers[buffer_id].IsInBounds(segment.device_addr, segment.size)) {
+ return false;
+ }
+ buffer_ids.push_back(buffer_id);
+ }
runtime.ResetMultiRange();
for (u32 index = 0; index < binding.segment_count; ++index) {
- const MultiRangeSegment& segment = pool[binding.segment_first + index];
- Buffer& buffer = slot_buffers[segment.buffer_id];
- TouchBuffer(buffer, segment.buffer_id);
- if (SynchronizeBuffer(buffer, segment.device_addr, segment.size)) {
+ const MultiRangeSegment& segment = segments[index];
+ const BufferId buffer_id = buffer_ids[index];
+ Buffer& buffer = slot_buffers[buffer_id];
+ TouchBuffer(buffer, buffer_id);
+ if (!SynchronizeBuffer(buffer, segment.device_addr, segment.size)) {
runtime.InvalidateMultiRange(key);
}
const u32 offset = buffer.Offset(segment.device_addr);
buffer.MarkUsage(offset, segment.size);
if (is_written) {
- MarkWrittenBuffer(segment.buffer_id, segment.device_addr, segment.size);
+ MarkWrittenBuffer(buffer_id, segment.device_addr, segment.size);
}
runtime.PushMultiRangeSource(buffer, offset, segment.size);
}
- return runtime.BindMultiRangeStorageBuffer(key, is_written);
+ return true;
+ } else {
+ return false;
+ }
+}
+
+template
+bool BufferCache::TryResolveUnifiedSegments(
+ [[maybe_unused]] const Binding& binding,
+ [[maybe_unused]] std::span pool,
+ [[maybe_unused]] UnifiedExtents& extents) {
+ if constexpr (USE_UNIFIED_MEMORY) {
+ extents.clear();
+ const auto push = [&](DAddr device_addr, u64 size) {
+ const std::optional relative = TryResolveUnifiedRange(device_addr, size);
+ if (!relative) {
+ return false;
+ }
+ if (!extents.empty() && extents.back().relative + extents.back().size == *relative) {
+ extents.back().size += size;
+ return true;
+ }
+ extents.push_back(UnifiedExtent{.relative = *relative, .size = size});
+ return true;
+ };
+ if (binding.segment_count < 2) {
+ return push(binding.device_addr, binding.size);
+ }
+ if (binding.segment_first + binding.segment_count > pool.size()) {
+ return false;
+ }
+ for (const MultiRangeSegment& segment :
+ pool.subspan(binding.segment_first, binding.segment_count)) {
+ if (!push(segment.device_addr, segment.size)) {
+ return false;
+ }
+ }
+ return true;
+ } else {
+ return false;
+ }
+}
+
+template
+void BufferCache::ResolveGeometrySegments([[maybe_unused]] bool is_indexed) {
+ if constexpr (requires { runtime.BindStagedVertexBuffers(); }) {
+ const auto& draw_state = maxwell3d->draw_manager.draw_state;
+ if (is_indexed && draw_state.inline_index_draw_indexes.empty()) {
+ ResolveMultiRangeStorage(channel_state->index_buffer, false, graphics_segments);
+ }
+ u32 enabled_mask = enabled_vertex_buffers_mask;
+ while (enabled_mask != 0) {
+ const u32 index = std::countr_zero(enabled_mask);
+ enabled_mask &= enabled_mask - 1;
+ Binding& slot = VertexBufferSlot(index);
+ ResolveMultiRangeStorage(slot, false, graphics_segments);
+ Binding& channel_binding = channel_state->vertex_buffers[index];
+ channel_binding.segment_first = slot.segment_first;
+ channel_binding.segment_count = slot.segment_count;
+ }
+ }
+}
+
+template
+bool BufferCache::StageVirtualVertexBuffer([[maybe_unused]] u32 index,
+ [[maybe_unused]] const Binding& binding,
+ [[maybe_unused]] bool force) {
+ if constexpr (requires { runtime.BindStagedVertexBuffers(); }) {
+ auto& flags = maxwell3d->dirty.flags;
+ const bool rebind = force || flags[Dirty::VertexBuffer0 + index] ||
+ ((virtual_vertex_buffers_mask >> index) & 1) == 0;
+ const u32 stride = maxwell3d->regs.vertex_streams[index].stride;
+ const u64 salt = VERTEX_GEOMETRY_SALT + (u64{index} << 40);
+ bool staged = false;
+ if constexpr (USE_UNIFIED_MEMORY) {
+ UnifiedExtents extents;
+ if (TryResolveUnifiedSegments(binding, graphics_segments, extents)) {
+ const u64 view_key = GeometryKey(binding.gpu_addr, salt + VIEW_GEOMETRY_SALT);
+ staged = runtime.StageUnifiedVertexBuffer(index, view_key, extents, binding.size,
+ stride, rebind);
+ }
+ }
+ if (!staged) {
+ const u64 key = GeometryKey(binding.gpu_addr, salt);
+ if (PushMultiRangeSources(binding, false, graphics_segments, key)) {
+ staged = runtime.StageMultiRangeVertexBuffer(index, key, binding.size, stride,
+ rebind);
+ }
+ }
+ if (!staged) {
+ return false;
+ }
+ flags[Dirty::VertexBuffer0 + index] = false;
+ virtual_vertex_buffers_mask |= 1u << index;
+ return true;
+ } else {
+ return false;
+ }
+}
+
+template
+bool BufferCache::BindVirtualIndexBuffer() {
+ if constexpr (!HAS_FULL_INDEX_AND_PRIMITIVE_SUPPORT &&
+ requires { runtime.BindStagedVertexBuffers(); }) {
+ const Binding& binding = channel_state->index_buffer;
+ const auto& draw_state = maxwell3d->draw_manager.draw_state;
+ const auto& index_ref = draw_state.index_buffer;
+ if constexpr (USE_UNIFIED_MEMORY) {
+ UnifiedExtents extents;
+ const u64 view_key =
+ GeometryKey(binding.gpu_addr, INDEX_GEOMETRY_SALT + VIEW_GEOMETRY_SALT);
+ if (TryResolveUnifiedSegments(binding, graphics_segments, extents) &&
+ runtime.BindUnifiedIndexBuffer(draw_state.topology, index_ref.format,
+ index_ref.first, index_ref.count, view_key,
+ extents, binding.size)) {
+ return true;
+ }
+ }
+ const u64 key = GeometryKey(binding.gpu_addr, INDEX_GEOMETRY_SALT);
+ if (!PushMultiRangeSources(binding, false, graphics_segments, key)) {
+ return false;
+ }
+ return runtime.BindMultiRangeIndexBuffer(draw_state.topology, index_ref.format,
+ index_ref.first, index_ref.count, key,
+ binding.size);
+ } else {
+ return false;
+ }
+}
+
+template
+void BufferCache::BindStagedVertexBuffers() {
+ if constexpr (requires { runtime.BindStagedVertexBuffers(); }) {
+ runtime.BindStagedVertexBuffers();
+ }
+}
+
+template
+bool BufferCache::HasPendingUnifiedWrites([[maybe_unused]] DAddr device_addr,
+ [[maybe_unused]] u64 size) {
+ if constexpr (USE_UNIFIED_MEMORY) {
+ if (unified_written_ranges.Empty()) {
+ return false;
+ }
+ if (runtime.KnownGpuTick() >= unified_write_tick) {
+ unified_written_ranges.Clear();
+ return false;
+ }
+ bool overlaps = false;
+ unified_written_ranges.ForEachInRange(device_addr, size,
+ [&overlaps](DAddr, DAddr) { overlaps = true; });
+ return overlaps;
+ } else {
+ return false;
+ }
+}
+
+template
+void BufferCache::WaitForUnifiedWrites([[maybe_unused]] DAddr device_addr,
+ [[maybe_unused]] u64 size) {
+ if constexpr (USE_UNIFIED_MEMORY) {
+ if (!HasPendingUnifiedWrites(device_addr, size)) {
+ return;
+ }
+ runtime.Wait(unified_write_tick);
+ unified_written_ranges.Clear();
+ }
+}
+
+template
+template
+bool BufferCache::CopyUnifiedWrites([[maybe_unused]] Buffer& buffer,
+ [[maybe_unused]] DAddr device_addr,
+ [[maybe_unused]] u64 size,
+ [[maybe_unused]] Func&& add_upload) {
+ if constexpr (USE_UNIFIED_MEMORY) {
+ if (!HasPendingUnifiedWrites(device_addr, size)) {
+ return false;
+ }
+ boost::container::small_vector, 4> overlaps;
+ unified_written_ranges.ForEachInRange(device_addr, size,
+ [&overlaps](DAddr start, DAddr end) {
+ overlaps.emplace_back(start, end);
+ });
+ const DAddr buffer_start = buffer.CpuAddr();
+ boost::container::small_vector window_ids;
+ UnifiedWindowGroups groups;
+ for (const auto& [start, end] : overlaps) {
+ if (!ResolveUnifiedWindows(start, start - buffer_start, end - start, window_ids,
+ groups)) {
+ runtime.Wait(unified_write_tick);
+ unified_written_ranges.Clear();
+ return false;
+ }
+ }
+ for (size_t i = 0; i < window_ids.size(); ++i) {
+ const std::span group_span(groups[i].data(), groups[i].size());
+ runtime.CopyFromUnifiedMemory(window_ids[i], buffer, group_span);
+ }
+ DAddr cursor = device_addr;
+ for (const auto& [start, end] : overlaps) {
+ buffer.MarkUsage(start - buffer_start, end - start);
+ if (start > cursor) {
+ add_upload(cursor, start - cursor);
+ }
+ cursor = end;
+ }
+ if (cursor < device_addr + size) {
+ add_upload(cursor, device_addr + size - cursor);
+ }
+ return true;
+ } else {
+ return false;
+ }
+}
+
+template
+bool BufferCache::BindUnifiedStorage([[maybe_unused]] const Binding& binding,
+ [[maybe_unused]] bool is_written) {
+ if constexpr (USE_UNIFIED_MEMORY) {
+ const auto relative = TryResolveUnifiedRange(binding.device_addr, binding.size);
+ if (!relative) {
+ return false;
+ }
+ const auto range = runtime.ResolveUnifiedStorage(*relative, binding.size);
+ if (!range) {
+ return false;
+ }
+ if (is_written) {
+ memory_tracker.MarkRegionAsCpuModified(binding.device_addr, binding.size);
+ unified_written_ranges.Add(binding.device_addr, binding.size);
+ unified_write_tick = runtime.CurrentTick();
+ uncommitted_unified_writes = true;
+ }
+ runtime.BindStorageBuffer(range->buffer, range->address, range->offset,
+ binding.size, is_written);
+ return true;
} else {
return false;
}
@@ -1086,7 +1480,11 @@ void BufferCache
::BindHostGraphicsStorageBuffers(size_t stage) {
}
Buffer& buffer = slot_buffers[binding.buffer_id];
TouchBuffer(buffer, binding.buffer_id);
+ if (BindUnifiedStorage(binding, is_written)) {
+ return;
+ }
const u32 size = binding.size;
+
SynchronizeBuffer(buffer, binding.device_addr, size);
const u32 offset = buffer.Offset(binding.device_addr);
@@ -1195,6 +1593,7 @@ void BufferCache
::BindHostComputeUniformBuffers() {
}();
if constexpr (!IS_OPENGL) {
if (needs_alignment_stream) {
+ WaitForUnifiedWrites(binding.device_addr, size);
const std::span span =
runtime.BindMappedUniformBuffer(0, binding_index, size);
device_memory.ReadBlockUnsafe(binding.device_addr, span.data(), size);
@@ -1226,6 +1625,9 @@ void BufferCache::BindHostComputeStorageBuffers() {
}
Buffer& buffer = slot_buffers[binding.buffer_id];
TouchBuffer(buffer, binding.buffer_id);
+ if (BindUnifiedStorage(binding, is_written)) {
+ return;
+ }
const u32 size = binding.size;
SynchronizeBuffer(buffer, binding.device_addr, size);
@@ -1282,6 +1684,7 @@ void BufferCache
::DoUpdateGraphicsBuffers(bool is_indexed) {
UpdateIndexBuffer();
}
UpdateVertexBuffers();
+ ResolveGeometrySegments(is_indexed);
UpdateTransformFeedbackBuffers();
for (size_t stage = 0; stage < NUM_STAGES; ++stage) {
UpdateUniformBuffers(stage);
@@ -1338,13 +1741,17 @@ void BufferCache
::UpdateIndexBuffer() {
const std::optional device_addr = gpu_memory->GpuToCpuAddress(gpu_addr_begin);
const u32 address_size = static_cast(gpu_addr_end - gpu_addr_begin);
const u32 draw_size = (index_buffer_ref.count + index_buffer_ref.first) * u32(index_buffer_ref.FormatSizeInBytes());
- const u32 size = (std::min)(address_size, draw_size);
+ u32 size = (std::min)(address_size, draw_size);
if (size == 0 || !device_addr) {
channel_state->index_buffer = NULL_BINDING;
return;
}
+ if constexpr (requires { runtime.BindStagedVertexBuffers(); }) {
+ size = ClampToMappedRange(gpu_addr_begin, size);
+ }
channel_state->index_buffer = Binding{
.device_addr = *device_addr,
+ .gpu_addr = gpu_addr_begin,
.size = size,
.buffer_id = FindBuffer(*device_addr, size, false),
};
@@ -1382,10 +1789,13 @@ void BufferCache::UpdateVertexBuffer(u32 index) {
}
if (!gpu_memory->IsWithinGPUAddressRange(gpu_addr_end) || size >= 64_MiB) {
size = static_cast(gpu_memory->MaxContinuousRange(gpu_addr_begin, size));
+ } else if constexpr (requires { runtime.BindStagedVertexBuffers(); }) {
+ size = ClampToMappedRange(gpu_addr_begin, size);
}
const BufferId buffer_id = FindBuffer(*device_addr, size, false);
const Binding binding{
.device_addr = *device_addr,
+ .gpu_addr = gpu_addr_begin,
.size = size,
.buffer_id = buffer_id,
};
@@ -1742,16 +2152,28 @@ bool BufferCache::SynchronizeBuffer(Buffer& buffer, DAddr device_addr, u32 si
u64 total_size_bytes = 0;
u64 largest_copy = 0;
const DAddr buffer_start = buffer.cpu_addr_cached;
- memory_tracker.ForEachUploadRange(device_addr, size, [&](u64 device_addr_out, u64 range_size) {
+ const auto add_upload = [&](u64 upload_addr, u64 upload_size) {
upload_copies.push_back(BufferCopy{
.src_offset = total_size_bytes,
- .dst_offset = device_addr_out - buffer_start,
- .size = range_size,
+ .dst_offset = upload_addr - buffer_start,
+ .size = upload_size,
});
- total_size_bytes += range_size;
- largest_copy = (std::max)(largest_copy, range_size);
+ total_size_bytes += upload_size;
+ largest_copy = (std::max)(largest_copy, upload_size);
+ };
+ bool copied_from_windows = false;
+ memory_tracker.ForEachUploadRange(device_addr, size, [&](u64 device_addr_out, u64 range_size) {
+ if (CopyUnifiedWrites(buffer, device_addr_out, range_size, add_upload)) {
+ copied_from_windows = true;
+ return;
+ }
+ add_upload(device_addr_out, range_size);
});
if (total_size_bytes == 0) {
+ if (copied_from_windows) {
+ any_buffer_uploaded = true;
+ return false;
+ }
return true;
}
const std::span copies_span(upload_copies.data(), upload_copies.size());
@@ -1799,6 +2221,130 @@ void BufferCache::ImmediateUploadMemory([[maybe_unused]] Buffer& buffer,
}
}
+template
+bool BufferCache::ResolveUnifiedWindows(
+ [[maybe_unused]] DAddr device_addr, [[maybe_unused]] u64 buffer_offset,
+ [[maybe_unused]] u64 size, [[maybe_unused]] boost::container::small_vector& window_ids,
+ [[maybe_unused]] UnifiedWindowGroups& groups) {
+ if constexpr (USE_UNIFIED_MEMORY) {
+ const u8* const physical_base = device_memory.GetPhysicalBase();
+ const u64 unified_base = runtime.UnifiedMemoryBase();
+ const u64 unified_size = runtime.UnifiedMemorySize();
+ const u64 window_size = runtime.UnifiedMemoryWindowSize();
+ if (window_size == 0) {
+ return false;
+ }
+ const auto group_for = [&](u64 window) -> boost::container::small_vector& {
+ for (size_t i = 0; i < window_ids.size(); ++i) {
+ if (window_ids[i] == window) {
+ return groups[i];
+ }
+ }
+ window_ids.push_back(window);
+ groups.emplace_back();
+ return groups.back();
+ };
+ u64 downloaded = 0;
+ while (downloaded < size) {
+ const DAddr page_addr = device_addr + downloaded;
+ const u8* const ptr = device_memory.GetPointer(page_addr);
+ if (ptr == nullptr) {
+ return false;
+ }
+ const u64 page_offset = page_addr & Core::DEVICE_PAGEMASK;
+ u64 chunk = (std::min)(size - downloaded,
+ static_cast(Core::DEVICE_PAGESIZE) - page_offset);
+ const u64 phys_offset = static_cast(ptr - physical_base);
+ if (phys_offset < unified_base || phys_offset - unified_base + chunk > unified_size) {
+ return false;
+ }
+ const u64 relative = phys_offset - unified_base;
+ const u64 window = relative / window_size;
+ const u64 local_offset = relative % window_size;
+ chunk = (std::min)(chunk, window_size - local_offset);
+ auto& group = group_for(window);
+ if (!group.empty()) {
+ BufferCopy& last = group.back();
+ if (last.src_offset + last.size == buffer_offset + downloaded &&
+ last.dst_offset + last.size == local_offset) {
+ last.size += chunk;
+ downloaded += chunk;
+ continue;
+ }
+ }
+ group.push_back(BufferCopy{
+ .src_offset = buffer_offset + downloaded,
+ .dst_offset = local_offset,
+ .size = chunk,
+ });
+ downloaded += chunk;
+ }
+ return true;
+ } else {
+ return false;
+ }
+}
+
+template
+std::optional BufferCache::TryResolveUnifiedRange([[maybe_unused]] DAddr device_addr,
+ [[maybe_unused]] u64 size) {
+ if constexpr (USE_UNIFIED_MEMORY) {
+ if (size == 0 || !runtime.IsUnifiedMemoryBindable()) {
+ return std::nullopt;
+ }
+ const u8* const first = device_memory.GetSpan(device_addr, size);
+ if (first == nullptr) {
+ return std::nullopt;
+ }
+ const u64 phys_offset = static_cast(first - device_memory.GetPhysicalBase());
+ const u64 unified_base = runtime.UnifiedMemoryBase();
+ if (phys_offset < unified_base) {
+ return std::nullopt;
+ }
+ const u64 relative = phys_offset - unified_base;
+ const u64 unified_size = runtime.UnifiedMemorySize();
+ if (relative >= unified_size || unified_size - relative < size) {
+ return std::nullopt;
+ }
+ if (memory_tracker.IsRegionGpuModified(device_addr, size) ||
+ IsRegionGpuModified(device_addr, size)) {
+ return std::nullopt;
+ }
+ return relative;
+ } else {
+ return std::nullopt;
+ }
+}
+
+template
+bool BufferCache::TryUnifiedDownloadMemory([[maybe_unused]] Buffer& buffer,
+ [[maybe_unused]] std::span copies) {
+ if constexpr (USE_UNIFIED_MEMORY) {
+ boost::container::small_vector window_ids;
+ UnifiedWindowGroups groups;
+ for (const BufferCopy& copy : copies) {
+ if (!ResolveUnifiedWindows(buffer.CpuAddr() + copy.src_offset, copy.src_offset,
+ copy.size, window_ids, groups)) {
+ return false;
+ }
+ }
+ for (const BufferCopy& copy : copies) {
+ buffer.MarkUsage(copy.src_offset, copy.size);
+ }
+ runtime.PreCopyBarrier();
+ for (size_t i = 0; i < window_ids.size(); ++i) {
+ const std::span group_span(groups[i].data(), groups[i].size());
+ runtime.CopyToUnifiedMemory(window_ids[i], buffer, group_span);
+ }
+ runtime.FlushUnifiedMemoryCopies();
+ runtime.UnifiedMemoryHostBarrier();
+ runtime.Finish();
+ return true;
+ } else {
+ return false;
+ }
+}
+
template
void BufferCache::MappedUploadMemory([[maybe_unused]] Buffer& buffer,
[[maybe_unused]] u64 total_size_bytes,
@@ -1902,6 +2448,12 @@ void BufferCache
::DownloadBufferMemory(Buffer& buffer, DAddr device_addr, u64
}
if constexpr (USE_MEMORY_MAPS) {
+ if constexpr (USE_UNIFIED_MEMORY) {
+ if (runtime.HasUnifiedMemory() &&
+ TryUnifiedDownloadMemory(buffer, std::span(copies.data(), copies.size()))) {
+ return;
+ }
+ }
auto download_staging = runtime.DownloadStagingBuffer(total_size_bytes);
const u8* const mapped_memory = download_staging.mapped_span.data();
const std::span copies_span(copies.data(), copies.data() + copies.size());
@@ -1963,6 +2515,15 @@ void BufferCache::DeleteBuffer(BufferId buffer_id, bool do_not_mark) {
replace(channel_state->transform_feedback_buffers);
replace(channel_state->compute_uniform_buffers);
replace(channel_state->compute_storage_buffers);
+ const auto drop_segments = [buffer_id](std::vector& pool) {
+ for (MultiRangeSegment& segment : pool) {
+ if (segment.buffer_id == buffer_id) {
+ segment.buffer_id = BufferId{};
+ }
+ }
+ };
+ drop_segments(graphics_segments);
+ drop_segments(compute_segments);
// Mark the whole buffer as CPU written to stop tracking CPU writes
if (!do_not_mark) {
diff --git a/src/video_core/buffer_cache/buffer_cache_base.h b/src/video_core/buffer_cache/buffer_cache_base.h
index 0dbb368c47..211b67a883 100644
--- a/src/video_core/buffer_cache/buffer_cache_base.h
+++ b/src/video_core/buffer_cache/buffer_cache_base.h
@@ -12,6 +12,7 @@
#include
#include
#include
+#include
#include
#include
#include
@@ -95,6 +96,11 @@ struct MultiRangeSegment {
u32 size{};
};
+struct UnifiedExtent {
+ u64 relative{};
+ u64 size{};
+};
+
struct TextureBufferBinding : Binding {
PixelFormat format;
};
@@ -190,6 +196,10 @@ class BufferCache : public VideoCommon::ChannelSetupCaches pool);
+ bool BindUnifiedStorage(const Binding& binding, bool is_written);
+
+ bool PushMultiRangeSources(const Binding& binding, bool is_written,
+ std::span pool, u64 key);
+
void ResolveMultiRangeStorage(Binding& binding, bool is_written,
std::vector& pool);
@@ -462,6 +477,41 @@ private:
void MappedUploadMemory(Buffer& buffer, u64 total_size_bytes, std::span copies);
+ bool TryUnifiedDownloadMemory(Buffer& buffer, std::span copies);
+
+ std::optional TryResolveUnifiedRange(DAddr device_addr, u64 size);
+
+ using UnifiedExtents = boost::container::small_vector;
+
+ bool TryResolveUnifiedSegments(const Binding& binding, std::span pool,
+ UnifiedExtents& extents);
+
+ void ResolveGeometrySegments(bool is_indexed);
+
+ bool StageVirtualVertexBuffer(u32 index, const Binding& binding, bool force);
+
+ bool BindVirtualIndexBuffer();
+
+ void BindStagedVertexBuffers();
+
+ [[nodiscard]] u64 GeometryKey(GPUVAddr gpu_addr, u64 salt) const;
+
+ [[nodiscard]] u32 ClampToMappedRange(GPUVAddr gpu_addr, u32 size) const;
+
+ bool HasPendingUnifiedWrites(DAddr device_addr, u64 size);
+
+ void WaitForUnifiedWrites(DAddr device_addr, u64 size);
+
+ template
+ bool CopyUnifiedWrites(Buffer& buffer, DAddr device_addr, u64 size, Func&& add_upload);
+
+ using UnifiedWindowGroups =
+ boost::container::small_vector, 4>;
+
+ bool ResolveUnifiedWindows(DAddr device_addr, u64 buffer_offset, u64 size,
+ boost::container::small_vector& window_ids,
+ UnifiedWindowGroups& groups);
+
void DownloadBufferMemory(Buffer& buffer_id);
void DownloadBufferMemory(Buffer& buffer_id, DAddr device_addr, u64 size);
@@ -506,6 +556,7 @@ private:
u32 last_index_count = 0;
u32 enabled_vertex_buffers_mask = 0;
+ u32 virtual_vertex_buffers_mask = 0;
u64 vertex_buffers_serial = 0;
std::array v_buffer{};
@@ -515,11 +566,20 @@ private:
Common::RangeSet uncommitted_gpu_modified_ranges;
Common::RangeSet gpu_modified_ranges;
std::deque> committed_gpu_modified_ranges;
+ Common::RangeSet unified_written_ranges;
+ u64 unified_write_tick = 0;
+ bool uncommitted_unified_writes = false;
// Async Buffers
+ struct AsyncDownloadBatch {
+ boost::container::small_vector staging_copies;
+ boost::container::small_vector unified_copies;
+ bool unified_writes = false;
+ };
+
Common::OverlapRangeSet async_downloads;
std::deque> async_buffers;
- std::deque> pending_downloads;
+ std::deque pending_downloads;
std::optional current_buffer;
std::deque async_buffers_death_ring;
diff --git a/src/video_core/host_shaders/CMakeLists.txt b/src/video_core/host_shaders/CMakeLists.txt
index c4e7ac3f6f..78322d81dc 100644
--- a/src/video_core/host_shaders/CMakeLists.txt
+++ b/src/video_core/host_shaders/CMakeLists.txt
@@ -16,13 +16,16 @@ set(GLSL_INCLUDES
set(SHADER_FILES
${CMAKE_CURRENT_SOURCE_DIR}/astc_decoder.comp
${CMAKE_CURRENT_SOURCE_DIR}/blit_color_float.frag
+ ${CMAKE_CURRENT_SOURCE_DIR}/block_linear_swizzle_2d_buffer.comp
${CMAKE_CURRENT_SOURCE_DIR}/block_linear_unswizzle_2d.comp
+ ${CMAKE_CURRENT_SOURCE_DIR}/block_linear_unswizzle_2d_buffer.comp
${CMAKE_CURRENT_SOURCE_DIR}/blit_color_msaa.frag
${CMAKE_CURRENT_SOURCE_DIR}/blit_depth.frag
${CMAKE_CURRENT_SOURCE_DIR}/blit_depth_msaa.frag
${CMAKE_CURRENT_SOURCE_DIR}/blit_depth_stencil_msaa.frag
${CMAKE_CURRENT_SOURCE_DIR}/block_linear_unswizzle_3d.comp
${CMAKE_CURRENT_SOURCE_DIR}/block_linear_unswizzle_3d_bcn.comp
+ ${CMAKE_CURRENT_SOURCE_DIR}/block_linear_unswizzle_3d_buffer.comp
${CMAKE_CURRENT_SOURCE_DIR}/convert_abgr8_to_d24s8.frag
${CMAKE_CURRENT_SOURCE_DIR}/convert_abgr8_to_d32f.frag
${CMAKE_CURRENT_SOURCE_DIR}/convert_d32f_to_abgr8.frag
diff --git a/src/video_core/host_shaders/block_linear_swizzle_2d_buffer.comp b/src/video_core/host_shaders/block_linear_swizzle_2d_buffer.comp
new file mode 100644
index 0000000000..3497a5942c
--- /dev/null
+++ b/src/video_core/host_shaders/block_linear_swizzle_2d_buffer.comp
@@ -0,0 +1,83 @@
+// SPDX-FileCopyrightText: Copyright 2026 Eden Emulator Project
+// SPDX-License-Identifier: GPL-3.0-or-later
+
+#version 430
+
+#define BINDING_INPUT_BUFFER 0
+#define BINDING_OUTPUT_BUFFER 1
+
+layout(push_constant) uniform PushConstants {
+ uvec3 dim;
+ uint bytes_per_block_log2;
+
+ uvec3 origin;
+ uint layer_stride;
+
+ uint block_size;
+ uint x_shift;
+ uint block_height;
+ uint block_height_mask;
+} pc;
+
+layout(binding = BINDING_INPUT_BUFFER, std430) readonly buffer InputBuffer {
+ uint in_u32[];
+};
+
+layout(binding = BINDING_OUTPUT_BUFFER, std430) buffer OutputBuffer {
+ uint out_u32[];
+};
+
+layout(local_size_x = 16, local_size_y = 8, local_size_z = 1) in;
+
+const uint GOB_SIZE_X = 64;
+const uint GOB_SIZE_Y = 8;
+
+const uint GOB_SIZE_X_SHIFT = 6;
+const uint GOB_SIZE_Y_SHIFT = 3;
+const uint GOB_SIZE_SHIFT = GOB_SIZE_X_SHIFT + GOB_SIZE_Y_SHIFT;
+
+const uvec2 SWIZZLE_MASK = uvec2(GOB_SIZE_X - 1u, GOB_SIZE_Y - 1u);
+
+uint SwizzleTable(uint pos) {
+ const uint t[8] = uint[](
+ 0x12100200, 0x13110301, 0x16140604, 0x17150705,
+ 0x1a180a08, 0x1b190b09, 0x1e1c0e0c, 0x1f1d0f0d
+ );
+ const uint i = pos >> 4;
+ const uint h = (t[i / 4] >> ((i % 4) * 8)) & 0xff;
+ return (h << 4) | (pos & 0xf);
+}
+
+uint SwizzleOffset(uvec2 pos) {
+ pos = pos & SWIZZLE_MASK;
+ return SwizzleTable(pos.y * 64u + pos.x);
+}
+
+void main() {
+ uvec3 coord = gl_GlobalInvocationID;
+ if (coord.x >= pc.dim.x || coord.y >= pc.dim.y || coord.z >= pc.dim.z) {
+ return;
+ }
+
+ uvec3 pos = coord + pc.origin;
+ pos.x <<= pc.bytes_per_block_log2;
+
+ uint swizzle = SwizzleOffset(pos.xy);
+ uint block_y = pos.y >> GOB_SIZE_Y_SHIFT;
+
+ uint offset = 0u;
+ offset += pos.z * pc.layer_stride;
+ offset += (block_y >> pc.block_height) * pc.block_size;
+ offset += (block_y & pc.block_height_mask) << GOB_SIZE_SHIFT;
+ offset += (pos.x >> GOB_SIZE_X_SHIFT) << pc.x_shift;
+ offset += swizzle;
+
+ uint words = 1u << (pc.bytes_per_block_log2 - 2u);
+ uint linear_index = coord.x + coord.y * pc.dim.x + coord.z * pc.dim.x * pc.dim.y;
+ uint in_idx = linear_index * words;
+ uint out_idx = offset >> 2u;
+
+ for (uint word = 0u; word < words; ++word) {
+ out_u32[out_idx + word] = in_u32[in_idx + word];
+ }
+}
diff --git a/src/video_core/host_shaders/block_linear_unswizzle_2d_buffer.comp b/src/video_core/host_shaders/block_linear_unswizzle_2d_buffer.comp
new file mode 100644
index 0000000000..3fc71e05b6
--- /dev/null
+++ b/src/video_core/host_shaders/block_linear_unswizzle_2d_buffer.comp
@@ -0,0 +1,104 @@
+// SPDX-FileCopyrightText: Copyright 2026 Eden Emulator Project
+// SPDX-License-Identifier: GPL-3.0-or-later
+
+#version 430
+
+#extension GL_EXT_shader_16bit_storage : require
+#extension GL_EXT_shader_8bit_storage : require
+
+#define BINDING_INPUT_BUFFER 0
+#define BINDING_OUTPUT_BUFFER 1
+
+layout(push_constant) uniform PushConstants {
+ uvec3 dim;
+ uint bytes_per_block_log2;
+
+ uvec3 origin;
+ uint layer_stride;
+
+ uint block_size;
+ uint x_shift;
+ uint block_height;
+ uint block_height_mask;
+} pc;
+
+layout(binding = BINDING_INPUT_BUFFER, std430) buffer InputBufferU32 { uint u32data[]; };
+layout(binding = BINDING_INPUT_BUFFER, std430) buffer InputBufferU64 { uvec2 u64data[]; };
+layout(binding = BINDING_INPUT_BUFFER, std430) buffer InputBufferU128 { uvec4 u128data[]; };
+
+layout(binding = BINDING_OUTPUT_BUFFER, std430) writeonly buffer OutputBuffer {
+ uint out_u32[];
+};
+
+layout(local_size_x = 16, local_size_y = 8, local_size_z = 1) in;
+
+const uint GOB_SIZE_X = 64;
+const uint GOB_SIZE_Y = 8;
+
+const uint GOB_SIZE_X_SHIFT = 6;
+const uint GOB_SIZE_Y_SHIFT = 3;
+const uint GOB_SIZE_SHIFT = GOB_SIZE_X_SHIFT + GOB_SIZE_Y_SHIFT;
+
+const uvec2 SWIZZLE_MASK = uvec2(GOB_SIZE_X - 1u, GOB_SIZE_Y - 1u);
+
+uint SwizzleTable(uint pos) {
+ const uint t[8] = uint[](
+ 0x12100200, 0x13110301, 0x16140604, 0x17150705,
+ 0x1a180a08, 0x1b190b09, 0x1e1c0e0c, 0x1f1d0f0d
+ );
+ const uint i = pos >> 4;
+ const uint h = (t[i / 4] >> ((i % 4) * 8)) & 0xff;
+ return (h << 4) | (pos & 0xf);
+}
+
+uint SwizzleOffset(uvec2 pos) {
+ pos = pos & SWIZZLE_MASK;
+ return SwizzleTable(pos.y * 64u + pos.x);
+}
+
+uvec4 ReadTexel(uint offset) {
+ switch (pc.bytes_per_block_log2) {
+ case 2u:
+ return uvec4(u32data[offset / 4u], 0u, 0u, 0u);
+ case 3u:
+ return uvec4(u64data[offset / 8u], 0u, 0u);
+ case 4u:
+ return u128data[offset / 16u];
+ }
+ return uvec4(0u);
+}
+
+void main() {
+ uvec3 coord = gl_GlobalInvocationID;
+ if (coord.x >= pc.dim.x || coord.y >= pc.dim.y || coord.z >= pc.dim.z) {
+ return;
+ }
+
+ uvec3 pos = coord + pc.origin;
+ pos.x <<= pc.bytes_per_block_log2;
+
+ uint swizzle = SwizzleOffset(pos.xy);
+ uint block_y = pos.y >> GOB_SIZE_Y_SHIFT;
+
+ uint offset = 0u;
+ offset += pos.z * pc.layer_stride;
+ offset += (block_y >> pc.block_height) * pc.block_size;
+ offset += (block_y & pc.block_height_mask) << GOB_SIZE_SHIFT;
+ offset += (pos.x >> GOB_SIZE_X_SHIFT) << pc.x_shift;
+ offset += swizzle;
+
+ uvec4 texel = ReadTexel(offset);
+
+ uint words = 1u << (pc.bytes_per_block_log2 - 2u);
+ uint linear_index = coord.x + coord.y * pc.dim.x + coord.z * pc.dim.x * pc.dim.y;
+ uint out_idx = linear_index * words;
+
+ out_u32[out_idx] = texel.x;
+ if (words > 1u) {
+ out_u32[out_idx + 1u] = texel.y;
+ }
+ if (words > 2u) {
+ out_u32[out_idx + 2u] = texel.z;
+ out_u32[out_idx + 3u] = texel.w;
+ }
+}
diff --git a/src/video_core/host_shaders/block_linear_unswizzle_3d_buffer.comp b/src/video_core/host_shaders/block_linear_unswizzle_3d_buffer.comp
new file mode 100644
index 0000000000..7333568eb7
--- /dev/null
+++ b/src/video_core/host_shaders/block_linear_unswizzle_3d_buffer.comp
@@ -0,0 +1,105 @@
+// SPDX-FileCopyrightText: Copyright 2026 Eden Emulator Project
+// SPDX-License-Identifier: GPL-3.0-or-later
+
+#version 430
+
+#define BINDING_INPUT_BUFFER 0
+#define BINDING_OUTPUT_BUFFER 1
+
+layout(push_constant) uniform PushConstants {
+ uvec3 dim;
+ uint bytes_per_block_log2;
+
+ uvec3 origin;
+ uint slice_size;
+
+ uint block_size;
+ uint x_shift;
+ uint block_height;
+ uint block_height_mask;
+
+ uint block_depth;
+ uint block_depth_mask;
+} pc;
+
+layout(binding = BINDING_INPUT_BUFFER, std430) buffer InputBufferU32 { uint u32data[]; };
+layout(binding = BINDING_INPUT_BUFFER, std430) buffer InputBufferU64 { uvec2 u64data[]; };
+layout(binding = BINDING_INPUT_BUFFER, std430) buffer InputBufferU128 { uvec4 u128data[]; };
+
+layout(binding = BINDING_OUTPUT_BUFFER, std430) writeonly buffer OutputBuffer {
+ uint out_u32[];
+};
+
+layout(local_size_x = 8, local_size_y = 8, local_size_z = 4) in;
+
+const uint GOB_SIZE_X = 64;
+const uint GOB_SIZE_Y = 8;
+
+const uint GOB_SIZE_X_SHIFT = 6;
+const uint GOB_SIZE_Y_SHIFT = 3;
+const uint GOB_SIZE_SHIFT = GOB_SIZE_X_SHIFT + GOB_SIZE_Y_SHIFT;
+
+const uvec2 SWIZZLE_MASK = uvec2(GOB_SIZE_X - 1u, GOB_SIZE_Y - 1u);
+
+uint SwizzleTable(uint pos) {
+ const uint t[8] = uint[](
+ 0x12100200, 0x13110301, 0x16140604, 0x17150705,
+ 0x1a180a08, 0x1b190b09, 0x1e1c0e0c, 0x1f1d0f0d
+ );
+ const uint i = pos >> 4;
+ const uint h = (t[i / 4] >> ((i % 4) * 8)) & 0xff;
+ return (h << 4) | (pos & 0xf);
+}
+
+uint SwizzleOffset(uvec2 pos) {
+ pos = pos & SWIZZLE_MASK;
+ return SwizzleTable(pos.y * 64u + pos.x);
+}
+
+uvec4 ReadTexel(uint offset) {
+ switch (pc.bytes_per_block_log2) {
+ case 2u:
+ return uvec4(u32data[offset / 4u], 0u, 0u, 0u);
+ case 3u:
+ return uvec4(u64data[offset / 8u], 0u, 0u);
+ case 4u:
+ return u128data[offset / 16u];
+ }
+ return uvec4(0u);
+}
+
+void main() {
+ uvec3 coord = gl_GlobalInvocationID;
+ if (coord.x >= pc.dim.x || coord.y >= pc.dim.y || coord.z >= pc.dim.z) {
+ return;
+ }
+
+ uvec3 pos = coord + pc.origin;
+ pos.x <<= pc.bytes_per_block_log2;
+
+ uint swizzle = SwizzleOffset(pos.xy);
+ uint block_y = pos.y >> GOB_SIZE_Y_SHIFT;
+
+ uint offset = 0u;
+ offset += (pos.z >> pc.block_depth) * pc.slice_size;
+ offset += (pos.z & pc.block_depth_mask) << (GOB_SIZE_SHIFT + pc.block_height);
+ offset += (block_y >> pc.block_height) * pc.block_size;
+ offset += (block_y & pc.block_height_mask) << GOB_SIZE_SHIFT;
+ offset += (pos.x >> GOB_SIZE_X_SHIFT) << pc.x_shift;
+ offset += swizzle;
+
+ uvec4 texel = ReadTexel(offset);
+
+ uint words = 1u << (pc.bytes_per_block_log2 - 2u);
+ uint linear_index = coord.x + coord.y * pc.dim.x + coord.z * pc.dim.x * pc.dim.y;
+ uint out_idx = linear_index * words;
+
+ out_u32[out_idx] = texel.x;
+ if (words > 1u) {
+ out_u32[out_idx + 1u] = texel.y;
+ }
+ if (words > 2u) {
+ out_u32[out_idx + 2u] = texel.z;
+ out_u32[out_idx + 3u] = texel.w;
+ }
+}
diff --git a/src/video_core/host_shaders/sgsr1_shader_mobile.frag b/src/video_core/host_shaders/sgsr1_shader_mobile.frag
index 3453ca2cae..7fed788afe 100644
--- a/src/video_core/host_shaders/sgsr1_shader_mobile.frag
+++ b/src/video_core/host_shaders/sgsr1_shader_mobile.frag
@@ -6,9 +6,9 @@
precision highp float;
precision highp int;
-// Operation modes: RGBA -> 1, RGBY -> 3, LERP -> 4
-#define OPERATION_MODE 1
#define EDGE_THRESHOLD (8.0 / 255.0)
+#define DIRECTION_EPSILON 6.5e-05
+#define DEVIATION_FLOOR 6.0e-02
layout(push_constant) uniform constants {
vec2 scale;
@@ -21,20 +21,37 @@ layout(set = 0, binding = 0) uniform sampler2D sampler0;
layout(location=0) in vec2 texcoord;
layout(location=0) out vec4 frag_color;
-vec4 weightY(vec4 dx, vec4 dy, vec4 std) {
- vec4 x = ((dx * dx) + (dy * dy)) * 0.55f + std;
- return (x - 1.f) * (x - 4.f) * 3.8125f; // approx. of (x - 1) * (x - 4)^3
+mediump vec4 fastLanczos2(mediump vec4 x) {
+ mediump vec4 wA = x - 4.0f;
+ mediump vec4 wB = x * wA - wA;
+ wA *= wA;
+ return wB * wA;
+}
+
+mediump vec2 edgeDirection(mediump vec4 left, mediump vec4 right) {
+ mediump float RxLz = right.x - left.z;
+ mediump float RwLy = right.w - left.y;
+ mediump vec2 delta = vec2(RxLz + RwLy, RxLz - RwLy);
+ mediump float length_inv =
+ inversesqrt((delta.x * delta.x + DIRECTION_EPSILON) + delta.y * delta.y);
+ return delta * length_inv;
+}
+
+mediump vec4 weightY(mediump vec4 dx, mediump vec4 dy, mediump vec4 c, mediump float std,
+ mediump vec2 dir) {
+ mediump vec4 edge_dis = dx * dir.y + dy * dir.x;
+ mediump vec4 x = (dx * dx + dy * dy) +
+ (edge_dis * edge_dis) * (clamp((c * c) * std, 0.0f, 1.0f) * 0.7f - 1.0f);
+ return fastLanczos2(x);
}
void main() {
- vec4 color = textureLod(sampler0, texcoord.xy, 0.0f);
- // image coord
- vec2 icoord = (texcoord * size + vec2(-0.5f, 0.5f));
- vec2 icoord_pixel = floor(icoord);
- vec2 coord = icoord_pixel * scale;
- vec2 pl = icoord - icoord_pixel;
- // left: 0, right: 1, upDown: 2
- mat3x4 dg = mat3x4(
+ mediump vec4 color = textureLod(sampler0, texcoord.xy, 0.0f);
+ highp vec2 icoord = (texcoord * size + vec2(-0.5f, 0.5f));
+ highp vec2 icoord_pixel = floor(icoord);
+ highp vec2 coord = icoord_pixel * scale;
+ mediump vec2 pl = icoord - icoord_pixel;
+ mediump mat3x4 dg = mat3x4(
textureGather(sampler0, coord, 1),
textureGather(sampler0, coord + vec2(2.f * scale.x, 0.0f), 1),
vec4(
@@ -42,42 +59,40 @@ void main() {
textureGather(sampler0, coord + vec2(scale.x, +scale.y), 1).yx
)
);
- float edgeVote = abs(dg[0].z - dg[0].y) + abs(color.y - dg[0].y) + abs(color.y - dg[0].z);
+ mediump float edgeVote =
+ abs(dg[0].z - dg[0].y) + abs(color.y - dg[0].y) + abs(color.y - dg[0].z);
if (edgeVote > EDGE_THRESHOLD) {
- float mean = (dg[0].y + dg[0].z + dg[1].x + dg[1].w) * 0.25f;
+ mediump float mean = (dg[0].y + dg[0].z + dg[1].x + dg[1].w) * 0.25f;
dg = dg - mean;
- vec4 sum = abs(dg[0]) + abs(dg[1]) + abs(dg[2]);
- float std = 2.181818f / (sum.x + sum.y + sum.z + sum.w);
- mat2x4 w = mat2x4(
- weightY(
- pl.xxxx + vec4(+1.0f, +0.0f, +0.0f, +1.0f),
- pl.yyyy + vec4(-1.0f, -1.0f, +0.0f, +0.0f),
- clamp(abs(dg[0]) * std, 0.0f, 1.0f)
- ) + weightY(
- pl.xxxx + vec4(-1.0f, -2.0f, -2.0f, -1.0f),
- pl.yyyy + vec4(-1.0f, -1.0f, +0.0f, +0.0f),
- clamp(abs(dg[1]) * std, 0.0f, 1.0f)
- ) + weightY(
- pl.xxxx + vec4(+0.0f, -1.0f, -1.0f, +0.0f),
- pl.yyyy + vec4(+1.0f, +1.0f, -2.0f, -2.0f),
- clamp(abs(dg[2]) * std, 0.0f, 1.0f)
- ),
- dg[0] + dg[1] + dg[2]
+ mediump float sum = dot(abs(dg[0]) + abs(dg[1]) + abs(dg[2]), vec4(1.0f));
+ mediump float sum_mean = 1.014185e+01f / max(sum, DEVIATION_FLOOR);
+ mediump float std = sum_mean * sum_mean;
+ mediump vec2 dir = edgeDirection(dg[0], dg[1]);
+ mediump vec4 w0 = weightY(
+ pl.xxxx + vec4(+1.0f, +0.0f, +0.0f, +1.0f),
+ pl.yyyy + vec4(-1.0f, -1.0f, +0.0f, +0.0f),
+ dg[0], std, dir
);
- // compute final y with bounds
- vec2 yb = vec2(
- min(min(dg[0].y, dg[0].z), min(dg[1].x, dg[1].w)), // min
- max(max(dg[0].y, dg[0].z), max(dg[1].x, dg[1].w)) // max
+ mediump vec4 w1 = weightY(
+ pl.xxxx + vec4(-1.0f, -2.0f, -2.0f, -1.0f),
+ pl.yyyy + vec4(-1.0f, -1.0f, +0.0f, +0.0f),
+ dg[1], std, dir
);
- vec2 fvy = vec2(
- w[0].x + w[0].y + w[0].z + w[0].w,
- w[1].x + w[1].y + w[1].z + w[1].w
+ mediump vec4 w2 = weightY(
+ pl.xxxx + vec4(+0.0f, -1.0f, -1.0f, +0.0f),
+ pl.yyyy + vec4(+1.0f, +1.0f, -2.0f, -2.0f),
+ dg[2], std, dir
);
- float fy = clamp((fvy.y / fvy.x) * edge_sharpness, yb[0], yb[1]);
- // Smooth high contrast input
- float dy = clamp(fy - color.y + mean, -23.0f / 255.0f, 23.0f / 255.0f);
+ mediump float sum_w = dot(w0 + w1 + w2, vec4(1.0f));
+ mediump float sum_wc = dot(w0 * dg[0] + w1 * dg[1] + w2 * dg[2], vec4(1.0f));
+ mediump vec2 yb = vec2(
+ min(min(dg[0].y, dg[0].z), min(dg[1].x, dg[1].w)),
+ max(max(dg[0].y, dg[0].z), max(dg[1].x, dg[1].w))
+ );
+ mediump float fy = clamp((sum_wc / sum_w) * edge_sharpness, yb[0], yb[1]);
+ mediump float dy = clamp(fy - color.y + mean, -23.0f / 255.0f, 23.0f / 255.0f);
color = clamp(color + dy, 0.0f, 1.0f);
}
- color.w = 1.0f; //assume alpha channel is not used
+ color.w = 1.0f;
frag_color.xyzw = color;
-}
\ No newline at end of file
+}
diff --git a/src/video_core/memory_manager.cpp b/src/video_core/memory_manager.cpp
index d5838a387d..9556115426 100644
--- a/src/video_core/memory_manager.cpp
+++ b/src/video_core/memory_manager.cpp
@@ -529,6 +529,29 @@ size_t MemoryManager::MaxContinuousRange(GPUVAddr gpu_addr, size_t size) const {
return range_so_far;
}
+size_t MemoryManager::MaxMappedRange(GPUVAddr gpu_addr, size_t size) const {
+ size_t range_so_far = 0;
+ bool stopped{false};
+ auto stop = [&]([[maybe_unused]] std::size_t page_index, [[maybe_unused]] std::size_t offset,
+ [[maybe_unused]] std::size_t copy_amount) {
+ stopped = true;
+ return true;
+ };
+ auto accumulate = [&]([[maybe_unused]] std::size_t page_index,
+ [[maybe_unused]] std::size_t offset, std::size_t copy_amount) {
+ range_so_far += copy_amount;
+ return false;
+ };
+ auto check_short_pages = [&](std::size_t page_index, std::size_t offset,
+ std::size_t copy_amount) {
+ GPUVAddr base = (page_index << big_page_bits) + offset;
+ MemoryOperation(base, copy_amount, false, accumulate, stop, stop);
+ return stopped;
+ };
+ MemoryOperation(gpu_addr, size, true, accumulate, stop, check_short_pages);
+ return range_so_far;
+}
+
size_t MemoryManager::GetMemoryLayoutSize(GPUVAddr gpu_addr, size_t max_size) const {
std::unique_lock lock(guard);
return kind_map.GetContinuousSizeFrom(gpu_addr);
diff --git a/src/video_core/memory_manager.h b/src/video_core/memory_manager.h
index 08978567d2..5eabcb2f8c 100644
--- a/src/video_core/memory_manager.h
+++ b/src/video_core/memory_manager.h
@@ -141,6 +141,8 @@ public:
size_t MaxContinuousRange(GPUVAddr gpu_addr, size_t size) const;
+ size_t MaxMappedRange(GPUVAddr gpu_addr, size_t size) const;
+
bool IsWithinGPUAddressRange(GPUVAddr gpu_addr) const {
return gpu_addr < address_space_size;
}
diff --git a/src/video_core/renderer_opengl/gl_buffer_cache.h b/src/video_core/renderer_opengl/gl_buffer_cache.h
index 6fee58a0eb..4df68bbe35 100644
--- a/src/video_core/renderer_opengl/gl_buffer_cache.h
+++ b/src/video_core/renderer_opengl/gl_buffer_cache.h
@@ -262,6 +262,7 @@ struct BufferCacheParams {
// TODO: Investigate why OpenGL seems to perform worse with persistently mapped buffer uploads
static constexpr bool USE_MEMORY_MAPS_FOR_UPLOADS = false;
+ static constexpr bool USE_UNIFIED_MEMORY = false;
};
using BufferCache = VideoCommon::BufferCache;
diff --git a/src/video_core/renderer_opengl/gl_shader_cache.cpp b/src/video_core/renderer_opengl/gl_shader_cache.cpp
index df69eb97f5..2fd158fd77 100644
--- a/src/video_core/renderer_opengl/gl_shader_cache.cpp
+++ b/src/video_core/renderer_opengl/gl_shader_cache.cpp
@@ -238,6 +238,7 @@ ShaderCache::ShaderCache(Tegra::MaxwellDeviceMemoryManager& device_memory_,
.has_gl_bool_ref_bug = device.HasBoolRefBug(),
.ignore_nan_fp_comparisons = true,
.gl_max_compute_smem_size = device.GetMaxComputeSharedMemorySize(),
+ .max_shared_memory_size = device.GetMaxComputeSharedMemorySize(),
.min_ssbo_alignment = device.GetShaderStorageBufferAlignment(),
// Use the host limit, but never more than the guest can produce. Maxwell exposes 8 clip
// distances and the SPIR-V output array is sized for at most 8, so clamping here keeps a
diff --git a/src/video_core/renderer_opengl/gl_texture_cache.h b/src/video_core/renderer_opengl/gl_texture_cache.h
index 8a830fa0c9..b0731f3381 100644
--- a/src/video_core/renderer_opengl/gl_texture_cache.h
+++ b/src/video_core/renderer_opengl/gl_texture_cache.h
@@ -373,6 +373,7 @@ struct TextureCacheParams {
static constexpr bool HAS_DEVICE_MEMORY_INFO = true;
static constexpr bool IMPLEMENTS_ASYNC_DOWNLOADS = true;
static constexpr bool HAS_MSAA_DOWNLOADS = false;
+ static constexpr bool USE_UNIFIED_MEMORY = false;
using Runtime = OpenGL::TextureCacheRuntime;
using Image = OpenGL::Image;
diff --git a/src/video_core/renderer_vulkan/vk_buffer_cache.cpp b/src/video_core/renderer_vulkan/vk_buffer_cache.cpp
index 958f3b2a2e..655db98450 100644
--- a/src/video_core/renderer_vulkan/vk_buffer_cache.cpp
+++ b/src/video_core/renderer_vulkan/vk_buffer_cache.cpp
@@ -7,9 +7,12 @@
#include
#include
#include
+#include
#include
+#include
#include
+#include "common/alignment.h"
#include "video_core/buffer_cache/buffer_cache_base.h"
#include "video_core/renderer_vulkan/vk_buffer_cache.h"
@@ -32,6 +35,32 @@ VkBufferCopy MakeBufferCopy(const VideoCommon::BufferCopy& copy) {
};
}
+constexpr size_t MAX_WINDOW_BARRIER_RANGES = 8;
+
+using WindowRange = std::pair;
+using WindowRanges = boost::container::small_vector;
+
+void CoalesceWindowRanges(WindowRanges& ranges) {
+ if (ranges.size() < 2) {
+ return;
+ }
+ std::sort(ranges.begin(), ranges.end());
+ size_t merged = 0;
+ for (size_t index = 1; index < ranges.size(); ++index) {
+ if (ranges[index].first <= ranges[merged].second) {
+ ranges[merged].second = (std::max)(ranges[merged].second, ranges[index].second);
+ } else {
+ ranges[++merged] = ranges[index];
+ }
+ }
+ ranges.resize(merged + 1);
+ if (ranges.size() > MAX_WINDOW_BARRIER_RANGES) {
+ const WindowRange bounding{ranges.front().first, ranges.back().second};
+ ranges.clear();
+ ranges.push_back(bounding);
+ }
+}
+
VkIndexType IndexTypeFromNumElements(const Device& device, u32 num_elements) {
if (num_elements <= 0xff && device.IsExtIndexTypeUint8Supported()) {
return VK_INDEX_TYPE_UINT8_EXT;
@@ -42,6 +71,16 @@ VkIndexType IndexTypeFromNumElements(const Device& device, u32 num_elements) {
return VK_INDEX_TYPE_UINT32;
}
+u32 GrowIndexCount(u32 current, u32 requested) {
+ constexpr u32 MinimumIndices = 4096;
+ constexpr u32 GrowthLimit = (std::numeric_limits::max)() / 2;
+ u32 grown = (std::max)(requested, MinimumIndices);
+ if (current <= GrowthLimit) {
+ grown = (std::max)(grown, current * 2);
+ }
+ return grown;
+}
+
size_t BytesPerIndex(VkIndexType index_type) {
switch (index_type) {
case VK_INDEX_TYPE_UINT8_EXT:
@@ -166,13 +205,12 @@ public:
virtual ~QuadIndexBuffer() = default;
void UpdateBuffer(u32 num_indices_) {
+ ReleaseRetiredBuffers();
if (num_indices_ <= num_indices) {
return;
}
- scheduler.Finish();
-
- num_indices = num_indices_;
+ num_indices = GrowIndexCount(num_indices, num_indices_);
index_type = IndexTypeFromNumElements(device, num_indices);
const u32 num_quads = GetQuadsNum(num_indices);
@@ -190,6 +228,12 @@ public:
.queueFamilyIndexCount = 0,
.pQueueFamilyIndices = nullptr,
};
+ if (buffer) {
+ retired_buffers.push_back(RetiredBuffer{
+ .buffer = std::move(buffer),
+ .tick = scheduler.CurrentTick(),
+ });
+ }
buffer = memory_allocator.CreateBuffer(buffer_ci, MemoryUsage::DeviceLocal);
if (device.HasDebuggingToolAttached()) {
buffer.SetObjectNameEXT("Quad LUT");
@@ -257,6 +301,17 @@ protected:
virtual void MakeAndUpdateIndices(u8* staging_data, size_t quad_size, u32 quad, u32 first) = 0;
+ struct RetiredBuffer {
+ vk::Buffer buffer;
+ u64 tick;
+ };
+
+ void ReleaseRetiredBuffers() {
+ std::erase_if(retired_buffers, [this](const RetiredBuffer& entry) {
+ return scheduler.IsFree(entry.tick);
+ });
+ }
+
const Device& device;
MemoryAllocator& memory_allocator;
Scheduler& scheduler;
@@ -264,6 +319,7 @@ protected:
vk::Buffer buffer{};
MemoryCommit memory_commit{};
+ std::vector retired_buffers;
VkIndexType index_type{};
u32 num_indices = 0;
};
@@ -374,6 +430,211 @@ BufferCacheRuntime::BufferCacheRuntime(const Device& device_, MemoryAllocator& m
scheduler_, staging_pool_);
}
+void BufferCacheRuntime::TryEnableUnifiedMemory(void* base, size_t size,
+ std::span hardware_buffers,
+ size_t hardware_buffer_window,
+ size_t hardware_buffer_base) {
+ unified_memory = memory_allocator.CreateHostMemoryImport(
+ base, size, hardware_buffers, hardware_buffer_window, hardware_buffer_base);
+ if (unified_memory) {
+ unified_memory->CreateMirror(scheduler.submit_mutex,
+ device.GetSparseAddressSpaceSize() / 2);
+ multi_range_buffers.ReserveSparseAddressSpace(unified_memory->GetMirrorSize());
+ }
+}
+
+void BufferCacheRuntime::CopyToUnifiedMemory(
+ size_t window_index, VkBuffer src_buffer,
+ std::span copies) {
+ if (!unified_memory || src_buffer == VK_NULL_HANDLE || copies.empty() ||
+ window_index >= unified_memory->GetWindowCount() ||
+ unified_memory->GetWindowBuffer(window_index) == VK_NULL_HANDLE) {
+ return;
+ }
+ PendingUnifiedCopy& pending = pending_unified_copies.emplace_back();
+ pending.window = window_index;
+ pending.buffer = src_buffer;
+ pending.copies.resize(copies.size());
+ std::ranges::transform(copies, pending.copies.begin(), MakeBufferCopy);
+}
+
+void BufferCacheRuntime::CopyFromUnifiedMemory(
+ size_t window_index, VkBuffer dst_buffer, std::span copies) {
+ if (!unified_memory || dst_buffer == VK_NULL_HANDLE || copies.empty() ||
+ window_index >= unified_memory->GetWindowCount()) {
+ return;
+ }
+ const VkBuffer window_buffer = unified_memory->GetWindowBuffer(window_index);
+ if (window_buffer == VK_NULL_HANDLE) {
+ return;
+ }
+ const bool foreign = unified_memory->NeedsForeignOwnershipTransfer();
+ const u32 queue_family = device.GetGraphicsFamily();
+ boost::container::small_vector vk_copies;
+ WindowRanges ranges;
+ for (const VideoCommon::BufferCopy& copy : copies) {
+ vk_copies.push_back(VkBufferCopy{
+ .srcOffset = static_cast(copy.dst_offset),
+ .dstOffset = static_cast(copy.src_offset),
+ .size = static_cast(copy.size),
+ });
+ ranges.emplace_back(copy.dst_offset, copy.dst_offset + copy.size);
+ }
+ CoalesceWindowRanges(ranges);
+ boost::container::small_vector acquire;
+ boost::container::small_vector release;
+ if (foreign) {
+ for (const WindowRange& range : ranges) {
+ acquire.push_back(VkBufferMemoryBarrier{
+ .sType = VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER,
+ .pNext = nullptr,
+ .srcAccessMask = 0,
+ .dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT,
+ .srcQueueFamilyIndex = VK_QUEUE_FAMILY_FOREIGN_EXT,
+ .dstQueueFamilyIndex = queue_family,
+ .buffer = window_buffer,
+ .offset = range.first,
+ .size = range.second - range.first,
+ });
+ release.push_back(VkBufferMemoryBarrier{
+ .sType = VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER,
+ .pNext = nullptr,
+ .srcAccessMask = VK_ACCESS_TRANSFER_READ_BIT,
+ .dstAccessMask = 0,
+ .srcQueueFamilyIndex = queue_family,
+ .dstQueueFamilyIndex = VK_QUEUE_FAMILY_FOREIGN_EXT,
+ .buffer = window_buffer,
+ .offset = range.first,
+ .size = range.second - range.first,
+ });
+ }
+ }
+ scheduler.RequestOutsideRenderPassOperationContext();
+ scheduler.Record([window_buffer, dst_buffer, vk_copies, acquire = std::move(acquire),
+ release = std::move(release)](vk::CommandBuffer cmdbuf) {
+ if (!acquire.empty()) {
+ cmdbuf.PipelineBarrier(VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT,
+ VK_PIPELINE_STAGE_TRANSFER_BIT, 0, {},
+ VideoCommon::FixSmallVectorADL(acquire), {});
+ }
+ cmdbuf.CopyBuffer(window_buffer, dst_buffer, VideoCommon::FixSmallVectorADL(vk_copies));
+ if (!release.empty()) {
+ cmdbuf.PipelineBarrier(VK_PIPELINE_STAGE_TRANSFER_BIT,
+ VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, 0, {},
+ VideoCommon::FixSmallVectorADL(release), {});
+ }
+ });
+}
+
+void BufferCacheRuntime::FlushUnifiedMemoryCopies() {
+ if (pending_unified_copies.empty()) {
+ return;
+ }
+ struct UnifiedCopyCommand {
+ VkBuffer buffer;
+ boost::container::small_vector copies;
+ };
+
+ std::stable_sort(pending_unified_copies.begin(), pending_unified_copies.end(),
+ [](const PendingUnifiedCopy& lhs, const PendingUnifiedCopy& rhs) {
+ return lhs.window < rhs.window;
+ });
+
+ const bool foreign = unified_memory->NeedsForeignOwnershipTransfer();
+ const u32 queue_family = device.GetGraphicsFamily();
+
+ size_t group_begin = 0;
+ while (group_begin < pending_unified_copies.size()) {
+ const size_t window = pending_unified_copies[group_begin].window;
+ size_t group_end = group_begin;
+ while (group_end < pending_unified_copies.size() &&
+ pending_unified_copies[group_end].window == window) {
+ ++group_end;
+ }
+ const VkBuffer window_buffer = unified_memory->GetWindowBuffer(window);
+
+ WindowRanges ranges;
+ for (size_t index = group_begin; index < group_end; ++index) {
+ for (const VkBufferCopy& copy : pending_unified_copies[index].copies) {
+ ranges.emplace_back(copy.dstOffset, copy.dstOffset + copy.size);
+ }
+ }
+ CoalesceWindowRanges(ranges);
+
+ boost::container::small_vector acquire;
+ boost::container::small_vector release;
+ if (foreign) {
+ for (const WindowRange& range : ranges) {
+ acquire.push_back(VkBufferMemoryBarrier{
+ .sType = VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER,
+ .pNext = nullptr,
+ .srcAccessMask = 0,
+ .dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT,
+ .srcQueueFamilyIndex = VK_QUEUE_FAMILY_FOREIGN_EXT,
+ .dstQueueFamilyIndex = queue_family,
+ .buffer = window_buffer,
+ .offset = range.first,
+ .size = range.second - range.first,
+ });
+ release.push_back(VkBufferMemoryBarrier{
+ .sType = VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER,
+ .pNext = nullptr,
+ .srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT,
+ .dstAccessMask = 0,
+ .srcQueueFamilyIndex = queue_family,
+ .dstQueueFamilyIndex = VK_QUEUE_FAMILY_FOREIGN_EXT,
+ .buffer = window_buffer,
+ .offset = range.first,
+ .size = range.second - range.first,
+ });
+ }
+ }
+
+ boost::container::small_vector commands;
+ commands.reserve(group_end - group_begin);
+ for (size_t index = group_begin; index < group_end; ++index) {
+ PendingUnifiedCopy& pending = pending_unified_copies[index];
+ commands.push_back(UnifiedCopyCommand{pending.buffer, std::move(pending.copies)});
+ }
+
+ scheduler.RequestOutsideRenderPassOperationContext();
+ scheduler.Record([window_buffer, acquire = std::move(acquire), release = std::move(release),
+ commands = std::move(commands)](vk::CommandBuffer cmdbuf) {
+ if (!acquire.empty()) {
+ cmdbuf.PipelineBarrier(VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT,
+ VK_PIPELINE_STAGE_TRANSFER_BIT, 0, {},
+ VideoCommon::FixSmallVectorADL(acquire), {});
+ }
+ for (const UnifiedCopyCommand& command : commands) {
+ cmdbuf.CopyBuffer(command.buffer, window_buffer,
+ VideoCommon::FixSmallVectorADL(command.copies));
+ }
+ if (!release.empty()) {
+ cmdbuf.PipelineBarrier(VK_PIPELINE_STAGE_TRANSFER_BIT,
+ VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, 0, {},
+ VideoCommon::FixSmallVectorADL(release), {});
+ }
+ });
+
+ group_begin = group_end;
+ }
+ pending_unified_copies.clear();
+}
+
+void BufferCacheRuntime::UnifiedMemoryHostBarrier() {
+ static constexpr VkMemoryBarrier HOST_BARRIER{
+ .sType = VK_STRUCTURE_TYPE_MEMORY_BARRIER,
+ .pNext = nullptr,
+ .srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT,
+ .dstAccessMask = VK_ACCESS_HOST_READ_BIT,
+ };
+ scheduler.RequestOutsideRenderPassOperationContext();
+ scheduler.Record([](vk::CommandBuffer cmdbuf) {
+ cmdbuf.PipelineBarrier(VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_HOST_BIT, 0,
+ HOST_BARRIER);
+ });
+}
+
StagingBufferRef BufferCacheRuntime::UploadStagingBuffer(size_t size) {
return staging_pool.Request(size, MemoryUsage::Upload);
}
@@ -411,6 +672,7 @@ u32 BufferCacheRuntime::GetStorageBufferAlignment() const {
}
void BufferCacheRuntime::TickFrame(Common::SlotVector& slot_buffers) noexcept {
+ FlushUnifiedMemoryCopies();
for (auto it = slot_buffers.begin(); it != slot_buffers.end(); it++) {
if (scheduler.IsFree(it->LastUsageTick())) {
it->ResetUsageTracking();
@@ -545,17 +807,17 @@ void BufferCacheRuntime::ClearBuffer(VkBuffer dest_buffer, u32 offset, size_t si
});
}
-bool BufferCacheRuntime::BindMultiRangeStorageBuffer(u64 key, bool is_written) {
+MultiRangeRef BufferCacheRuntime::AcquireMultiRange(u64 key, bool require_sparse) {
if (multi_range_sources.empty() || multi_range_total == 0) {
- return false;
+ return MultiRangeRef{};
}
const MultiRangeRef ref = multi_range_buffers.Get(device, scheduler, memory_allocator, key,
multi_range_sources, multi_range_total);
if (ref.handle == VK_NULL_HANDLE) {
- return false;
+ return MultiRangeRef{};
}
- if (is_written && !ref.sparse) {
- return false;
+ if (require_sparse && !ref.sparse) {
+ return MultiRangeRef{};
}
if (ref.needs_gather) {
PreCopyBarrier();
@@ -572,10 +834,220 @@ bool BufferCacheRuntime::BindMultiRangeStorageBuffer(u64 key, bool is_written) {
PostCopyBarrier();
multi_range_buffers.MarkGathered(key);
}
+ return ref;
+}
+
+bool BufferCacheRuntime::BindMultiRangeStorageBuffer(u64 key, bool is_written) {
+ const MultiRangeRef ref = AcquireMultiRange(key, is_written);
+ if (ref.handle == VK_NULL_HANDLE) {
+ return false;
+ }
guest_descriptor_queue.AddBuffer(ref.handle, ref.address, 0, ref.size);
return true;
}
+std::optional BufferCacheRuntime::ResolveUnifiedExtents(
+ u64 key, std::span extents, u32 size) {
+ if (extents.size() == 1) {
+ return unified_memory->ResolveRange(extents.front().relative, size);
+ }
+ return AcquireUnifiedView(key, extents);
+}
+
+std::optional BufferCacheRuntime::AcquireUnifiedView(
+ u64 key, std::span extents) {
+ const VkBufferUsageFlags usage = unified_memory->GetViewUsage();
+ if (usage == 0 || !multi_range_buffers.use_sparse || extents.size() < 2) {
+ return std::nullopt;
+ }
+ const VkDeviceSize block = multi_range_buffers.block_size;
+ boost::container::small_vector sources;
+ VkDeviceSize total = 0;
+ VkDeviceSize padding = 0;
+ for (size_t index = 0; index < extents.size(); ++index) {
+ VkDeviceSize begin = extents[index].relative;
+ VkDeviceSize end = begin + extents[index].size;
+ if (index == 0) {
+ padding = begin % block;
+ begin -= padding;
+ } else if ((begin % block) != 0) {
+ return std::nullopt;
+ }
+ if (index + 1 == extents.size()) {
+ end = Common::AlignUp(end, block);
+ } else if ((end % block) != 0) {
+ return std::nullopt;
+ }
+ while (begin < end) {
+ const auto memory = unified_memory->ResolveViewMemory(begin);
+ if (!memory || (memory->offset % block) != 0) {
+ return std::nullopt;
+ }
+ const VkDeviceSize length = (std::min)(end - begin, memory->available);
+ if ((length % block) != 0) {
+ return std::nullopt;
+ }
+ sources.push_back(MultiRangeSource{
+ .handle = memory->buffer,
+ .memory = memory->memory,
+ .memory_offset = 0,
+ .offset = memory->offset,
+ .size = length,
+ .write_tick = 0,
+ .memory_type = memory->memory_type,
+ });
+ total += length;
+ begin += length;
+ }
+ }
+ const MultiRangeRef ref = multi_range_buffers.GetView(
+ device, scheduler, key, sources, total, usage,
+ VK_EXTERNAL_MEMORY_HANDLE_TYPE_ANDROID_HARDWARE_BUFFER_BIT_ANDROID);
+ if (ref.handle == VK_NULL_HANDLE) {
+ return std::nullopt;
+ }
+ return HostMemoryImport::Range{
+ .buffer = ref.handle,
+ .address = ref.address,
+ .offset = padding,
+ };
+}
+
+bool BufferCacheRuntime::StageUnifiedVertexBuffer(
+ u32 index, u64 key, std::span extents, u32 size, u32 stride,
+ bool force) {
+ if (!unified_memory ||
+ (unified_memory->GetUsage() & VK_BUFFER_USAGE_VERTEX_BUFFER_BIT) == 0) {
+ return false;
+ }
+ const auto range = ResolveUnifiedExtents(key, extents, size);
+ if (!range) {
+ return false;
+ }
+ StageVertexBuffer(
+ StagedVertexBuffer{
+ .index = index,
+ .buffer = range->buffer,
+ .offset = range->offset,
+ .size = size,
+ .stride = stride,
+ },
+ force);
+ return true;
+}
+
+bool BufferCacheRuntime::StageMultiRangeVertexBuffer(u32 index, u64 key, u32 size, u32 stride,
+ bool force) {
+ const MultiRangeRef ref = AcquireMultiRange(key, false);
+ if (ref.handle == VK_NULL_HANDLE) {
+ return false;
+ }
+ StageVertexBuffer(
+ StagedVertexBuffer{
+ .index = index,
+ .buffer = ref.handle,
+ .offset = 0,
+ .size = size,
+ .stride = stride,
+ },
+ force);
+ return true;
+}
+
+void BufferCacheRuntime::StageVertexBuffer(const StagedVertexBuffer& target, bool force) {
+ StagedVertexBuffer& bound = bound_vertex_buffers[target.index];
+ if (!force && bound == target) {
+ return;
+ }
+ bound = target;
+ if (target.index < device.GetMaxVertexInputBindings()) {
+ staged_vertex_buffers.push_back(target);
+ }
+}
+
+void BufferCacheRuntime::BindStagedVertexBuffers() {
+ if (staged_vertex_buffers.empty()) {
+ return;
+ }
+ scheduler.Record([staged = staged_vertex_buffers,
+ extended = device.IsExtExtendedDynamicStateSupported()](
+ vk::CommandBuffer cmdbuf) {
+ std::array buffers{};
+ std::array offsets{};
+ std::array sizes{};
+ std::array strides{};
+ size_t begin = 0;
+ while (begin < staged.size()) {
+ const u32 first = staged[begin].index;
+ u32 count = 0;
+ while (begin + count < staged.size() && staged[begin + count].index == first + count) {
+ const StagedVertexBuffer& entry = staged[begin + count];
+ buffers[count] = entry.buffer;
+ offsets[count] = entry.offset;
+ sizes[count] = entry.size;
+ strides[count] = entry.stride;
+ ++count;
+ }
+ if (extended) {
+ cmdbuf.BindVertexBuffers2EXT(first, count, buffers.data(), offsets.data(),
+ sizes.data(), strides.data());
+ } else {
+ cmdbuf.BindVertexBuffers(first, count, buffers.data(), offsets.data());
+ }
+ begin += count;
+ }
+ });
+ staged_vertex_buffers.clear();
+}
+
+bool BufferCacheRuntime::IsIndexRangeUsable(PrimitiveTopology topology, IndexFormat index_format,
+ VkDeviceSize offset, u32 size) const {
+ const VkIndexType vk_index_type = MaxwellToVK::IndexFormat(index_format);
+ const bool is_quad =
+ topology == PrimitiveTopology::Quads || topology == PrimitiveTopology::QuadStrip;
+ const bool is_emulated_uint8 =
+ vk_index_type == VK_INDEX_TYPE_UINT8_EXT && !device.IsExtIndexTypeUint8Supported();
+ if (is_quad || is_emulated_uint8) {
+ return size <= device.GetMaxStorageBufferRange() &&
+ (offset % device.GetStorageBufferAlignment()) == 0;
+ }
+ return (offset % BytesPerIndex(vk_index_type)) == 0;
+}
+
+bool BufferCacheRuntime::BindUnifiedIndexBuffer(PrimitiveTopology topology,
+ IndexFormat index_format, u32 base_vertex,
+ u32 num_indices, u64 key,
+ std::span extents,
+ u32 size) {
+ constexpr VkBufferUsageFlags GeometryUsage =
+ VK_BUFFER_USAGE_INDEX_BUFFER_BIT | VK_BUFFER_USAGE_STORAGE_BUFFER_BIT;
+ if (!unified_memory || (unified_memory->GetUsage() & GeometryUsage) != GeometryUsage) {
+ return false;
+ }
+ const auto range = ResolveUnifiedExtents(key, extents, size);
+ if (!range || range->offset > (std::numeric_limits::max)() - size ||
+ !IsIndexRangeUsable(topology, index_format, range->offset, size)) {
+ return false;
+ }
+ BindIndexBuffer(topology, index_format, base_vertex, num_indices, range->buffer,
+ static_cast(range->offset), size);
+ return true;
+}
+
+bool BufferCacheRuntime::BindMultiRangeIndexBuffer(PrimitiveTopology topology,
+ IndexFormat index_format, u32 base_vertex,
+ u32 num_indices, u64 key, u32 size) {
+ if (!IsIndexRangeUsable(topology, index_format, 0, size)) {
+ return false;
+ }
+ const MultiRangeRef ref = AcquireMultiRange(key, false);
+ if (ref.handle == VK_NULL_HANDLE) {
+ return false;
+ }
+ BindIndexBuffer(topology, index_format, base_vertex, num_indices, ref.handle, 0, size);
+ return true;
+}
+
void BufferCacheRuntime::BindIndexBuffer(PrimitiveTopology topology, IndexFormat index_format,
u32 base_vertex, u32 num_indices, VkBuffer buffer,
u32 offset, [[maybe_unused]] u32 size) {
diff --git a/src/video_core/renderer_vulkan/vk_buffer_cache.h b/src/video_core/renderer_vulkan/vk_buffer_cache.h
index fbd8c2e753..828bc0c339 100644
--- a/src/video_core/renderer_vulkan/vk_buffer_cache.h
+++ b/src/video_core/renderer_vulkan/vk_buffer_cache.h
@@ -7,6 +7,8 @@
#pragma once
#include
+#include
+#include
#include
@@ -110,6 +112,36 @@ public:
void TickFrame(Common::SlotVector& slot_buffers) noexcept;
+ void TryEnableUnifiedMemory(void* base, size_t size,
+ std::span hardware_buffers,
+ size_t hardware_buffer_window, size_t hardware_buffer_base);
+
+ [[nodiscard]] bool HasUnifiedMemory() const noexcept {
+ return unified_memory != nullptr && unified_memory->IsValid();
+ }
+
+ [[nodiscard]] u64 UnifiedMemorySize() const noexcept {
+ return unified_memory ? unified_memory->GetSize() : 0;
+ }
+
+ [[nodiscard]] u64 UnifiedMemoryBase() const noexcept {
+ return unified_memory ? unified_memory->GetBaseOffset() : 0;
+ }
+
+ [[nodiscard]] u64 UnifiedMemoryWindowSize() const noexcept {
+ return unified_memory ? unified_memory->GetWindowSize() : 0;
+ }
+
+ void CopyToUnifiedMemory(size_t window_index, VkBuffer src_buffer,
+ std::span copies);
+
+ void CopyFromUnifiedMemory(size_t window_index, VkBuffer dst_buffer,
+ std::span copies);
+
+ void FlushUnifiedMemoryCopies();
+
+ void UnifiedMemoryHostBarrier();
+
u64 CurrentTick();
u64 KnownGpuTick();
@@ -200,6 +232,21 @@ public:
bool BindMultiRangeStorageBuffer(u64 key, bool is_written);
+ bool StageUnifiedVertexBuffer(u32 index, u64 key,
+ std::span extents, u32 size,
+ u32 stride, bool force);
+
+ bool StageMultiRangeVertexBuffer(u32 index, u64 key, u32 size, u32 stride, bool force);
+
+ void BindStagedVertexBuffers();
+
+ bool BindUnifiedIndexBuffer(PrimitiveTopology topology, IndexFormat index_format,
+ u32 base_vertex, u32 num_indices, u64 key,
+ std::span extents, u32 size);
+
+ bool BindMultiRangeIndexBuffer(PrimitiveTopology topology, IndexFormat index_format,
+ u32 base_vertex, u32 num_indices, u64 key, u32 size);
+
void InvalidateMultiRange(u64 key) {
multi_range_buffers.Invalidate(key);
}
@@ -217,6 +264,28 @@ public:
BindBuffer(buffer, offset, size);
}
+ void BindStorageBuffer(VkBuffer buffer, VkDeviceAddress address, VkDeviceSize offset, u32 size,
+ [[maybe_unused]] bool is_written) {
+ guest_descriptor_queue.AddBuffer(buffer, address, offset, size);
+ }
+
+ [[nodiscard]] bool IsUnifiedMemoryBindable() const noexcept {
+ return unified_memory != nullptr && unified_memory->IsValid() &&
+ unified_memory->IsBindable();
+ }
+
+ [[nodiscard]] std::optional ResolveUnifiedStorage(u64 relative,
+ u32 size) const {
+ if (size > device.GetMaxStorageBufferRange()) {
+ return std::nullopt;
+ }
+ const auto range = unified_memory->ResolveRange(relative, size);
+ if (!range || (range->offset % device.GetStorageBufferAlignment()) != 0) {
+ return std::nullopt;
+ }
+ return range;
+ }
+
void BindTextureBuffer(Buffer& buffer, u32 offset, u32 size,
VideoCore::Surface::PixelFormat format) {
guest_descriptor_queue.AddTexelBuffer(buffer.View(offset, size, format),
@@ -233,6 +302,35 @@ public:
}
private:
+ struct PendingUnifiedCopy {
+ size_t window;
+ VkBuffer buffer;
+ boost::container::small_vector copies;
+ };
+
+ struct StagedVertexBuffer {
+ u32 index;
+ VkBuffer buffer;
+ VkDeviceSize offset;
+ u32 size;
+ u32 stride;
+
+ bool operator==(const StagedVertexBuffer&) const = default;
+ };
+
+ [[nodiscard]] MultiRangeRef AcquireMultiRange(u64 key, bool require_sparse);
+
+ [[nodiscard]] std::optional ResolveUnifiedExtents(
+ u64 key, std::span extents, u32 size);
+
+ [[nodiscard]] std::optional AcquireUnifiedView(
+ u64 key, std::span extents);
+
+ void StageVertexBuffer(const StagedVertexBuffer& target, bool force);
+
+ [[nodiscard]] bool IsIndexRangeUsable(PrimitiveTopology topology, IndexFormat index_format,
+ VkDeviceSize offset, u32 size) const;
+
void BindBuffer(const Buffer& buffer, u32 offset, u32 size) {
const VkBuffer handle = buffer.Handle();
if (handle == VK_NULL_HANDLE) {
@@ -257,6 +355,8 @@ private:
std::shared_ptr quad_strip_index_buffer;
vk::Buffer null_buffer;
+ HostMemoryImport* unified_memory{};
+ boost::container::small_vector pending_unified_copies;
std::unique_ptr uint8_pass;
QuadIndexedPass quad_index_pass;
@@ -264,6 +364,9 @@ private:
MultiRangeBufferCache multi_range_buffers;
boost::container::small_vector