nvn: fix uniform copy/oracle coherency, linear writeback ordering, and sparse sharing edge cases

Address review findings on PR #4:
- FrozenOracle / ApplyPendingInlineWrites: track exact byte ranges written
  by inline uniform updates so 4 KiB chunks with partial inline coverage stay
  unreadable outside written bytes while fully covered 4-byte handles resolve.
- DrawContext::BuildDescriptors / ExecutePlan: copy misaligned DeviceLocal and
  GPU-modified UBO ranges on the GPU (after flushing shadows, mirror uploads,
  and inline updates) instead of reading stale guest RAM.
- Recorder::SetRenderCondition, CopyBufferToTexture, DecodeBufferToTexture,
  CopyTextureToBuffer: flush overlapping linear write-backs across the full
  operation span after ending an open render pass.
- Recorder::FlushLinearWritebacks: sort pending storages by latest
  gpu_write_gen so repeated overlapping writes (A, B, A) preserve final order.
- Recorder::NotePoolWrite / CompleteMain: record strided row parameters for
  padded linear write-backs on Mirror pools so completion does not overwrite
  independent CPU edits to row-padding gaps.
- SparsePagePool / SparseBacking: track stale shared pages on guest writes,
  reject retained shared pages when a tile becomes unshareable, keep rebound
  tiles in BindSparse failure recovery, permit zero-allocation shared-key hits
  at full budget, and include host-block valid extents in SparseAliasKey.
- Tests: add regression coverage in compute_vulkan.cpp, vulkan.cpp, and
  memory.cpp.

