Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
111 changes: 97 additions & 14 deletions runtime/shims/d3d12_vulkan_device.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -10127,6 +10127,14 @@ struct TitleTexture {
std::uint64_t full_hash = 0;
bool full_hashed = false;
bool every_byte() const { return mapped && layout.layout.size <= (4u << 20); }
bool rolling_hash() const { return mapped && !every_byte(); }
leonida::TitleTextureChunkHashes chunk_hashes;
std::uint64_t source_revision = 0; // Map, written Unmap or a replacement texture layout
void layout_changed() {
++source_revision;
hashed = false;
chunk_hashes = {};
}
std::uint64_t fills = 0;
};

Expand Down Expand Up @@ -10163,14 +10171,15 @@ void DeviceState::title_texture_mapped(const void* resource, std::uint64_t addre
if (it == title_textures.end() || it->second->resource != resource) return;
TitleTexture& t = *it->second;
t.mapped = true;
++t.source_revision;
t.memory.retry();
// The title computes the layout of what it writes right before it maps: take it when no view gave one.
if (!t.gpu_written && (t.layout_guessed || !t.layout_known) &&
title_xg_layout(*static_cast<const Resource*>(resource), t.layout, t.desc)) {
t.layout_known = true;
t.layout_guessed = false;
t.layout_from_xg = true;
t.hashed = false;
t.layout_changed();
}
static std::atomic<int> logged{0};
if (logged.fetch_add(1, std::memory_order_relaxed) < 48) {
Expand All @@ -10196,6 +10205,7 @@ void DeviceState::title_texture_unmapped(const void* resource, std::uint64_t add
std::lock_guard lock(title_texture_mutex);
const auto it = title_textures.find(address);
if (it != title_textures.end() && it->second->resource == resource) {
++it->second->source_revision;
it->second->stale = true;
it->second->memory.retry();
}
Expand Down Expand Up @@ -11938,6 +11948,8 @@ class Device final
const auto entries = leonida::title_texture_snapshot(state_.title_textures);
title_pass_ = true;
std::uint64_t checked = 0, filled = 0, fill_pass_ns = 0;
TitleTexture* first_rolling = nullptr;
TitleTexture* next_rolling = nullptr;
const auto visit = [&](TitleTexture& t) {
// A slot-133 texture's guessed layout (no slot-70 view yet) is only used once the title maps it.
if (t.gpu_written || !t.layout_known || !t.resource ||
Expand Down Expand Up @@ -11970,7 +11982,14 @@ class Device final
t.memory.defer();
return;
}
if (t.hashed && hash == t.hash && !t.stale) {
const bool rolling = t.rolling_hash();
if (t.hashed && hash == t.hash && !t.stale && (!rolling || t.chunk_hashes.ready())) {
if (rolling) {
// A single exhaustive chunk across all large mapped textures, after the usual checks.
if (!first_rolling) first_rolling = &t;
if (!next_rolling && t.address >= title_rolling_cursor_) next_rolling = &t;
return;
}
if (!t.every_byte() || stats.passes % 6) return;
std::uint64_t full = 0;
checked += span;
Expand Down Expand Up @@ -12035,6 +12054,12 @@ class Device final
++stats.every_pass_visits;
visit(*entry.second);
}
if (TitleTexture* t = next_rolling ? next_rolling : first_rolling) {
title_rolling_cursor_ = t->address + 1;
const auto start = clock::now();
checked += check_title_chunk(*t);
stats.hash_ns += std::chrono::duration_cast<std::chrono::nanoseconds>(clock::now() - start).count();
}
stats.every_pass_ns += std::chrono::duration_cast<std::chrono::nanoseconds>(clock::now() - every_start).count();
// The budget is the round robin's: mapped and stale textures above are checked every pass whatever it is.
const auto first_bytes = checked, first_hash_ns = stats.hash_ns;
Expand Down Expand Up @@ -12162,8 +12187,8 @@ class Device final
// still has that resource. Others (host copies, unbound memory) are filled under the lock as before.
Resource* r = nullptr;
rt::xg_xs::Texture layout{};
std::uint64_t cpu = 0, fills = 0;
bool every_byte = false;
std::uint64_t cpu = 0;
TitleFillVersion version;
{
std::lock_guard lock(state_.title_texture_mutex);
const InTitleTextures inside;
Expand All @@ -12178,16 +12203,16 @@ class Device final
r->AddRef();
layout = t.layout;
cpu = t.cpu;
fills = t.fills;
every_byte = t.every_byte();
version = {t.fills, t.source_revision, leonida::title_memory_map::generation(),
t.every_byte(), t.rolling_hash()};
} else {
filled = fill_title_texture(t, true) != 0;
}
}
}
}
if (r) {
filled = fill_unlocked(address, *r, layout, cpu, fills, every_byte, f);
filled = fill_unlocked(address, *r, layout, cpu, version, f);
r->Release();
}
std::size_t left = 0;
Expand All @@ -12208,20 +12233,35 @@ class Device final
}
}

struct TitleFillVersion {
std::uint64_t fills = 0, source_revision = 0, map_generation = 0;
bool every_byte = false, rolling = false;
};

static bool title_mapping_unchanged(std::uint64_t generation, std::uint64_t base, std::uint64_t span) {
if (generation == leonida::title_memory_map::generation()) return true;
std::uint64_t now = 0;
bool overlaps = false;
return leonida::title_memory_map::changes_since(generation, now, base, base + span,
[&](auto, auto) { overlaps = true; }) && !overlaps;
}

// The fill worker's fill of a staged texture: copy, hash and upload without the registry lock, then the result
// under it, if the registry still names `r` at `address` and nobody filled it meanwhile.
bool fill_unlocked(std::uint64_t address, Resource& r, const rt::xg_xs::Texture& layout, std::uint64_t cpu,
std::uint64_t fills, bool every_byte, TitleFiller& f) {
TitleFillVersion version, TitleFiller& f) {
const std::uint64_t span = layout.layout.size;
f.tiled.resize(std::size_t(span));
const bool copied = copy_guarded(f.tiled.data(), reinterpret_cast<const std::uint8_t*>(cpu), std::size_t(span),
title_memory_write_combined(cpu));
std::uint64_t hash = 0, full = 0;
bool full_hashed = false, ok = false, nonzero = false;
leonida::TitleTextureChunkHashes chunk_hashes;
std::uint64_t staged_ns = 0;
if (copied) {
hash_guarded(f.tiled.data(), f.tiled.size(), hash);
full_hashed = every_byte && hash_guarded(f.tiled.data(), f.tiled.size(), full, true);
full_hashed = version.every_byte && hash_guarded(f.tiled.data(), f.tiled.size(), full, true);
if (version.rolling) snapshot_title_chunks(chunk_hashes, f.tiled);
const auto start = std::chrono::steady_clock::now();
ok = r.upload_staged_title(layout, f.tiled.data(), f.columns, false, nonzero);
staged_ns = std::chrono::duration_cast<std::chrono::nanoseconds>(std::chrono::steady_clock::now() - start)
Expand All @@ -12245,12 +12285,21 @@ class Device final
return false;
}
++title_stats_.staged_fills;
if (t.fills != fills) return true; // another fill recorded itself in between: its hash is as good
if ((version.rolling || t.rolling_hash()) &&
(t.fills != version.fills || t.source_revision != version.source_revision ||
!title_mapping_unchanged(version.map_generation, cpu, span))) {
// This upload may have become visible after the intervening one. Refill from the current layout
// rather than trusting a digest from a different upload or from before the first large Map.
t.stale = true;
return true;
}
if (t.fills != version.fills) return true; // another fill recorded itself in between: its hash is as good
if (t.owned && !t.fills) r.publish_streamed_texture();
t.hash = hash;
t.hashed = true;
t.full_hash = full;
t.full_hashed = full_hashed;
t.chunk_hashes = std::move(chunk_hashes);
++t.fills;
++title_stats_.fills;
title_stats_.fill_bytes += span;
Expand Down Expand Up @@ -12297,6 +12346,7 @@ class Device final
geometry_refresher_->wake.notify_one();
}
std::uint64_t title_refresh_cursor_ = 0; // under title_texture_mutex
std::uint64_t title_rolling_cursor_ = 0; // likewise
std::uint64_t title_map_generation_ = 0; // likewise: the map changes the passes have seen
std::chrono::steady_clock::time_point title_retry_all_{}; // likewise
leonida::TitleWriteRanges title_map_changes_; // likewise, scratch
Expand Down Expand Up @@ -12392,7 +12442,7 @@ class Device final
t->desc = words;
t->layout_known = true;
t->layout_guessed = t->layout_from_xg = false;
t->hashed = false;
t->layout_changed();
} else {
refuse_title_view(why, d, address); // counted; the view of its image is still written
}
Expand Down Expand Up @@ -12607,6 +12657,32 @@ class Device final
if (!t.hashed || hash != t.hash || t.stale) fill_title_texture(t, true);
}