VTX-HLE by Vortex727 (https://github.com/Vortex727/FUKKO)
This commit is contained in:
Rhys Denno committed 2026-11-19 11:55:16 -05:00
1 parent 15b4bde789
commit c2c72c2375
11 files changed
+477 -53

No files matched your search

+60
View File
@@ -4839,3 +4839,63 @@ TEST_CASE("NVN inline uniform: early submit does not split pending updates outsi
CHECK(rig.context.Stats().ops_failed == 0);
CHECK(rig.context.Stats().ops_unsupported == 0);
}
TEST_CASE("NVN inline uniform: misaligned DeviceLocal UBO preserves GPU writes plus inline update",
"[nvn][compute][inline]") {
auto vulkan = MakeHeadlessVulkan();
if (!vulkan) {
SKIP("no Vulkan device");
}
constexpr u64 UBO_OFFSET = 0x5040;
constexpr u64 UBO_VA = VERTEX_POOL_VA + UBO_OFFSET;
VertexMirrorRig rig(*vulkan, false, false, 0, std::nullopt, 1 /* POOL_CPU_NO_ACCESS */, false);
// ClearBuffer writes F32_FIVE (off-screen) to +0x00 on the GPU while guest RAM stays 0.0f.
// Losing GPU bytes to stale guest RAM would draw on-screen (1 sample) instead of clipping (0).
{
std::vector<u64> list;
VertexMirrorRig::PushTargetSetup(list, PROGRAM_UNIFORM_XY, UBO_OFFSET, 256);
Push(list, VC::Op::ClearBuffer,
VC::ClearBufferPayload{.address = UBO_VA + 0x00, .size = 256, .value = F32_FIVE});
Push(list, VC::Op::ResetCounter, VC::ResetCounterPayload{.counter_type = SAMPLES_PASSED});
VertexMirrorRig::PushInlineU32(list, UBO_VA + 0x10, F32_ONE_64TH);
Push(list, VC::Op::Draw,
VC::DrawPayload{.mode = 0, .first = 0, .count = 1, .instance_count = 1});
CHECK(rig.SubmitAndCount(list) == 0);
}
// Outside a pass: GPU ClearBuffer sets +0x00 to 1/64, inline update sets +0x10 to 1/64.
{
std::vector<u64> list;
VertexMirrorRig::PushTargetSetup(list, PROGRAM_UNIFORM_XY, UBO_OFFSET, 256);
Push(list, VC::Op::ClearBuffer,
VC::ClearBufferPayload{.address = UBO_VA + 0x00, .size = 256, .value = F32_FIVE});
Push(list, VC::Op::ClearBuffer,
VC::ClearBufferPayload{.address = UBO_VA + 0x00, .size = 4, .value = F32_ONE_64TH});
Push(list, VC::Op::ResetCounter, VC::ResetCounterPayload{.counter_type = SAMPLES_PASSED});
VertexMirrorRig::PushInlineU32(list, UBO_VA + 0x10, F32_ONE_64TH);
Push(list, VC::Op::Draw,
VC::DrawPayload{.mode = 0, .first = 0, .count = 1, .instance_count = 1});
CHECK(rig.SubmitAndCount(list) == 1);
}
// Inside an open pass: pass ends, inline updates flush, and GPU copy preserves both.
{
std::vector<u64> list;
VertexMirrorRig::PushTargetSetup(list, PROGRAM_UNIFORM_XY, UBO_OFFSET, 256);
Push(list, VC::Op::ClearBuffer,
VC::ClearBufferPayload{.address = UBO_VA + 0x00, .size = 256, .value = F32_FIVE});
Push(list, VC::Op::ClearBuffer,
VC::ClearBufferPayload{.address = UBO_VA + 0x00, .size = 4, .value = F32_ONE_64TH});
Push(list, VC::Op::ResetCounter, VC::ResetCounterPayload{.counter_type = SAMPLES_PASSED});
Push(list, VC::Op::Draw,
VC::DrawPayload{.mode = 0, .first = 0, .count = 1, .instance_count = 1});
VertexMirrorRig::PushInlineU32(list, UBO_VA + 0x10, F32_ONE_64TH);
Push(list, VC::Op::Draw,
VC::DrawPayload{.mode = 0, .first = 0, .count = 1, .instance_count = 1});
CHECK(rig.SubmitAndCount(list) == 1);
}
CHECK(rig.context.Stats().ops_failed == 0);
CHECK(rig.context.Stats().ops_unsupported == 0);
}
+45
View File
@@ -2415,3 +2415,48 @@ TEST_CASE("MKW buffer lookup cache follows pool replacement and virtual remaps",
REQUIRE_FALSE(impl->ResolveBuffer(0x3fff0, 32, pool, offset));
resolve(0x3fff0, 16, 2, 0xfff0);
}
TEST_CASE("SparsePagePool tracks stale shared pages, IsShared, and full-budget key hits",
"[nvn][sparse]") {
auto vulkan = MakeHeadlessVulkan();
if (!vulkan) {
SKIP("no Vulkan device");
}
Nvn::Context::Impl impl(*vulkan->device, vulkan->submit_mutex, nullptr,
{.background_backing = false});
Nvn::SparsePagePool pool(*impl.allocator, Nvn::SparsePagePool::PageBytes);
const Nvn::SparseAliasKey key_a{0x1000'0000ULL, 0xABCDULL};
const Nvn::SparseAliasKey key_b{0x2000'0000ULL, 0xABCDULL};
bool reused = false;
const u32 page = pool.AcquireShared(key_a, ~0u, 1, reused);
REQUIRE(page != Nvn::SparsePagePool::NoPage);
CHECK_FALSE(reused);
CHECK(pool.IsShared(page));
CHECK_FALSE(pool.HasRoom());
CHECK(pool.AcquireShared(key_a, ~0u, 2, reused, false) == page);
CHECK(reused);
pool.Free(page);
CHECK(pool.AcquireShared(key_b, ~0u, 2, reused, false) == Nvn::SparsePagePool::NoPage);
CHECK_FALSE(reused);
pool.MarkSharedStale(page);
CHECK(pool.AcquireShared(key_a, ~0u, 3, reused, false) == page);
CHECK_FALSE(reused);
pool.Free(page);
pool.ClearSharedStale(page);
CHECK(pool.AcquireShared(key_a, ~0u, 3, reused, false) == page);
CHECK(reused);
pool.Free(page);
CHECK(pool.Allocate(~0u) == Nvn::SparsePagePool::NoPage);
pool.Free(page);
CHECK(pool.HasRoom());
const u32 priv = pool.Allocate(~0u);
REQUIRE(priv != Nvn::SparsePagePool::NoPage);
CHECK_FALSE(pool.IsShared(priv));
pool.Free(priv);
}
+93
View File
@@ -1517,6 +1517,99 @@ void RunLinearTextureWriteback(HeadlessVulkan& vulkan, bool allow_import) {
REQUIRE(actual == cpu_texel);
}
// Submission 4: Overlapping linear storages written A, B, A must flush in write order
// so A's final value wins over B's earlier write.
constexpr u64 TEX_LINEAR_A = 13;
constexpr u64 TEX_LINEAR_B = 14;
constexpr u64 OVERLAP_OFFSET = 32768;
context.CreateTexture(make_rgba16f(TEX_LINEAR_A, OVERLAP_OFFSET,
Vulkan::Nvn::TexFlag::LinearRenderTarget, STRIDE));
context.CreateTexture(make_rgba16f(TEX_LINEAR_B, OVERLAP_OFFSET,
Vulkan::Nvn::TexFlag::LinearRenderTarget, STRIDE));
{
std::vector<u64> list;
auto push_clear = [&](u64 serial, float r, float g, float b, float a) {
VC::ClearTexturePayload clear{};
clear.texture = {.serial = serial, .level = 0, .layer = 0};
clear.region = {0, 0, 0, static_cast<s32>(WIDTH), static_cast<s32>(HEIGHT), 1};
clear.layer_count = 1;
clear.is_integer = 0;
const float color[4] = {r, g, b, a};
std::memcpy(clear.color, color, sizeof(color));
Push(list, VC::Op::ClearTexture, clear, 0xF);
};
push_clear(TEX_LINEAR_A, 1.0f, -0.5f, 0.25f, 2.0f);
push_clear(TEX_LINEAR_B, 0.5f, -1.0f, 0.0f, 4.0f);
push_clear(TEX_LINEAR_A, 0.25f, 0.5f, 1.0f, 2.0f);
PushEnd(list);
context.Submit(MakeSubmission(4, 0, std::move(list), {TEX_LINEAR_A, TEX_LINEAR_B}));
REQUIRE(context.Wait(4, 20s));
}
check_linear_guest(OVERLAP_OFFSET, cpu_texel);
if (!allow_import) {
// Submission 5: Padded mirror readback writes only the valid texel rows, preserving CPU
// modifications written to row padding gaps between capture and completion.
constexpr u64 EVENT_VA = READBACK_VA + 12288;
class GapHookMemory final : public VC::GuestMemory {
public:
GapHookMemory(VC::GuestMemory& inner_, u8* gap_byte_)
: inner{inner_}, gap_byte{gap_byte_} {}
bool Read(u64 va, void* dst, size_t size) override {
if (va == EVENT_VA && size == sizeof(u32) && !injected.exchange(true)) {
*gap_byte = 0x77;
const u32 signaled = 1;
std::memcpy(dst, &signaled, sizeof(signaled));
return true;
}
return inner.Read(va, dst, size);
}
bool Write(u64 va, const void* src, size_t size) override {
return inner.Write(va, src, size);
}
u8* Pointer(u64 va) override {
return inner.Pointer(va);
}
VC::GuestMemory& inner;
u8* gap_byte;
std::atomic<bool> injected{false};
} gap_hook{memory, tex_mem + RT_OFFSET + ROW_BYTES + 4};
context.SetGuestMemory(&gap_hook);
std::vector<u64> list;
VC::ClearTexturePayload clear{};
clear.texture = {.serial = TEX_LINEAR_RT, .level = 0, .layer = 0};
clear.region = {0, 0, 0, static_cast<s32>(WIDTH), static_cast<s32>(HEIGHT), 1};
clear.layer_count = 1;
clear.is_integer = 0;
const float color[4] = {0.5f, -1.0f, 0.0f, 4.0f};
std::memcpy(clear.color, color, sizeof(color));
Push(list, VC::Op::ClearTexture, clear, 0xF);
// Copy 4 bytes out of RT_OFFSET to force FlushLinearWritebacks (and mirror capture) before
// WaitEvent reads EVENT_VA.
Push(list, VC::Op::CopyBufferToBuffer,
VC::CopyBufferToBufferPayload{.src = TEX_POOL_VA + RT_OFFSET,
.dst = READBACK_VA + 8192,
.size = 4});
PushWaitEvent(list, EVENT_VA, VC::EVENT_WAIT_EQUAL, 1);
PushEnd(list);
context.Submit(MakeSubmission(5, 0, std::move(list), {TEX_LINEAR_RT}));
REQUIRE(context.Wait(5, 20s));
CHECK(gap_hook.injected.load());
CHECK(tex_mem[RT_OFFSET + ROW_BYTES + 4] == 0x77);
context.SetGuestMemory(&memory);
for (u32 y = 0; y < HEIGHT; ++y) {
const u8* row = tex_mem + RT_OFFSET + y * STRIDE;
for (u32 x = 0; x < WIDTH; ++x) {
std::array<u16, 4> actual{};
std::memcpy(actual.data(), row + x * sizeof(actual), sizeof(actual));
REQUIRE(actual == expected_copy);
}
}
}
REQUIRE(context.Stats().ops_failed == 0);
context.SetGuestMemory(nullptr);
}
@@ -1212,7 +1212,19 @@ void Context::Impl::CompleteMain() {
VC::GuestMemory* memory = guest.load(std::memory_order_acquire);
for (const InFlight::Readback& readback : flight->readbacks) {
const u8* source = mapped.data() + readback.download_offset;
if (readback.pool->host) {
if (readback.row_count > 0 && readback.row_bytes > 0) {
for (u32 row = 0; row < readback.row_count; ++row) {
const u64 rel = static_cast<u64>(row) * readback.row_stride;
const u64 len = (std::min)(readback.row_bytes, readback.size - rel);
if (readback.pool->host) {
std::memcpy(readback.pool->host + readback.pool_offset + rel,
source + rel, static_cast<size_t>(len));
} else if (memory) {
memory->Write(readback.pool->address + readback.pool_offset + rel,
source + rel, static_cast<size_t>(len));
}
}
} else if (readback.pool->host) {
std::memcpy(readback.pool->host + readback.pool_offset, source, readback.size);
} else if (memory) {
memory->Write(readback.pool->address + readback.pool_offset, source,
@@ -2431,7 +2443,8 @@ bool Context::Impl::NeedsGpuFlushForUniform(u64 begin, u64 end, u64 current_seq)
}
void Context::Impl::ApplyPendingInlineWrites(u64 base_address, u8* dst, u64 size,
u64 current_seq) const {
u64 current_seq,
std::vector<std::pair<u64, u64>>* written) const {
if (size == 0 || dst == nullptr || pending_pool_writes.empty()) {
return;
}
@@ -2446,6 +2459,9 @@ void Context::Impl::ApplyPendingInlineWrites(u64 base_address, u8* dst, u64 size
std::memcpy(dst + (lo - base_address),
write.inline_bytes.data() + (lo - write.begin),
static_cast<size_t>(hi - lo));
if (written != nullptr) {
written->emplace_back(lo - base_address, hi - base_address);
}
}
}
}
@@ -384,8 +384,28 @@ constexpr u64 FROZEN_CHUNK = 4096;
class FrozenOracle final : public TextureOracle {
public:
struct Uniform {
std::vector<u8> bytes; ///< the bound range (inline updates applied)
std::vector<u8> readable; ///< per FROZEN_CHUNK: guest memory could be read
std::vector<u8> bytes; ///< the bound range (inline updates applied)
std::vector<u8> readable; ///< per FROZEN_CHUNK: guest memory could be read
std::vector<std::pair<u64, u64>> inline_written; ///< byte spans written by inline updates
[[nodiscard]] bool WordReadable(u64 offset) const noexcept {
for (u64 byte = offset; byte < offset + sizeof(u32); ++byte) {
if (readable[byte / FROZEN_CHUNK] != 0) {
continue;
}
bool covered = false;
for (const auto& [lo, hi] : inline_written) {
if (lo <= byte && byte < hi) {
covered = true;
break;
}
}
if (!covered) {
return false;
}
}
return true;
}
};
struct Stage {
std::array<u32, 64> combined{};
@@ -449,11 +469,8 @@ private:
if (u64{offset} + sizeof(u32) > uniform.bytes.size()) {
return std::nullopt;
}
for (u64 at = offset / FROZEN_CHUNK; at <= (offset + sizeof(u32) - 1) / FROZEN_CHUNK;
++at) {
if (!uniform.readable[at]) {
return std::nullopt;
}
if (!uniform.WordReadable(offset)) {
return std::nullopt;
}
u32 value;
std::memcpy(&value, uniform.bytes.data() + offset, sizeof(value));
@@ -525,11 +542,15 @@ std::unique_ptr<TextureOracle> DrawContext::FreezeOracle(
}
uniform.bytes.resize(size);
uniform.readable.assign((size + FROZEN_CHUNK - 1) / FROZEN_CHUNK, 0);
uniform.inline_written.clear();
bool all_readable = false;
if (ReadSnapshotBytes(binding.address, uniform.bytes.data(), size)) {
std::fill(uniform.readable.begin(), uniform.readable.end(), u8{1});
all_readable = true;
} else {
if (memory->Read(binding.address, uniform.bytes.data(), size)) {
std::fill(uniform.readable.begin(), uniform.readable.end(), u8{1});
all_readable = true;
} else {
for (u64 chunk = 0; chunk < uniform.readable.size(); ++chunk) {
const u64 begin = chunk * FROZEN_CHUNK;
@@ -542,8 +563,9 @@ std::unique_ptr<TextureOracle> DrawContext::FreezeOracle(
}
}
if (host != nullptr) {
impl.ApplyPendingInlineWrites(binding.address, uniform.bytes.data(), size,
host->HostFlight().seq);
impl.ApplyPendingInlineWrites(
binding.address, uniform.bytes.data(), size, host->HostFlight().seq,
all_readable ? nullptr : &uniform.inline_written);
}
}
// Inline updates of this submission are newer than guest memory; the last one wins.
@@ -553,9 +575,9 @@ std::unique_ptr<TextureOracle> DrawContext::FreezeOracle(
if (lo < hi) {
std::memcpy(uniform.bytes.data() + (lo - binding.address),
update.data + (lo - update.address), hi - lo);
for (u64 chunk = (lo - binding.address) / FROZEN_CHUNK;
chunk <= (hi - 1 - binding.address) / FROZEN_CHUNK; ++chunk) {
uniform.readable[chunk] = 1;
if (!all_readable) {
uniform.inline_written.emplace_back(lo - binding.address,
hi - binding.address);
}
}
}
@@ -1046,12 +1068,31 @@ bool DrawContext::BuildDescriptors(PipelineBase& pipe, DrawPlan& plan, bool grap
}
const bool misaligned = resolved && uniform && (ref.offset % 256) != 0;
const u64 current_seq = host->HostFlight().seq;
const bool needs_gpu_source =
resolved && !write && snapshot_range == UniformSnapshotView::npos &&
(ref.pool->backing == Pool::Backing::DeviceLocal ||
HasOverlappingShadow(*ref.pool, ref.pool_offset, ref.pool_offset + size) ||
impl.NeedsGpuFlushForUniform(binding.address, binding.address + size, current_seq));
if (misaligned && needs_gpu_source) {
const BufferRef copy = AllocArena(size, 256, nullptr);
if (copy.buffer) {
if (overlaps) {
plan.flush_inline = true;
}
plan.UseRange(ref.pool, ref.pool_offset, size, false, DrawPlan::RangeUse::NO_INFO,
false, false);
plan.uniform_copies.push_back(
{ref.buffer, ref.offset, copy.buffer, copy.offset, size});
if (cs_mode != CostSplit::Mode::Count) [[unlikely]] {
CostSplitNote(CostSplit::Data::Uniform, ref, size, true);
}
return VkDescriptorBufferInfo{copy.buffer, copy.offset, size};
}
}
bool flush_inline_to_pool = false;
if (overlaps && !misaligned && resolved && !write &&
snapshot_range == UniformSnapshotView::npos) {
if (!pass_open || ref.pool->backing == Pool::Backing::DeviceLocal ||
HasOverlappingShadow(*ref.pool, ref.pool_offset, ref.pool_offset + size) ||
impl.NeedsGpuFlushForUniform(binding.address, binding.address + size, current_seq)) {
if (!pass_open || needs_gpu_source) {
flush_inline_to_pool = true;
plan.flush_inline = true;
}
@@ -1783,7 +1824,7 @@ bool DrawContext::PrepareOutsidePass(DrawPlan& plan) {
need = true;
}
}
if (plan.flush_inline && !inline_updates.empty()) {
if ((plan.flush_inline && !inline_updates.empty()) || !plan.uniform_copies.empty()) {
if (!need) {
cause = BreakCause::InlineUpdate;
}
@@ -1856,6 +1897,18 @@ bool DrawContext::PrepareOutsidePass(DrawPlan& plan) {
if (shadow.any) {
ApplyShadows(plan, true);
}
if (!plan.uniform_copies.empty()) {
host->HostFlushBarrier();
for (const DrawPlan::UniformCopy& copy : plan.uniform_copies) {
const VkBufferCopy region{
.srcOffset = copy.src_offset,
.dstOffset = copy.dst_offset,
.size = copy.size,
};
host->HostCmd().CopyBuffer(copy.src, copy.dst, region);
}
host->HostMarkWritten();
}
// A dispatch orders after earlier dispatches only as NVN does (behind a game barrier);
// the replay's own commands above flushed for themselves.
if (plan.graphics) {
@@ -77,10 +77,19 @@ struct DrawPlan {
/// to a 1x1x1 3D scratch (1) or to every face of a cube scratch (6).
u32 retype_layers{0};
};
/// GPU copies to arena uniform buffers for misaligned GPU-owned/DeviceLocal ranges.
struct UniformCopy {
VkBuffer src;
u64 src_offset;
VkBuffer dst;
u64 dst_offset;
u64 size;
};
std::vector<ImageUse> images;
std::vector<RangeUse> ranges;
std::vector<ImageBinding> bindings;
std::vector<FeedbackCopy> feedback;
std::vector<UniformCopy> uniform_copies;
/// Allocated descriptor set (pipelines that cannot push), filled by PushPlan.
VkDescriptorSet set{VK_NULL_HANDLE};
/// The plan is for a graphics draw (false: a dispatch); only the fallback counters read it.
@@ -111,6 +120,7 @@ struct DrawPlan {
ranges.clear();
bindings.clear();
feedback.clear();
uniform_copies.clear();
set = VK_NULL_HANDLE;
raw_global_writes = false;
raw_stores_written_through = false;
@@ -104,9 +104,10 @@ constexpr VkBufferUsageFlags SHADOW_USAGE =
VK_BUFFER_USAGE_VERTEX_BUFFER_BIT | VK_BUFFER_USAGE_INDEX_BUFFER_BIT;
constexpr VkBufferUsageFlags ARENA_USAGE =
VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT |
VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_INDEX_BUFFER_BIT |
VK_BUFFER_USAGE_VERTEX_BUFFER_BIT | VK_BUFFER_USAGE_INDIRECT_BUFFER_BIT;
VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT |
VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT | VK_BUFFER_USAGE_STORAGE_BUFFER_BIT |
VK_BUFFER_USAGE_INDEX_BUFFER_BIT | VK_BUFFER_USAGE_VERTEX_BUFFER_BIT |
VK_BUFFER_USAGE_INDIRECT_BUFFER_BIT;
VkSamplerAddressMode WrapMode(u32 nvn) {
switch (nvn) {
@@ -640,8 +640,10 @@ private:
/// The replay wrote a pool range on the GPU (through the pool's own buffer unless
/// `invalidate_mirror` is false: a pool mirror's write-back, after which the mirror and the
/// guest bytes agree).
void NotePoolWrite(Pool& pool, u64 offset, u64 size, bool invalidate_mirror = true);
void NotePoolWrite(Pool& pool, u64 offset, u64 size, bool invalidate_mirror = true,
u64 row_bytes = 0, u64 row_stride = 0, u32 row_count = 0);
void NoteTouched(const std::shared_ptr<Storage>& storage);
[[nodiscard]] bool HasLinearWritebackOverlapping(const Pool& pool, u64 begin, u64 end) const;
/// Writes GPU-modified linear storages in CPU-readable pools back to their pools so guest
/// CPU readers (and intra-submission buffer ops over those addresses) see the GPU's texels.
void FlushLinearWritebacks(const Pool* filter_pool = nullptr, u64 filter_begin = 0,
@@ -749,7 +751,7 @@ private:
/// CopyBufferToTexture into a decoded stand-in (ASTC/BCn): decodes the source blocks on the
/// CPU.
bool DecodeBufferToTexture(Storage& s, u32 level, u32 layer,
const VC::CopyBufferTexturePayload& p, const Pool& pool, u64 offset);
const VC::CopyBufferTexturePayload& p, Pool& pool, u64 offset);
void ClearTexture(const VC::ClearTexturePayload& p);
void ClearTexturePartial(Storage& s, u32 level, u32 layer, u32 layer_count, u32 x, u32 y,
@@ -1454,7 +1456,8 @@ void Recorder::UploadRange(Pool& pool, u64 offset, u64 size) {
barrier_pending = true;
}
void Recorder::NotePoolWrite(Pool& pool, u64 offset, u64 size, bool invalidate_mirror) {
void Recorder::NotePoolWrite(Pool& pool, u64 offset, u64 size, bool invalidate_mirror,
u64 row_bytes, u64 row_stride, u32 row_count) {
impl.NoteNonInlinePoolWrite(pool.address + offset, size, flight.seq);
if (impl.invalidate_wait_ms != 0) {
// Where a guest invalidate has to wait for this submission (nvn_gpu_writes.h).
@@ -1494,11 +1497,13 @@ void Recorder::NotePoolWrite(Pool& pool, u64 offset, u64 size, bool invalidate_m
dirty_pool_set.insert(&pool);
for (const InFlight::Readback& existing : readbacks) {
if (existing.pool.get() == &pool && existing.pool_offset == offset &&
existing.size == size) {
existing.size == size && existing.row_bytes == row_bytes &&
existing.row_stride == row_stride && existing.row_count == row_count) {
return;
}
}
readbacks.push_back({impl.pools.at(pool.serial), offset, size, download_size});
readbacks.push_back({impl.pools.at(pool.serial), offset, size, download_size, row_bytes,
row_stride, row_count});
download_size += (size + 15) / 16 * 16;
break;
}
@@ -1910,6 +1915,17 @@ void Recorder::NoteGpuWrite(Storage& s) {
}
}
bool Recorder::HasLinearWritebackOverlapping(const Pool& pool, u64 begin, u64 end) const {
for (const std::shared_ptr<Storage>& owner : linear_writebacks) {
const Storage& s = *owner;
const u64 s_end = s.pool_offset + s.layout.size;
if (s.pool_serial == pool.serial && s.pool_offset < end && begin < s_end) {
return true;
}
}
return false;
}
void Recorder::FlushLinearWritebacks(const Pool* filter_pool, u64 filter_begin, u64 filter_end) {
if (linear_writebacks.empty()) {
return;
@@ -1935,6 +1951,11 @@ void Recorder::FlushLinearWritebacks(const Pool* filter_pool, u64 filter_begin,
}
linear_writebacks = std::move(remaining);
}
if (pending.size() > 1) {
std::ranges::stable_sort(pending, {}, [](const std::shared_ptr<Storage>& entry) {
return entry->gpu_write_gen;
});
}
for (std::shared_ptr<Storage>& owner : pending) {
Storage& s = *owner;
if (!s.image || s.origin != StorageOrigin::Gpu) {
@@ -1989,7 +2010,11 @@ void Recorder::FlushLinearWritebacks(const Pool* filter_pool, u64 filter_begin,
track_writes = saved;
Cmd().CopyImageToBuffer(*s.image, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, pool->Handle(),
geometry.regions);
NotePoolWrite(*pool, s.pool_offset, geometry.span);
if (geometry.padded) {
NotePoolWrite(*pool, s.pool_offset, geometry.span, true, row_bytes, stride, copy_rows);
} else {
NotePoolWrite(*pool, s.pool_offset, geometry.span);
}
barrier_pending = true;
}
}
@@ -3900,6 +3925,10 @@ void Recorder::CopyBufferToTexture(const VC::CopyBufferTexturePayload& p) {
Failed("CopyBufferToTexture", "source range leaves the memory pool");
return;
}
if (HasLinearWritebackOverlapping(*pool, offset, offset + geometry.span)) {
EndDrawPass();
FlushLinearWritebacks(pool, offset, offset + geometry.span);
}
const LevelExtent extent = ExtentOfLevel(s, level);
const bool covers_level =
p.region.x <= 0 && p.region.y <= 0 &&
@@ -3914,7 +3943,7 @@ void Recorder::CopyBufferToTexture(const VC::CopyBufferTexturePayload& p) {
}
bool Recorder::DecodeBufferToTexture(Storage& s, u32 level, u32 layer,
const VC::CopyBufferTexturePayload& p, const Pool& pool,
const VC::CopyBufferTexturePayload& p, Pool& pool,
u64 offset) {
const BlockInfo block = FormatBlockInfo(s.desc.format);
if (!block.bytes || s.samples != VK_SAMPLE_COUNT_1_BIT) {
@@ -3979,9 +4008,13 @@ bool Recorder::DecodeBufferToTexture(Storage& s, u32 level, u32 layer,
Failed("CopyBufferToTexture", "source range leaves the memory pool");
return false;
}
if (HasLinearWritebackOverlapping(pool, offset, offset + span)) {
EndDrawPass();
FlushLinearWritebacks(&pool, offset, offset + span);
}
{
// The CPU reads the blocks: bytes a submission still in flight writes would be stale.
std::scoped_lock lock{const_cast<Pool&>(pool).dirty_mutex};
std::scoped_lock lock{pool.dirty_mutex};
for (const Pool::Dirty& dirty : pool.gpu_dirty) {
if (dirty.begin < offset + span && dirty.end > offset) {
Unsupported("CopyBufferToTexture",
@@ -4098,6 +4131,10 @@ void Recorder::CopyTextureToBuffer(const VC::CopyBufferTexturePayload& p) {
Failed("CopyTextureToBuffer", "destination range leaves the memory pool");
return;
}
if (HasLinearWritebackOverlapping(*pool, offset, offset + geometry.span)) {
EndDrawPass();
FlushLinearWritebacks(pool, offset, offset + geometry.span);
}
EnsureContents(s, false);
if (geometry.padded) {
// Bytes between rows are not written: the mirror must hold the guest's version of them.
@@ -4810,7 +4847,9 @@ void Recorder::SetRenderCondition(const VC::SetRenderConditionPayload& p) {
// noted as a write yet.
if (ahead != nullptr &&
engine->SlotsAllocated() <= ahead->position + CounterEngine::SLOT_COUNT &&
!draw.InlineUpdatePending(p.address, CounterEngine::REPORT_PAIR_SPAN)) {
!draw.InlineUpdatePending(p.address, CounterEngine::REPORT_PAIR_SPAN) &&
!HasLinearWritebackOverlapping(*pool_a, offset_a, offset_a + sizeof(u64)) &&
!HasLinearWritebackOverlapping(*pool_b, offset_b, offset_b + sizeof(u64))) {
// Computed ahead, nothing wrote its report pair since and its slot still holds it: the
// predicate this point would compute, without a pass break or any command.
condition_slot = ahead->slot;
@@ -4819,6 +4858,10 @@ void Recorder::SetRenderCondition(const VC::SetRenderConditionPayload& p) {
return;
}
EndDrawPass(BreakCause::RenderCondition);
if (!linear_writebacks.empty()) {
FlushLinearWritebacks(pool_a, offset_a, offset_a + sizeof(u64));
FlushLinearWritebacks(pool_b, offset_b, offset_b + sizeof(u64));
}
// CPU-written counters of mirrored pools must reach the mirror first.
UploadRange(*pool_a, offset_a, sizeof(u64));
UploadRange(*pool_b, offset_b, sizeof(u64));
@@ -4826,6 +4869,10 @@ void Recorder::SetRenderCondition(const VC::SetRenderConditionPayload& p) {
return;
}
EndDrawPass(BreakCause::RenderCondition);
if (!linear_writebacks.empty()) {
FlushLinearWritebacks(pool_a, offset_a, offset_a + sizeof(u64));
FlushLinearWritebacks(pool_b, offset_b, offset_b + sizeof(u64));
}
UploadRange(*pool_a, offset_a, sizeof(u64));
UploadRange(*pool_b, offset_b, sizeof(u64));
EvaluateConditionOnCpu(*pool_a, offset_a, *pool_b, offset_b, p.mode & 1);
@@ -415,6 +415,9 @@ struct InFlight {
u64 pool_offset;
u64 size;
u64 download_offset;
u64 row_bytes{0};
u64 row_stride{0};
u32 row_count{0};
};
u64 seq{};
@@ -1034,7 +1037,8 @@ struct Context::Impl {
void InvalidatePendingInlineBytesOverlapping(u64 address, u64 size);
void ErasePendingPoolWritesForSeq(u64 seq);
[[nodiscard]] bool NeedsGpuFlushForUniform(u64 begin, u64 end, u64 current_seq);
void ApplyPendingInlineWrites(u64 base_address, u8* dst, u64 size, u64 current_seq) const;
void ApplyPendingInlineWrites(u64 base_address, u8* dst, u64 size, u64 current_seq,
std::vector<std::pair<u64, u64>>* written = nullptr) const;
/// Draw state per NVN queue index (it persists across submissions on a queue).
std::map<u32, std::unique_ptr<DrawContext>> draw_contexts;
std::map<u32, QueueState> queues;
+102 -17
View File
@@ -91,31 +91,60 @@ u32 SparsePagePool::Allocate(u32 memory_type_bits) {
}
u32 SparsePagePool::AcquireShared(const SparseAliasKey& key, u32 memory_type_bits, u64 epoch,
bool& reused) {
bool& reused, bool allow_alloc) {
std::scoped_lock lock{mutex_};
if (const auto found = by_key_.find(key); found != by_key_.end()) {
const u32 page = found->second;
++refs_[page];
++shared_extra_refs_;
reused = epoch_[page] < epoch;
reused = epoch_[page] < epoch && stale_[page] == 0;
return page;
}
reused = false;
if (!allow_alloc) {
return NoPage;
}
const u32 page = AllocateLocked(memory_type_bits);
if (page != NoPage) {
by_key_.emplace(key, page);
key_of_.emplace(page, key);
epoch_[page] = epoch;
stale_[page] = 0;
}
return page;
}
bool SparsePagePool::IsShared(u32 page) const {
std::scoped_lock lock{mutex_};
return key_of_.contains(page);
}
bool SparsePagePool::HoldsKey(u32 page, const SparseAliasKey& key) const {
std::scoped_lock lock{mutex_};
const auto found = key_of_.find(page);
return found != key_of_.end() && found->second == key;
}
void SparsePagePool::MarkSharedStale(u32 page) {
if (page == NoPage) {
return;
}
std::scoped_lock lock{mutex_};
if (page < stale_.size()) {
stale_[page] = 1;
}
}
void SparsePagePool::ClearSharedStale(u32 page) {
if (page == NoPage) {
return;
}
std::scoped_lock lock{mutex_};
if (page < stale_.size()) {
stale_[page] = 0;
}
}
u32 SparsePagePool::AllocateLocked(u32 memory_type_bits) {
if (used_ + PageBytes > budget_) {
return NoPage;
@@ -135,6 +164,7 @@ u32 SparsePagePool::AllocateLocked(u32 memory_type_bits) {
}
used_ += PageBytes;
refs_[page] = 1;
stale_[page] = 0;
return page;
}
}
@@ -166,8 +196,10 @@ u32 SparsePagePool::AllocateLocked(u32 memory_type_bits) {
if (refs_.size() < blocks_.size() * PagesPerBlock) {
refs_.resize(blocks_.size() * PagesPerBlock, 0);
epoch_.resize(blocks_.size() * PagesPerBlock, 0);
stale_.resize(blocks_.size() * PagesPerBlock, 0);
}
refs_[first] = 1;
stale_[first] = 0;
used_ += PageBytes;
return first;
}
@@ -183,6 +215,7 @@ void SparsePagePool::Free(u32 page) {
return;
}
refs_[page] = 0;
stale_[page] = 0;
if (const auto found = key_of_.find(page); found != key_of_.end()) {
by_key_.erase(found->second);
key_of_.erase(found);
@@ -478,12 +511,30 @@ void SparseBacking::SetMapped(u8& flags, u32 id, bool tail, bool mapped) {
}
}
void SparseBacking::SetTilePagesStale(u32 id, bool stale) {
if (!share_ || !pool_) {
return;
}
const u32 slots = host_per_x_ * host_per_y_;
const u32* pages = &tile_pages_[static_cast<size_t>(id) * slots];
for (u32 slot = 0; slot < slots; ++slot) {
if (stale) {
pool_->MarkSharedStale(pages[slot]);
} else {
pool_->ClearSharedStale(pages[slot]);
}
}
}
void SparseBacking::ContentChanged(u64 begin, u64 end) {
layout_.ForEachUnit(
begin, end,
[&](u32 id) {
if ((tile_flags_[id] & Mapped) != 0) {
tile_flags_[id] |= Dirty;
if ((tile_flags_[id] & Bound) != 0) {
SetTilePagesStale(id, true);
}
Queue(tile_flags_[id], id, false);
}
},
@@ -502,6 +553,9 @@ void SparseBacking::MarkAllDirty() {
void SparseBacking::MarkTileDirty(u32 id) {
if ((tile_flags_[id] & Mapped) != 0) {
tile_flags_[id] |= Dirty;
if ((tile_flags_[id] & Bound) != 0) {
SetTilePagesStale(id, true);
}
Queue(tile_flags_[id], id, false);
}
}
@@ -573,8 +627,11 @@ bool SparseBacking::TilePagesCurrent(Context::Impl& impl, const Storage& s, u32
return false;
}
// A private page stays right for an unshareable tile; a shared one only for its key.
const bool holds = shareable && pool_->HoldsKey(page, KeyOf(source, tile.slot));
if (shareable != holds) {
if (shareable) {
if (!pool_->HoldsKey(page, KeyOf(source, tile.slot, tile.width, tile.height))) {
return false;
}
} else if (pool_->IsShared(page)) {
return false;
}
}
@@ -583,7 +640,8 @@ bool SparseBacking::TilePagesCurrent(Context::Impl& impl, const Storage& s, u32
bool SparseBacking::BindUnit(Context::Impl& impl, const Storage& s, bool tail, u32 id, bool bind,
std::vector<VkSparseImageMemoryBind>& image_binds,
std::vector<VkSparseMemoryBind>& opaque_binds, bool* reused) {
std::vector<VkSparseMemoryBind>& opaque_binds, bool* reused,
bool allow_alloc) {
const u32 layer = tail ? id : layout_.Tile(id).layer;
std::span<const HostTile> tiles;
u32 slots = 0;
@@ -616,16 +674,17 @@ bool SparseBacking::BindUnit(Context::Impl& impl, const Storage& s, bool tail, u
bool all_reused = shared;
const u64 epoch = impl.sparse_prepare_epoch;
// Memory for every host block first: a failure leaves nothing bound.
const auto need = [&](u32 index) {
const auto need = [&](u32 index, u32 width, u32 height) {
if (pages[index] == SparsePagePool::NoPage) {
if (shared) {
bool page_reused = false;
pages[index] =
pool_->AcquireShared(KeyOf(source, index), memory_type_bits_, epoch,
page_reused);
pages[index] = pool_->AcquireShared(KeyOf(source, index, width, height),
memory_type_bits_, epoch, page_reused,
allow_alloc);
all_reused = all_reused && page_reused;
} else {
pages[index] = pool_->Allocate(memory_type_bits_);
pages[index] = allow_alloc ? pool_->Allocate(memory_type_bits_)
: SparsePagePool::NoPage;
}
} else {
all_reused = false;
@@ -637,10 +696,10 @@ bool SparseBacking::BindUnit(Context::Impl& impl, const Storage& s, bool tail, u
}
bool ok = true;
for (const HostTile& tile : tiles) {
ok = ok && need(tile.slot);
ok = ok && need(tile.slot, tile.width, tile.height);
}
for (u32 i = 0; ok && i < opaque_count; ++i) {
ok = need(static_cast<u32>(tiles.size()) + i);
ok = need(static_cast<u32>(tiles.size()) + i, 0, 0);
}
if (!ok) {
for (u32 i = 0; i < slots; ++i) {
@@ -689,6 +748,11 @@ bool SparseBacking::Prepare(Context::Impl& impl, const Storage& s, Uploads& uplo
std::vector<VkSparseImageMemoryBind> image_binds;
std::vector<VkSparseMemoryBind> opaque_binds;
std::vector<std::pair<bool, u32>> bound_now;
struct ReboundTile {
u32 id;
std::vector<u32> old_pages;
};
std::vector<ReboundTile> rebound_now;
u64 binds = 0;
u64 unbinds = 0;
// The first unit that finds no page ends the allocating of this call; the generation is read
@@ -714,9 +778,9 @@ bool SparseBacking::Prepare(Context::Impl& impl, const Storage& s, Uploads& uplo
std::vector<u32> old(pages, pages + slots);
std::fill(pages, pages + slots, SparsePagePool::NoPage);
const u64 bound_before = bound_pages_;
if (!exhausted &&
BindUnit(impl, s, false, id, true, image_binds, opaque_binds, &reused)) {
deferred_free_.insert(deferred_free_.end(), old.begin(), old.end());
if (BindUnit(impl, s, false, id, true, image_binds, opaque_binds, &reused,
!exhausted && pool_->HasRoom())) {
rebound_now.push_back({id, std::move(old)});
bound_pages_ = bound_before; // as many blocks bound as before
++binds;
} else {
@@ -729,8 +793,10 @@ bool SparseBacking::Prepare(Context::Impl& impl, const Storage& s, Uploads& uplo
continue;
}
} else if (want && !have) {
if (exhausted || !pool_->HasRoom() ||
!BindUnit(impl, s, tail, id, true, image_binds, opaque_binds, &reused)) {
const bool allow_alloc = !exhausted && pool_->HasRoom();
if ((!allow_alloc && (!share_ || tail)) ||
!BindUnit(impl, s, tail, id, true, image_binds, opaque_binds, &reused,
allow_alloc)) {
exhausted = true;
if (!std::exchange(starved_logged_, true)) {
LOG_WARNING(Render_Vulkan,
@@ -842,11 +908,24 @@ bool SparseBacking::Prepare(Context::Impl& impl, const Storage& s, Uploads& uplo
for (const auto& [tail, id] : bound_now) {
u8& flags = tail ? tail_flags_[id] : tile_flags_[id];
flags &= static_cast<u8>(~Bound);
if ((flags & Mapped) != 0) {
flags |= Dirty;
}
Queue(flags, id, tail);
std::vector<VkSparseImageMemoryBind> unused_image;
std::vector<VkSparseMemoryBind> unused_opaque;
BindUnit(impl, s, tail, id, false, unused_image, unused_opaque);
}
const u32 slots = host_per_x_ * host_per_y_;
for (const ReboundTile& rebound : rebound_now) {
u32* const pages = &tile_pages_[static_cast<size_t>(rebound.id) * slots];
for (u32 i = 0; i < slots; ++i) {
pool_->Free(pages[i]);
}
std::copy(rebound.old_pages.begin(), rebound.old_pages.end(), pages);
tile_flags_[rebound.id] |= Dirty;
Queue(tile_flags_[rebound.id], rebound.id, false);
}
uploads.tiles.clear();
uploads.tails.clear();
for (const u32 page : deferred_free_) {
@@ -858,6 +937,11 @@ bool SparseBacking::Prepare(Context::Impl& impl, const Storage& s, Uploads& uplo
impl.stats.virtual_sparse_binds.fetch_add(image_binds.size() + opaque_binds.size(),
std::memory_order_relaxed);
}
for (const ReboundTile& rebound : rebound_now) {
for (const u32 page : rebound.old_pages) {
pool_->Free(page);
}
}
for (const u32 page : deferred_free_) {
pool_->Free(page);
}
@@ -870,6 +954,7 @@ bool SparseBacking::Prepare(Context::Impl& impl, const Storage& s, Uploads& uplo
}
for (const u32 id : uploads.tiles) {
tile_flags_[id] &= static_cast<u8>(~Dirty);
SetTilePagesStale(id, false);
}
for (const u32 id : uploads.tails) {
tail_flags_[id] &= static_cast<u8>(~Dirty);
@@ -66,9 +66,13 @@ public:
/// reference). `reused`: the page existed before replay step `epoch`, so its texels were
/// uploaded or written earlier in the command stream. NoPage when out of memory.
[[nodiscard]] u32 AcquireShared(const SparseAliasKey& key, u32 memory_type_bits, u64 epoch,
bool& reused);
bool& reused, bool allow_alloc = true);
/// Whether `page` is currently held in the shared key map (regardless of key).
[[nodiscard]] bool IsShared(u32 page) const;
/// Whether `page` is the shared page of `key`.
[[nodiscard]] bool HoldsKey(u32 page, const SparseAliasKey& key) const;
void MarkSharedStale(u32 page);
void ClearSharedStale(u32 page);
/// Drops one reference; the page is free when the last one goes.
void Free(u32 page);
/// Bytes saved by sharing: references beyond the first of each shared page.
@@ -114,6 +118,7 @@ private:
std::vector<u32> free_;
std::vector<u32> refs_; ///< per page: references (0 free)
std::vector<u64> epoch_; ///< per shared page: the replay step that allocated it
std::vector<u8> stale_; ///< per shared page: owning tile has un-uploaded guest changes
std::unordered_map<SparseAliasKey, u32, SparseAliasKeyHash> by_key_;
std::unordered_map<u32, SparseAliasKey> key_of_;
u64 shared_extra_refs_{0};
@@ -235,13 +240,18 @@ private:
std::vector<u32>& TilePages(u32 id);
bool BindUnit(Context::Impl& impl, const Storage& s, bool tail, u32 id, bool bind,
std::vector<VkSparseImageMemoryBind>& image_binds,
std::vector<VkSparseMemoryBind>& opaque_binds, bool* reused = nullptr);
std::vector<VkSparseMemoryBind>& opaque_binds, bool* reused = nullptr,
bool allow_alloc = true);
/// The guest address of tile `id`'s 64 KiB, when one physical run maps all of it.
bool TileSource(Context::Impl& impl, const Storage& s, u32 id, u64& source) const;
/// The alias key of host block `slot` of a tile whose bytes are at `source`.
[[nodiscard]] SparseAliasKey KeyOf(u64 source, u32 slot) const {
return {source, shape_ ^ (static_cast<u64>(slot + 1) * 0xC2B2AE3D27D4EB4FULL)};
/// The alias key of host block `slot` of valid extent (`width`, `height`) whose bytes are at
/// `source`.
[[nodiscard]] SparseAliasKey KeyOf(u64 source, u32 slot, u32 width, u32 height) const {
u64 key_shape = shape_ ^ (static_cast<u64>(slot + 1) * 0xC2B2AE3D27D4EB4FULL);
key_shape ^= ((static_cast<u64>(width) << 32) | height) * 0x9E3779B97F4A7C15ULL;
return {source, key_shape};
}
void SetTilePagesStale(u32 id, bool stale);
/// Whether the bound pages of tile `id` still hold the bytes its guest mapping points at.
bool TilePagesCurrent(Context::Impl& impl, const Storage& s, u32 id);