static void snapshot_title_chunks(leonida::TitleTextureChunkHashes& chunks,
const std::vector<std::uint8_t>& snapshot) {
chunks.snapshot(snapshot.size(), [&](std::size_t offset, std::size_t bytes) {
return hash_bytes(snapshot.data() + offset, bytes, true);
});
}

std::size_t check_title_chunk(TitleTexture& t) {
const auto chunk = t.chunk_hashes.next();
const auto address = t.cpu + chunk.offset;
const auto* bytes = reinterpret_cast<const std::uint8_t*>(static_cast<std::uintptr_t>(address));
std::uint64_t hash = 0;
bool ok = false;
// Stream from WC pages into cached scratch before hashing, just as the upload copy does.
if (title_memory_write_combined(address)) {
if (title_tiled_.size() < chunk.bytes) title_tiled_.resize(chunk.bytes);
ok = copy_guarded(title_tiled_.data(), bytes, chunk.bytes, true);
if (ok) hash = hash_bytes(title_tiled_.data(), chunk.bytes, true);
} else {
ok = hash_guarded(bytes, chunk.bytes, hash, true);
}
if (!ok) t.memory.defer();
else if (hash != chunk.hash) t.stale = true; // Use the next pass's normal priority upload.
return chunk.bytes;
}

// Snapshot the whole footprint before uploading any subresource. A concurrent unmap defers the fill.
// Private title staging bypasses the D3D12 submit callbacks. Generic staged copies require an outer fill.
std::uint64_t fill_title_texture(TitleTexture& t, bool staged) {
Expand All @@ -12620,6 +12696,8 @@ class Device final
}
const std::uint64_t span = layout.layout.size;
if (!title_texture_readable(t)) return 0;
const bool rolling = t.rolling_hash();
const auto map_generation = rolling ? leonida::title_memory_map::generation() : 0;
title_tiled_.resize(std::size_t(span));
if (!copy_guarded(title_tiled_.data(), reinterpret_cast<const std::uint8_t*>(t.cpu), std::size_t(span),
title_memory_write_combined(t.cpu))) {
Expand Down Expand Up @@ -12687,9 +12765,14 @@ class Device final
static_cast<unsigned long long>(t.cpu), static_cast<unsigned long long>(span),
int(staged), int(nonzero));
if (t.owned && !t.fills) t.resource->publish_streamed_texture();
t.hash = hash;
t.hashed = true;
t.stale = false;
if (rolling && !title_mapping_unchanged(map_generation, t.cpu, span)) {
t.stale = true;
} else {
if (rolling) snapshot_title_chunks(t.chunk_hashes, title_tiled_);
t.hash = hash;
t.hashed = true;
t.stale = false;
}
++t.fills;
++title_stats_.fills;
title_stats_.fill_bytes += span;
Expand Down
37 changes: 37 additions & 0 deletions runtime/src/title_texture_refresh.h
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
#pragma once
#include <algorithm>
#include <cstddef>
#include <cstdint>
#include <utility>
#include <vector>
Expand Down Expand Up @@ -28,6 +29,42 @@ inline bool title_write_overlaps(const TitleWriteRanges& writes, std::uintptr_t
return begin < end && it != writes.end() && it->first < end;
}

// Each digest describes a chunk of the last successful upload, never a subsequently observed CPU snapshot.
class TitleTextureChunkHashes {
public:
static constexpr std::size_t chunk_bytes = 256u << 10;

struct Chunk {
std::size_t offset, bytes;
std::uint64_t hash;
};

bool ready() const { return !hashes_.empty(); }

template<class Hash>
void snapshot(std::size_t bytes, Hash hash) {
bytes_ = bytes;
next_ = 0;
hashes_.resize(bytes / chunk_bytes + (bytes % chunk_bytes != 0));
for (std::size_t i = 0; i < hashes_.size(); ++i) {
const auto offset = i * chunk_bytes;
hashes_[i] = hash(offset, std::min(chunk_bytes, bytes - offset));
}
}

// The caller checks ready() first. A failed read still advances so later chunks get their turn.
Chunk next() {
const auto index = next_;
next_ = index + 1 == hashes_.size() ? 0 : index + 1;
const auto offset = index * chunk_bytes;
return {offset, std::min(chunk_bytes, bytes_ - offset), hashes_[index]};
}

private:
std::vector<std::uint64_t> hashes_;
std::size_t bytes_ = 0, next_ = 0;
};

// The registry's entries as one pass will visit them, in placement order. A pass cannot walk the registry itself: a
// fill it makes can submit, a submission destroys a retired image, and that image's destructor erases its entry
// (DeviceState::title_texture_gone). Windows' mutex is recursive for its owner, so the erase lands inside the pass and
Expand Down
66 changes: 65 additions & 1 deletion runtime/test/d3d12_existing_heap_test.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1402,6 +1402,55 @@ int check_mapped_plane(ID3D12Device* device) {
return 0;
}

// The last chunk contains a texel outside the periodic hash's two per-page samples and final 64 bytes.
int check_large_mapped_texture(ID3D12Device* device) {
const char* who = "large persistent slot-133 texture";
constexpr UINT width = 2048, height = 1024, pitch = width * 4, size = pitch * height;
constexpr UINT missed = size - pitch + 128;
const auto release_pages = [](void* p) { VirtualFree(p, 0, MEM_RELEASE); };
std::unique_ptr<void, decltype(release_pages)> pages(
VirtualAlloc(nullptr, size, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE), release_pages);
EXPECT(pages);
GpuReader gpu;
EXPECT(!gpu.init(device, size));
D3D12_RESOURCE_DESC desc{};
desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D;
desc.Width = width;
desc.Height = height;
desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
desc.SampleDesc.Count = desc.DepthOrArraySize = desc.MipLevels = 1;
leonida::title_xg_layouts::note({UINT(desc.Dimension), UINT(desc.Format), height, 1, 1, width}, 1);
Ref<ID3D12Resource> texture;
EXPECT_HR(rt::d3d12::create_buffer_at_host_address(device, pages.get(), desc, 6, IID_PPV_ARGS(&texture.p)), S_OK);
void* mapped = nullptr;
EXPECT_HR(texture->Map(0, nullptr, &mapped), S_OK);
EXPECT(mapped == pages.get());
auto* pixels = static_cast<std::uint8_t*>(mapped);
std::memset(pixels, 0x18, size);
ID3D12CommandList* lists[]{gpu.list.p};
auto submit = [&](UINT64 fence) {
gpu.queue->ExecuteCommandLists(1, lists);
return SUCCEEDED(gpu.queue->Signal(gpu.fence.p, fence)) &&
SUCCEEDED(gpu.fence->SetEventOnCompletion(fence, gpu.done)) &&
WaitForSingleObject(gpu.done, 30000) == WAIT_OBJECT_0;
};
std::vector<std::uint8_t> readback(size);
EXPECT(submit(1));
EXPECT_HR(texture->ReadFromSubresource(readback.data(), pitch, size, 0, nullptr), S_OK);
EXPECT(readback[missed] == 0x18);
pixels[missed] = 0x41; // Leave the original Map open and send no write notification.
// Here there is one large mapped texture. 32 chunks cover its 8 MiB, then the next pass uploads it.
for (UINT64 fence = 2; fence <= 34; ++fence) EXPECT(submit(fence));
EXPECT_HR(texture->ReadFromSubresource(readback.data(), pitch, size, 0, nullptr), S_OK);
EXPECT(readback[missed] == 0x41);
pixels[0] = 0x52; // A sampled change still refreshes on the very next pass.
EXPECT(submit(35));
EXPECT_HR(texture->ReadFromSubresource(readback.data(), pitch, size, 0, nullptr), S_OK);
EXPECT(readback[0] == 0x52);
texture->Unmap(0, nullptr);
return 0;
}

// Several threads write the same watched pages while submissions keep making them read-only again. Two threads that
// fault on one page race: the first fault reopens it, a submission can protect it again before the second fault is
// handled, and the second write must still be retried, not refused (refused, the process ends: seen natively). After
Expand Down Expand Up @@ -1990,7 +2039,8 @@ void print_cases(const std::vector<Case>& cases, const char* who) {

int main(int argc, char** argv) {
const bool prefix_only = argc == 2 && std::strcmp(argv[1], "--host-prefix-only") == 0;
if (argc != 1 && !prefix_only) return 2;
const bool large_mapped_only = argc == 2 && std::strcmp(argv[1], "--large-mapped-only") == 0;
if (argc != 1 && !prefix_only && !large_mapped_only) return 2;
_putenv_s("LEONIDA_TITLE_TEXTURE_PERIOD_MS", "0");
_putenv_s("LEONIDA_TITLE_TEXTURE_CHECK_KB", "0");
vktest::Device vk;
Expand Down Expand Up @@ -2018,6 +2068,18 @@ int main(int argc, char** argv) {
const int result = check_host_prefix_buffers(ours.p);
return result || vk.validation_errors() ? 1 : 0;
}
if (large_mapped_only) {
if (vk.host_image_copy) {
std::puts("large persistent slot-133 texture: host copies available");
failures += check_large_mapped_texture(ours.p);
}
info.host_image_copy = false;
Ref<ID3D12Device> staged;
if (FAILED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&staged.p)))) return 1;
std::puts("large persistent slot-133 texture: forced staged copies");
failures += check_large_mapped_texture(staged.p);
return failures || vk.validation_errors() ? 1 : 0;
}
failures += check(ours.p, "vulkan");
const std::vector<Case> vulkan_cases = open_cases(ours.p);
print_cases(vulkan_cases, "vulkan");
Expand All @@ -2028,6 +2090,7 @@ int main(int argc, char** argv) {
failures += check_pending_stream_views(ours.p);
failures += check_shared_bc_placements(ours.p);
failures += check_mapped_plane(ours.p);
failures += check_large_mapped_texture(ours.p);
failures += check_mapped_bc_array(ours.p);
}
{
Expand All @@ -2037,6 +2100,7 @@ int main(int argc, char** argv) {
Ref<ID3D12Device> staged;
if (FAILED(rt::d3d12::create_vulkan_device(no_host_copy, IID_PPV_ARGS(&staged.p)))) return 1;
failures += check_mapped_plane(staged.p);
failures += check_large_mapped_texture(staged.p);
failures += check_mapped_bc_array(staged.p);
}
failures += check_written_pages_all(ours.p);
Expand Down
Loading