From 9646d23c9522c27a03acce52e1f781ebcb2ad8a9 Mon Sep 17 00:00:00 2001 From: c1 Date: Thu, 26 Nov 2026 09:43:50 +0100 Subject: [PATCH 1/8] perf: remember a refused buffer memory SRV for a short, validated time A refused slot-70 buffer SRV repeated the placement scans and the memory questions on every call. A bounded negative cache, keyed by the request and validated by the placement generation and a region-information stamp, answers the repeat; any change misses and runs the full path. --- CMakeLists.txt | 9 ++ src/startup_stubs/d3d12_capture.inl | 3 + src/startup_stubs/d3d12_memory_srv.inl | 41 ++++++ src/startup_stubs/d3d12_xs_device.cpp | 4 +- src/startup_stubs/placed_buffer_range.h | 17 +++ src/startup_stubs/srv_refusal_cache.h | 126 +++++++++++++++++ tests/startup_srv_refusal_cache_check.cpp | 165 ++++++++++++++++++++++ 7 files changed, 364 insertions(+), 1 deletion(-) create mode 100644 src/startup_stubs/srv_refusal_cache.h create mode 100644 tests/startup_srv_refusal_cache_check.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 132ea73d76..8607ce6fba 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -2134,6 +2134,15 @@ foreach(mutation IN ITEMS height exact-fit first-32 unplaced-extent unplaced-cov add_test(NAME startup_memory_srv_buffer_${mutation}_control COMMAND startup_memory_srv_buffer_check --mutate ${mutation}) set_tests_properties(startup_memory_srv_buffer_${mutation}_control PROPERTIES WILL_FAIL TRUE) endforeach() +# Negative cache of refused buffer memory SRVs (src/startup_stubs/srv_refusal_cache.h); the mutated runs are negative controls. +add_executable(startup_srv_refusal_cache_check tests/startup_srv_refusal_cache_check.cpp) +target_include_directories(startup_srv_refusal_cache_check PRIVATE src) +target_compile_features(startup_srv_refusal_cache_check PRIVATE cxx_std_17) +add_test(NAME startup_srv_refusal_cache COMMAND startup_srv_refusal_cache_check) +foreach(mutation IN ITEMS generation commit key age hits invalid) + add_test(NAME startup_srv_refusal_cache_${mutation}_control COMMAND startup_srv_refusal_cache_check --mutate ${mutation}) + set_tests_properties(startup_srv_refusal_cache_${mutation}_control PROPERTIES WILL_FAIL TRUE) +endforeach() # Descriptor word 3 for formatted buffer loads (src/startup_stubs/buffer_format_word3.h); the mutated run must fail. add_executable(startup_buffer_format_word3_check tests/startup_buffer_format_word3_check.cpp) target_include_directories(startup_buffer_format_word3_check PRIVATE src) diff --git a/src/startup_stubs/d3d12_capture.inl b/src/startup_stubs/d3d12_capture.inl index a5b9479404..4ca6a1b904 100644 --- a/src/startup_stubs/d3d12_capture.inl +++ b/src/startup_stubs/d3d12_capture.inl @@ -281,11 +281,13 @@ void index_resource(const Wrapper* w, const ResourceInfo& info) const u64 base = reinterpret_cast(w->own().title_memory); if (!base || resource_index_check_mode() == 2) return; resource_address_index().insert(base, resource_index_extent(info), w); + x2w_startup::note_placement_change(); } void note_resource(Wrapper* w, const D3D12_RESOURCE_DESC* console, u64 bytes) { if (!w || !console) return; x2w_startup::ExclusiveNoteLock guard(note_lock); + x2w_startup::note_placement_change(); const ResourceInfo info{*console, bytes}; // Record and index change together or not at all (store_indexed); mode 2 leaves the index out. x2w_startup::store_indexed(resource_address_index(), resource_infos(), static_cast(w), @@ -306,6 +308,7 @@ void retire_placement(Wrapper* w) } } found->second.placement = Placement::none; + x2w_startup::note_placement_change(); } ReleaseSRWLockExclusive(¬e_lock); } diff --git a/src/startup_stubs/d3d12_memory_srv.inl b/src/startup_stubs/d3d12_memory_srv.inl index 1252190e86..e55a5ec75a 100644 --- a/src/startup_stubs/d3d12_memory_srv.inl +++ b/src/startup_stubs/d3d12_memory_srv.inl @@ -287,6 +287,7 @@ void clear_unplaced_buffers(Wrapper* device) } it->resource.Reset(); it = unplaced_buffers.erase(it); + x2w_startup::note_placement_change(); } else { ++it; } @@ -435,6 +436,7 @@ Wrapper* unplaced_memory_buffer(Wrapper* device, u64 address, u64 span_bytes, co } unplaced_buffers.push_back(UnplacedBufferEntry{device, memory.base, page_start, page_span, is_upload, native_resource, w}); + x2w_startup::note_placement_change(); return w; } @@ -669,6 +671,37 @@ void publish_as_srv(Wrapper* self, const D3D12_RESOURCE_DESC* resource, const Me view_slot<18, 2>(self, 0, reinterpret_cast(&resolved), destination, 0); } +// Refused buffer SRVs are remembered for a short time (srv_refusal_cache.h): the same view of the same address is +// published every frame, and each refusal used to repeat the placement scans and the memory questions. +x2w_startup::SrvRefusalCache& buffer_refusal_cache() +{ + static x2w_startup::SrvRefusalCache cache; + return cache; +} + +x2w_startup::SrvRefusalKey buffer_refusal_key(const D3D12_RESOURCE_DESC& resource, const MemoryShaderResourceView& input, u64 span_bytes) +{ + const auto& view = input.view; + x2w_startup::SrvRefusalKey key; + key.address = input.address; + key.span_bytes = span_bytes; + key.view_a = (u64{static_cast(view.Format)} << 32) | (u64{static_cast(view.ViewDimension)} << 16) | view.Shader4ComponentMapping; + key.view_b = view.Buffer.FirstElement; + key.view_c = (u64{view.Buffer.NumElements} << 32) | (u64{view.Buffer.StructureByteStride} << 8) | static_cast(view.Buffer.Flags); + key.resource_a = (u64{static_cast(resource.Dimension)} << 32) | static_cast(resource.Flags); + key.resource_b = resource.Width; + return key; +} + +// The generation first, then the memory: a change between the two reads makes the entry stale, never fresh. +x2w_startup::SrvRefusalStamp buffer_refusal_stamp(u64 address) +{ + x2w_startup::SrvRefusalStamp stamp; + stamp.generation = x2w_startup::srv_placement_generation().load(std::memory_order_acquire); + stamp.valid = x2w_startup::region_stamp(reinterpret_cast(address), stamp.base, stamp.size, stamp.commit, stamp.flags); + return stamp; +} + void __stdcall device_memory_srv(Wrapper* self, const D3D12_RESOURCE_DESC* resource, const MemoryShaderResourceView* input, u64 destination) { @@ -700,6 +733,13 @@ void __stdcall device_memory_srv(Wrapper* self, const D3D12_RESOURCE_DESC* resou if (resource->Dimension == D3D12_RESOURCE_DIMENSION_BUFFER) { const u64 elem_bytes = x2w_startup::buffer_srv_element_bytes(input->view); const u64 span_bytes = (input->view.Buffer.FirstElement + input->view.Buffer.NumElements) * elem_bytes; + const auto refusal_key = buffer_refusal_key(*resource, *input, span_bytes); + const auto refusal_stamp = buffer_refusal_stamp(input->address); + if (buffer_refusal_cache().hit(refusal_key, refusal_stamp, GetTickCount64())) { + refuse_memory_srv(refused, "unavailable buffer at the supplied address", "buffer_unavailable", resource, input, + destination); + return; + } Wrapper* buffer = existing_memory_buffer(self, input->address, span_bytes); if (!buffer) { buffer = unplaced_memory_buffer(self, input->address, span_bytes, *resource); @@ -709,6 +749,7 @@ void __stdcall device_memory_srv(Wrapper* self, const D3D12_RESOURCE_DESC* resou if (!buffer || !info || !x2w_startup::resolve_buffer_srv_desc(reinterpret_cast(buffer->own().title_memory), info->console.Width, input->address, input->view, adjusted)) { + buffer_refusal_cache().note(refusal_key, refusal_stamp, GetTickCount64()); refuse_memory_srv(refused, "unavailable buffer at the supplied address", "buffer_unavailable", resource, input, destination); return; diff --git a/src/startup_stubs/d3d12_xs_device.cpp b/src/startup_stubs/d3d12_xs_device.cpp index b2113c9871..53a705e26f 100644 --- a/src/startup_stubs/d3d12_xs_device.cpp +++ b/src/startup_stubs/d3d12_xs_device.cpp @@ -48,6 +48,7 @@ #include "startup_stubs/per_reason_refusal_census.h" #include "startup_stubs/buffer_format_word3.h" #include "startup_stubs/memory_srv_buffer.h" +#include "startup_stubs/srv_refusal_cache.h" #include "startup_stubs/single_element_srv.h" #include "startup_stubs/view_dimension.h" #include "startup_stubs/list_copy.h" @@ -4908,7 +4909,7 @@ HRESULT publish_placed_buffer(Wrapper* self, void* address, const D3D12_RESOURCE const ResourceInfo record{*desc, desc->Width, aliased ? Placement::aliased_buffer : Placement::copied_buffer, self, initial_state}; auto& group = placement_group(desc->Width); const HRESULT hr = x2w_startup::publish_placement(note_lock, resource_infos, group.by_start, group.max_width, - static_cast(w), reinterpret_cast(address), record, [&] { index_resource(w, record); }); + static_cast(w), reinterpret_cast(address), record, [&] { index_resource(w, record); x2w_startup::note_placement_change(); }); if (FAILED(hr)) { // The caller has never received this wrapper; release its desktop resource and storage. AcquireSRWLockExclusive(®istry_lock); @@ -5431,6 +5432,7 @@ void drain_retired_resources() { x2w_startup::ExclusiveNoteLock guard(note_lock); resource_address_index().erase(address, drop.wrapper); + x2w_startup::note_placement_change(); } if (drop.wrapper->own().retire_has_written_gen && !retire_address_has_live_user(address, drop.wrapper)) { AcquireSRWLockExclusive(&written_lock); diff --git a/src/startup_stubs/placed_buffer_range.h b/src/startup_stubs/placed_buffer_range.h index 6e8bc3c4c7..9dd6675ef7 100644 --- a/src/startup_stubs/placed_buffer_range.h +++ b/src/startup_stubs/placed_buffer_range.h @@ -70,6 +70,23 @@ inline std::uint64_t allocation_bytes(const void* address) return info.RegionSize; } +// One region-information call for the allocation holding address: its base, size, committed bytes and flags, with no +// page-table scan. False when the call is missing or fails (the caller must then not cache anything on it). +inline bool region_stamp(const void* address, std::uint64_t& base, std::uint64_t& size, std::uint64_t& commit, + std::uint64_t& flags) +{ + placed_detail::RegionInformation info{}; + SIZE_T returned = 0; + const placed_detail::QueryRegion query = placed_detail::query_region(); + if (!address || !query || !query(GetCurrentProcess(), address, 0 /* MemoryRegionInfo */, &info, sizeof(info), &returned)) + return false; + base = reinterpret_cast(info.AllocationBase); + size = info.RegionSize; + commit = info.CommitSize; + flags = info.Flags; + return true; +} + // False when the address is not committed (slot 133 returns E_INVALIDARG). Otherwise covered is // exactly "offset <= committed bytes from base && width <= committed bytes - offset" for the run the // full walk measures. diff --git a/src/startup_stubs/srv_refusal_cache.h b/src/startup_stubs/srv_refusal_cache.h new file mode 100644 index 0000000000..9f7f202fbf --- /dev/null +++ b/src/startup_stubs/srv_refusal_cache.h @@ -0,0 +1,126 @@ +#pragma once + +// A bounded negative cache for refused buffer memory SRVs (device slot 70, reason buffer_unavailable). +// +// A refused SRV used to repeat the whole resolution on every call: the placement scans, the resource index +// scan, and the memory questions of placed_buffer_range.h (a region-information call and, for partly committed +// or mapped allocations, a VirtualQuery walk that costs milliseconds per GiB). A title that re-publishes the same +// view every frame paid that for every refusal. +// +// The answer is not remembered blindly: placed_buffer_range.h explains why title memory may change behind the +// stand-ins. A refusal is reused only while all of this still holds: +// - the same request: address, span and every view / resource field the resolution reads (SrvRefusalKey); +// - the same stand-in state: the placement generation, which advances whenever a resource is indexed, retired, +// published or released, or an unplaced buffer is created or dropped (note_placement_change); +// - the same memory state: one cheap region-information stamp of the allocation holding the address (base, size, +// committed bytes, flags; no page scan). A stamp that could not be read is never cached; +// - an entry younger than kMaxAgeMs and used fewer than kMaxHits times, so a change the stamp cannot see (the +// same number of pages committed elsewhere) is picked up after at most that long. +// A miss runs the full resolution unchanged. The only wrong answer a stale hit can give is a refusal where the +// full path would now publish, delayed by at most kMaxAgeMs; it can never publish a view. + +#include +#include +#include +#include +#include + +namespace x2w_startup { + +inline std::atomic& srv_placement_generation() +{ + static std::atomic generation{1}; + return generation; +} + +// Call after any change of what existing_memory_buffer / unplaced_memory_buffer can find. +inline void note_placement_change() +{ + srv_placement_generation().fetch_add(1, std::memory_order_acq_rel); +} + +struct SrvRefusalKey { + std::uint64_t address = 0; + std::uint64_t span_bytes = 0; + std::uint64_t view_a = 0; // format, dimension, component mapping + std::uint64_t view_b = 0; // first element + std::uint64_t view_c = 0; // element count, stride, flags + std::uint64_t resource_a = 0; // dimension, flags + std::uint64_t resource_b = 0; // width + bool operator==(const SrvRefusalKey& o) const + { + return address == o.address && span_bytes == o.span_bytes && view_a == o.view_a && view_b == o.view_b && + view_c == o.view_c && resource_a == o.resource_a && resource_b == o.resource_b; + } +}; + +struct SrvRefusalStamp { + bool valid = false; // the region information could be read + std::uint64_t generation = 0; + std::uint64_t base = 0; + std::uint64_t size = 0; + std::uint64_t commit = 0; + std::uint64_t flags = 0; + bool operator==(const SrvRefusalStamp& o) const + { + return valid && o.valid && generation == o.generation && base == o.base && size == o.size && + commit == o.commit && flags == o.flags; + } +}; + +class SrvRefusalCache { +public: + static constexpr std::size_t kSlots = 256; + static constexpr std::uint64_t kMaxAgeMs = 250; + static constexpr std::uint32_t kMaxHits = 1024; + + // True when this request was refused under the same stand-in and memory state a moment ago. + bool hit(const SrvRefusalKey& key, const SrvRefusalStamp& stamp, std::uint64_t now_ms) + { + if (!stamp.valid) return false; + std::lock_guard lock(mutex_); + Entry& e = entries_[slot(key)]; + if (!e.used || !(e.key == key) || !(e.stamp == stamp) || now_ms < e.noted_ms || + now_ms - e.noted_ms > kMaxAgeMs || e.hits >= kMaxHits) { + return false; + } + ++e.hits; + return true; + } + + // Remember a refusal the full resolution just produced. + void note(const SrvRefusalKey& key, const SrvRefusalStamp& stamp, std::uint64_t now_ms) + { + if (!stamp.valid) return; + std::lock_guard lock(mutex_); + entries_[slot(key)] = Entry{true, key, stamp, now_ms, 0}; + } + + void clear() + { + std::lock_guard lock(mutex_); + for (Entry& e : entries_) e = Entry{}; + } + +private: + struct Entry { + bool used = false; + SrvRefusalKey key; + SrvRefusalStamp stamp; + std::uint64_t noted_ms = 0; + std::uint32_t hits = 0; + }; + + static std::size_t slot(const SrvRefusalKey& k) + { + std::uint64_t h = 1469598103934665603ull; + for (std::uint64_t v : {k.address, k.span_bytes, k.view_a, k.view_b, k.view_c, k.resource_a, k.resource_b}) + h = (h ^ v) * 1099511628211ull; + return static_cast((h ^ (h >> 32)) % kSlots); + } + + std::mutex mutex_; + std::array entries_{}; +}; + +} // namespace x2w_startup diff --git a/tests/startup_srv_refusal_cache_check.cpp b/tests/startup_srv_refusal_cache_check.cpp new file mode 100644 index 0000000000..a2139a56f1 --- /dev/null +++ b/tests/startup_srv_refusal_cache_check.cpp @@ -0,0 +1,165 @@ +// Checks the negative cache of refused buffer memory SRVs (device slot 70, src/startup_stubs/srv_refusal_cache.h) +// without a device: a refusal is reused only for the same request, placement generation and memory stamp, and +// only while it is young and lightly used. +// --mutate generation: expect a changed placement generation to still hit. +// --mutate commit: expect a changed committed-byte count of the allocation to still hit. +// --mutate key: expect a different view to hit an entry noted for another view. +// --mutate age: expect an entry older than the age limit to still hit. +// --mutate hits: expect an entry used more than the hit limit to still hit. +// --mutate invalid: expect a stamp that could not be read to be cached. +// Each mutated run is a negative control and must fail. +#include "startup_stubs/srv_refusal_cache.h" + +#include +#include + +namespace { + +int failures; +const char* mutation = ""; + +bool mutated(const char* name) +{ + return std::strcmp(mutation, name) == 0; +} + +void check(const char* name, bool condition) +{ + if (condition) return; + ++failures; + std::printf("FAIL %s\n", name); +} + +x2w_startup::SrvRefusalKey request(std::uint64_t address, std::uint64_t first_element) +{ + x2w_startup::SrvRefusalKey key; + key.address = address; + key.span_bytes = 0x4000; + key.view_a = 0x1234; + key.view_b = first_element; + key.view_c = 64; + key.resource_a = 1; + key.resource_b = 0x10000; + return key; +} + +x2w_startup::SrvRefusalStamp stamp(std::uint64_t generation, std::uint64_t commit) +{ + x2w_startup::SrvRefusalStamp s; + s.valid = true; + s.generation = generation; + s.base = 0x7000000000ull; + s.size = 0x200000; + s.commit = commit; + s.flags = 1; + return s; +} + +} // namespace + +int main(int argc, char** argv) +{ + if (argc == 3 && std::strcmp(argv[1], "--mutate") == 0) mutation = argv[2]; + using namespace x2w_startup; + + { + SrvRefusalCache cache; + const auto key = request(0x7000001000ull, 0); + check("an empty cache misses", !cache.hit(key, stamp(5, 0x1000), 100)); + cache.note(key, stamp(5, 0x1000), 100); + check("the same request, generation and stamp hit", cache.hit(key, stamp(5, 0x1000), 150)); + check("a hit repeats", cache.hit(key, stamp(5, 0x1000), 160)); + } + { + SrvRefusalCache cache; + const auto key = request(0x7000001000ull, 0); + cache.note(key, stamp(5, 0x1000), 100); + const bool hit = cache.hit(key, stamp(6, 0x1000), 110); + check("a new placement generation misses (a resource may now cover the address)", mutated("generation") ? hit : !hit); + } + { + SrvRefusalCache cache; + const auto key = request(0x7000001000ull, 0); + cache.note(key, stamp(5, 0x1000), 100); + const bool hit = cache.hit(key, stamp(5, 0x2000), 110); + check("more committed bytes in the allocation miss (the buffer may now be readable)", mutated("commit") ? hit : !hit); + auto moved = stamp(5, 0x1000); + moved.base += 0x10000; + check("another allocation base misses", !cache.hit(key, moved, 110)); + auto resized = stamp(5, 0x1000); + resized.size += 0x10000; + check("another allocation size misses", !cache.hit(key, resized, 110)); + auto flagged = stamp(5, 0x1000); + flagged.flags = 2; + check("other allocation flags miss", !cache.hit(key, flagged, 110)); + } + { + SrvRefusalCache cache; + cache.note(request(0x7000001000ull, 0), stamp(5, 0x1000), 100); + const bool other_view = cache.hit(request(0x7000001000ull, 8), stamp(5, 0x1000), 110); + check("another view of the same address misses", mutated("key") ? other_view : !other_view); + check("another address misses", !cache.hit(request(0x7000002000ull, 0), stamp(5, 0x1000), 110)); + auto wider = request(0x7000001000ull, 0); + wider.span_bytes += 4; + check("another span misses", !cache.hit(wider, stamp(5, 0x1000), 110)); + auto resource = request(0x7000001000ull, 0); + resource.resource_b += 1; + check("another resource width misses", !cache.hit(resource, stamp(5, 0x1000), 110)); + } + { + SrvRefusalCache cache; + const auto key = request(0x7000001000ull, 0); + cache.note(key, stamp(5, 0x1000), 100); + const bool old_hit = cache.hit(key, stamp(5, 0x1000), 100 + SrvRefusalCache::kMaxAgeMs + 1); + check("an entry older than the age limit misses", mutated("age") ? old_hit : !old_hit); + check("an entry exactly at the age limit still hits", [&] { + SrvRefusalCache fresh; + fresh.note(key, stamp(5, 0x1000), 100); + return fresh.hit(key, stamp(5, 0x1000), 100 + SrvRefusalCache::kMaxAgeMs); + }()); + check("a clock that went backwards misses", [&] { + SrvRefusalCache fresh; + fresh.note(key, stamp(5, 0x1000), 100); + return !fresh.hit(key, stamp(5, 0x1000), 50); + }()); + } + { + SrvRefusalCache cache; + const auto key = request(0x7000001000ull, 0); + cache.note(key, stamp(5, 0x1000), 100); + bool all = true; + for (std::uint32_t i = 0; i < SrvRefusalCache::kMaxHits; ++i) all = cache.hit(key, stamp(5, 0x1000), 110) && all; + check("the entry hits up to the hit limit", all); + const bool over = cache.hit(key, stamp(5, 0x1000), 110); + check("past the hit limit the full path runs again", mutated("hits") ? over : !over); + cache.note(key, stamp(5, 0x1000), 120); // the full path refused again and re-noted + check("a re-noted entry hits again", cache.hit(key, stamp(5, 0x1000), 121)); + } + { + SrvRefusalCache cache; + const auto key = request(0x7000001000ull, 0); + SrvRefusalStamp unreadable = stamp(5, 0x1000); + unreadable.valid = false; + cache.note(key, unreadable, 100); + const bool hit = cache.hit(key, unreadable, 110); + check("a stamp that could not be read is never cached", mutated("invalid") ? hit : !hit); + check("and never hits", !cache.hit(key, unreadable, 110)); + } + { + SrvRefusalCache cache; + const auto key = request(0x7000001000ull, 0); + cache.note(key, stamp(5, 0x1000), 100); + cache.clear(); + check("clear forgets everything", !cache.hit(key, stamp(5, 0x1000), 110)); + const auto before = srv_placement_generation().load(); + note_placement_change(); + check("note_placement_change advances the generation", srv_placement_generation().load() == before + 1); + } + + if (failures) { + std::printf("%d check(s) failed\n", failures); + return 1; + } + std::printf("srv refusal cache checks passed\n"); + return 0; +} From 09584683bc75d198b8f87108550e3133ae81fe94 Mon Sep 17 00:00:00 2001 From: c1 Date: Thu, 26 Nov 2026 10:00:38 +0100 Subject: [PATCH 2/8] fix: key the refusal cache by device and bump the placement generation at the tiled address flip Placement lookups are per device, so a refusal for one device must not be replayed for another. address_resource_overlap reads tiled_address_srv, which publish_tiled_texture sets: advance the generation there too. --- CMakeLists.txt | 2 +- src/startup_stubs/d3d12_memory_srv.inl | 8 ++++++-- src/startup_stubs/srv_refusal_cache.h | 5 +++-- tests/startup_srv_refusal_cache_check.cpp | 7 +++++++ 4 files changed, 17 insertions(+), 5 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 8607ce6fba..f0dc978325 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -2139,7 +2139,7 @@ add_executable(startup_srv_refusal_cache_check tests/startup_srv_refusal_cache_c target_include_directories(startup_srv_refusal_cache_check PRIVATE src) target_compile_features(startup_srv_refusal_cache_check PRIVATE cxx_std_17) add_test(NAME startup_srv_refusal_cache COMMAND startup_srv_refusal_cache_check) -foreach(mutation IN ITEMS generation commit key age hits invalid) +foreach(mutation IN ITEMS generation commit key device age hits invalid) add_test(NAME startup_srv_refusal_cache_${mutation}_control COMMAND startup_srv_refusal_cache_check --mutate ${mutation}) set_tests_properties(startup_srv_refusal_cache_${mutation}_control PROPERTIES WILL_FAIL TRUE) endforeach() diff --git a/src/startup_stubs/d3d12_memory_srv.inl b/src/startup_stubs/d3d12_memory_srv.inl index e55a5ec75a..d239c40f53 100644 --- a/src/startup_stubs/d3d12_memory_srv.inl +++ b/src/startup_stubs/d3d12_memory_srv.inl @@ -548,6 +548,8 @@ Wrapper* publish_tiled_texture(Wrapper* device, u64 address, const D3D12_RESOURC note_resource(resource, &desc, bytes); tiled_srv_textures.emplace(resource, TiledAddressTexture{device, resource, desc, {}}); tiled_srv_addresses.emplace(address, resource); + // address_resource_overlap reads tiled_address_srv: a buffer refused for overlap may be publishable now. + x2w_startup::note_placement_change(); return resource; } @@ -679,10 +681,12 @@ x2w_startup::SrvRefusalCache& buffer_refusal_cache() return cache; } -x2w_startup::SrvRefusalKey buffer_refusal_key(const D3D12_RESOURCE_DESC& resource, const MemoryShaderResourceView& input, u64 span_bytes) +x2w_startup::SrvRefusalKey buffer_refusal_key(const Wrapper* device, const D3D12_RESOURCE_DESC& resource, + const MemoryShaderResourceView& input, u64 span_bytes) { const auto& view = input.view; x2w_startup::SrvRefusalKey key; + key.device = reinterpret_cast(device); key.address = input.address; key.span_bytes = span_bytes; key.view_a = (u64{static_cast(view.Format)} << 32) | (u64{static_cast(view.ViewDimension)} << 16) | view.Shader4ComponentMapping; @@ -733,7 +737,7 @@ void __stdcall device_memory_srv(Wrapper* self, const D3D12_RESOURCE_DESC* resou if (resource->Dimension == D3D12_RESOURCE_DIMENSION_BUFFER) { const u64 elem_bytes = x2w_startup::buffer_srv_element_bytes(input->view); const u64 span_bytes = (input->view.Buffer.FirstElement + input->view.Buffer.NumElements) * elem_bytes; - const auto refusal_key = buffer_refusal_key(*resource, *input, span_bytes); + const auto refusal_key = buffer_refusal_key(self, *resource, *input, span_bytes); const auto refusal_stamp = buffer_refusal_stamp(input->address); if (buffer_refusal_cache().hit(refusal_key, refusal_stamp, GetTickCount64())) { refuse_memory_srv(refused, "unavailable buffer at the supplied address", "buffer_unavailable", resource, input, diff --git a/src/startup_stubs/srv_refusal_cache.h b/src/startup_stubs/srv_refusal_cache.h index 9f7f202fbf..8afda5cc06 100644 --- a/src/startup_stubs/srv_refusal_cache.h +++ b/src/startup_stubs/srv_refusal_cache.h @@ -40,6 +40,7 @@ inline void note_placement_change() } struct SrvRefusalKey { + std::uint64_t device = 0; // the device wrapper: every placement lookup is per device std::uint64_t address = 0; std::uint64_t span_bytes = 0; std::uint64_t view_a = 0; // format, dimension, component mapping @@ -49,7 +50,7 @@ struct SrvRefusalKey { std::uint64_t resource_b = 0; // width bool operator==(const SrvRefusalKey& o) const { - return address == o.address && span_bytes == o.span_bytes && view_a == o.view_a && view_b == o.view_b && + return device == o.device && address == o.address && span_bytes == o.span_bytes && view_a == o.view_a && view_b == o.view_b && view_c == o.view_c && resource_a == o.resource_a && resource_b == o.resource_b; } }; @@ -114,7 +115,7 @@ class SrvRefusalCache { static std::size_t slot(const SrvRefusalKey& k) { std::uint64_t h = 1469598103934665603ull; - for (std::uint64_t v : {k.address, k.span_bytes, k.view_a, k.view_b, k.view_c, k.resource_a, k.resource_b}) + for (std::uint64_t v : {k.device, k.address, k.span_bytes, k.view_a, k.view_b, k.view_c, k.resource_a, k.resource_b}) h = (h ^ v) * 1099511628211ull; return static_cast((h ^ (h >> 32)) % kSlots); } diff --git a/tests/startup_srv_refusal_cache_check.cpp b/tests/startup_srv_refusal_cache_check.cpp index a2139a56f1..f99dbf238d 100644 --- a/tests/startup_srv_refusal_cache_check.cpp +++ b/tests/startup_srv_refusal_cache_check.cpp @@ -4,6 +4,7 @@ // --mutate generation: expect a changed placement generation to still hit. // --mutate commit: expect a changed committed-byte count of the allocation to still hit. // --mutate key: expect a different view to hit an entry noted for another view. +// --mutate device: expect the same request on another device to hit an entry noted for the first device. // --mutate age: expect an entry older than the age limit to still hit. // --mutate hits: expect an entry used more than the hit limit to still hit. // --mutate invalid: expect a stamp that could not be read to be cached. @@ -33,6 +34,7 @@ void check(const char* name, bool condition) x2w_startup::SrvRefusalKey request(std::uint64_t address, std::uint64_t first_element) { x2w_startup::SrvRefusalKey key; + key.device = 0x5000; key.address = address; key.span_bytes = 0x4000; key.view_a = 0x1234; @@ -99,6 +101,11 @@ int main(int argc, char** argv) const bool other_view = cache.hit(request(0x7000001000ull, 8), stamp(5, 0x1000), 110); check("another view of the same address misses", mutated("key") ? other_view : !other_view); check("another address misses", !cache.hit(request(0x7000002000ull, 0), stamp(5, 0x1000), 110)); + auto other_device = request(0x7000001000ull, 0); + other_device.device += 0x100; + const bool device_hit = cache.hit(other_device, stamp(5, 0x1000), 110); + check("the same request on another device misses (placement lookups are per device)", + mutated("device") ? device_hit : !device_hit); auto wider = request(0x7000001000ull, 0); wider.span_bytes += 4; check("another span misses", !cache.hit(wider, stamp(5, 0x1000), 110)); From ef94abdd86c86b939dbfbe995272334f4843fa76 Mon Sep 17 00:00:00 2001 From: c1 Date: Thu, 26 Nov 2026 10:12:53 +0100 Subject: [PATCH 3/8] fix: advance the placement generation at the last release of any title resource address_resource_overlap and existing_memory_buffer stop counting a resource when its reference count reaches zero, also for resources without a placement entry, so a refusal cached for that overlap must not outlive the release. --- src/startup_stubs/d3d12_xs_device.cpp | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/startup_stubs/d3d12_xs_device.cpp b/src/startup_stubs/d3d12_xs_device.cpp index 53a705e26f..36cc19327c 100644 --- a/src/startup_stubs/d3d12_xs_device.cpp +++ b/src/startup_stubs/d3d12_xs_device.cpp @@ -1039,6 +1039,9 @@ ULONG __stdcall release(Wrapper* self) if (self->own().kind == descriptor_heap_kind) retire_drop_heap_views(self); if (self->own().kind == resource_kind && self->own().title_memory) { drop_mesh_lease_owner(self); + // The last release ends the resource for existing_memory_buffer and address_resource_overlap (they skip + // refs <= 0) whether or not it has a placement entry: a refusal cached while it was live is stale. + x2w_startup::note_placement_change(); retire_placement(self); if (self->own().retire_when_idle) retire_note_title_release(self); if (x2w_startup::linear_buffer_mode() != x2w_startup::LinearBufferMode::off) From 7fdee8f751c2986502841f01a72f0866c3026c89 Mon Sep 17 00:00:00 2001 From: c1 Date: Thu, 26 Nov 2026 10:45:55 +0100 Subject: [PATCH 4/8] fix: cache only memory-independent SRV refusals by default --- CMakeLists.txt | 2 +- src/startup_stubs/d3d12_memory_srv.inl | 45 +++++++-- src/startup_stubs/srv_refusal_cache.h | 38 +++++--- tests/startup_srv_refusal_cache_check.cpp | 106 ++++++++++++---------- 4 files changed, 121 insertions(+), 70 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index b739149ee3..ea44cf354d 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -2139,7 +2139,7 @@ add_executable(startup_srv_refusal_cache_check tests/startup_srv_refusal_cache_c target_include_directories(startup_srv_refusal_cache_check PRIVATE src) target_compile_features(startup_srv_refusal_cache_check PRIVATE cxx_std_17) add_test(NAME startup_srv_refusal_cache COMMAND startup_srv_refusal_cache_check) -foreach(mutation IN ITEMS generation commit key device age hits invalid) +foreach(mutation IN ITEMS generation memory key device age hits invalid) add_test(NAME startup_srv_refusal_cache_${mutation}_control COMMAND startup_srv_refusal_cache_check --mutate ${mutation}) set_tests_properties(startup_srv_refusal_cache_${mutation}_control PROPERTIES WILL_FAIL TRUE) endforeach() diff --git a/src/startup_stubs/d3d12_memory_srv.inl b/src/startup_stubs/d3d12_memory_srv.inl index d239c40f53..f0c0e21a8a 100644 --- a/src/startup_stubs/d3d12_memory_srv.inl +++ b/src/startup_stubs/d3d12_memory_srv.inl @@ -294,12 +294,22 @@ void clear_unplaced_buffers(Wrapper* device) } } -Wrapper* unplaced_memory_buffer(Wrapper* device, u64 address, u64 span_bytes, const D3D12_RESOURCE_DESC& requested_desc) -{ - if (address_resource_overlap(address, span_bytes)) return nullptr; +// memory_independent (out, optional): set when a nullptr answer was decided by the request and the stand-in state +// alone (a live resource overlaps, no page extent, a placed buffer owns the page), not by what is committed at the +// address. Only such refusals are exact enough to cache (srv_refusal_cache.h). +Wrapper* unplaced_memory_buffer(Wrapper* device, u64 address, u64 span_bytes, const D3D12_RESOURCE_DESC& requested_desc, + bool* memory_independent = nullptr) +{ + if (memory_independent) *memory_independent = false; + if (address_resource_overlap(address, span_bytes)) { + if (memory_independent) *memory_independent = true; + return nullptr; + } u64 page_start = 0, page_span = 0; - if (!x2w_startup::unplaced_buffer_extent(address, span_bytes, page_start, page_span)) + if (!x2w_startup::unplaced_buffer_extent(address, span_bytes, page_start, page_span)) { + if (memory_independent) *memory_independent = true; return nullptr; + } x2w_startup::PlacedBufferRange memory{}; if (!x2w_startup::measure_placed_buffer(reinterpret_cast(page_start), page_span, memory) || @@ -307,7 +317,10 @@ Wrapper* unplaced_memory_buffer(Wrapper* device, u64 address, u64 span_bytes, co return nullptr; const auto nearby = placed_buffer_range(device, page_start, page_span, true); - if (nearby.reject || nearby.owner) return nullptr; + if (nearby.reject || nearby.owner) { + if (memory_independent) *memory_independent = true; + return nullptr; + } auto* desktop = device_of(device); if (!desktop) return nullptr; @@ -697,12 +710,22 @@ x2w_startup::SrvRefusalKey buffer_refusal_key(const Wrapper* device, const D3D12 return key; } -// The generation first, then the memory: a change between the two reads makes the entry stale, never fresh. +// Refusals that depend on what is committed at the address are not cached unless X2W_SRV_REFUSAL_CACHE_MEMORY is +// set: commit and decommit happen behind the stand-ins and a region stamp cannot see pages that move with the same +// total, so a retry right after the title commits the buffer could be refused again for up to 250 ms. +bool srv_refusal_cache_memory_enabled() +{ + static const bool enabled = x2w_local::env_on("X2W_SRV_REFUSAL_CACHE_MEMORY"); + return enabled; +} + +// The generation first, then (opt-in only) the memory: a change between the two reads makes the entry stale, never fresh. x2w_startup::SrvRefusalStamp buffer_refusal_stamp(u64 address) { x2w_startup::SrvRefusalStamp stamp; stamp.generation = x2w_startup::srv_placement_generation().load(std::memory_order_acquire); - stamp.valid = x2w_startup::region_stamp(reinterpret_cast(address), stamp.base, stamp.size, stamp.commit, stamp.flags); + if (srv_refusal_cache_memory_enabled()) + stamp.valid = x2w_startup::region_stamp(reinterpret_cast(address), stamp.base, stamp.size, stamp.commit, stamp.flags); return stamp; } @@ -739,21 +762,23 @@ void __stdcall device_memory_srv(Wrapper* self, const D3D12_RESOURCE_DESC* resou const u64 span_bytes = (input->view.Buffer.FirstElement + input->view.Buffer.NumElements) * elem_bytes; const auto refusal_key = buffer_refusal_key(self, *resource, *input, span_bytes); const auto refusal_stamp = buffer_refusal_stamp(input->address); - if (buffer_refusal_cache().hit(refusal_key, refusal_stamp, GetTickCount64())) { + if (buffer_refusal_cache().hit(refusal_key, refusal_stamp, GetTickCount64(), srv_refusal_cache_memory_enabled())) { refuse_memory_srv(refused, "unavailable buffer at the supplied address", "buffer_unavailable", resource, input, destination); return; } Wrapper* buffer = existing_memory_buffer(self, input->address, span_bytes); + bool memory_independent = false; if (!buffer) { - buffer = unplaced_memory_buffer(self, input->address, span_bytes, *resource); + buffer = unplaced_memory_buffer(self, input->address, span_bytes, *resource, &memory_independent); } const ResourceInfo* info = buffer ? resource_info(buffer) : nullptr; D3D12_SHADER_RESOURCE_VIEW_DESC adjusted{}; if (!buffer || !info || !x2w_startup::resolve_buffer_srv_desc(reinterpret_cast(buffer->own().title_memory), info->console.Width, input->address, input->view, adjusted)) { - buffer_refusal_cache().note(refusal_key, refusal_stamp, GetTickCount64()); + // A buffer that was found (placed or unplaced) and does not fit the view is decided by its recorded size. + buffer_refusal_cache().note(refusal_key, refusal_stamp, GetTickCount64(), memory_independent || buffer != nullptr); refuse_memory_srv(refused, "unavailable buffer at the supplied address", "buffer_unavailable", resource, input, destination); return; diff --git a/src/startup_stubs/srv_refusal_cache.h b/src/startup_stubs/srv_refusal_cache.h index 8afda5cc06..c788c0c914 100644 --- a/src/startup_stubs/srv_refusal_cache.h +++ b/src/startup_stubs/srv_refusal_cache.h @@ -12,12 +12,17 @@ // - the same request: address, span and every view / resource field the resolution reads (SrvRefusalKey); // - the same stand-in state: the placement generation, which advances whenever a resource is indexed, retired, // published or released, or an unplaced buffer is created or dropped (note_placement_change); -// - the same memory state: one cheap region-information stamp of the allocation holding the address (base, size, -// committed bytes, flags; no page scan). A stamp that could not be read is never cached; -// - an entry younger than kMaxAgeMs and used fewer than kMaxHits times, so a change the stamp cannot see (the -// same number of pages committed elsewhere) is picked up after at most that long. -// A miss runs the full resolution unchanged. The only wrong answer a stale hit can give is a refusal where the -// full path would now publish, delayed by at most kMaxAgeMs; it can never publish a view. +// - an entry younger than kMaxAgeMs and used fewer than kMaxHits times. +// Two kinds of refusal exist, and only one is exact: +// - memory independent: decided by the request and by stand-in state alone (a live resource overlaps, the span has no +// page extent, a placed buffer owns the page, the found buffer is too small for the view). The key and the +// placement generation prove it, so it is cached by default; +// - memory dependent: decided by what is committed at the address. Commit and decommit happen behind the stand-ins, +// and a region-information stamp (base, size, committed bytes, flags) cannot see pages that move with the same +// total (reserve 128 KiB, commit the upper half, refuse; decommit it, commit the lower half, retry at once: the +// stamp is identical but the buffer is now readable). Such a refusal is cached only when the caller opts in +// (allow_memory_dependent), accepting that a retry within kMaxAgeMs can be refused again. +// A miss runs the full resolution unchanged. The default lookup never refuses what the full path would publish. #include #include @@ -76,25 +81,31 @@ class SrvRefusalCache { static constexpr std::uint32_t kMaxHits = 1024; // True when this request was refused under the same stand-in and memory state a moment ago. - bool hit(const SrvRefusalKey& key, const SrvRefusalStamp& stamp, std::uint64_t now_ms) + bool hit(const SrvRefusalKey& key, const SrvRefusalStamp& stamp, std::uint64_t now_ms, + bool allow_memory_dependent = false) { - if (!stamp.valid) return false; std::lock_guard lock(mutex_); Entry& e = entries_[slot(key)]; - if (!e.used || !(e.key == key) || !(e.stamp == stamp) || now_ms < e.noted_ms || + if (!e.used || !(e.key == key) || now_ms < e.noted_ms || now_ms - e.noted_ms > kMaxAgeMs || e.hits >= kMaxHits) { return false; } + if (e.memory_independent) { + if (e.stamp.generation != stamp.generation) return false; + } else if (!allow_memory_dependent || !(e.stamp == stamp)) { + return false; + } ++e.hits; return true; } - // Remember a refusal the full resolution just produced. - void note(const SrvRefusalKey& key, const SrvRefusalStamp& stamp, std::uint64_t now_ms) + // Remember a refusal the full resolution just produced. memory_independent: it does not depend on what is + // committed at the address (see above); the stamp's generation is then the only state it needs. + void note(const SrvRefusalKey& key, const SrvRefusalStamp& stamp, std::uint64_t now_ms, bool memory_independent) { - if (!stamp.valid) return; + if (!memory_independent && !stamp.valid) return; std::lock_guard lock(mutex_); - entries_[slot(key)] = Entry{true, key, stamp, now_ms, 0}; + entries_[slot(key)] = Entry{true, key, stamp, now_ms, 0, memory_independent}; } void clear() @@ -110,6 +121,7 @@ class SrvRefusalCache { SrvRefusalStamp stamp; std::uint64_t noted_ms = 0; std::uint32_t hits = 0; + bool memory_independent = false; }; static std::size_t slot(const SrvRefusalKey& k) diff --git a/tests/startup_srv_refusal_cache_check.cpp b/tests/startup_srv_refusal_cache_check.cpp index f99dbf238d..8e58217cf9 100644 --- a/tests/startup_srv_refusal_cache_check.cpp +++ b/tests/startup_srv_refusal_cache_check.cpp @@ -1,13 +1,15 @@ // Checks the negative cache of refused buffer memory SRVs (device slot 70, src/startup_stubs/srv_refusal_cache.h) -// without a device: a refusal is reused only for the same request, placement generation and memory stamp, and -// only while it is young and lightly used. +// without a device. A refusal decided by the request and the stand-in state alone (memory independent) is reused for +// the same request and placement generation. A refusal that depends on what is committed at the address is never +// reused by the default lookup: pages can move with the same committed total (reserve 128 KiB, commit the upper +// 64 KiB, refuse; decommit it, commit the lower 64 KiB, retry at once), which no region stamp can see. // --mutate generation: expect a changed placement generation to still hit. -// --mutate commit: expect a changed committed-byte count of the allocation to still hit. +// --mutate memory: expect the default lookup to reuse a memory dependent refusal (the page-move case). // --mutate key: expect a different view to hit an entry noted for another view. // --mutate device: expect the same request on another device to hit an entry noted for the first device. // --mutate age: expect an entry older than the age limit to still hit. // --mutate hits: expect an entry used more than the hit limit to still hit. -// --mutate invalid: expect a stamp that could not be read to be cached. +// --mutate invalid: expect a memory dependent entry with an unreadable stamp to hit under the opt-in. // Each mutated run is a negative control and must fail. #include "startup_stubs/srv_refusal_cache.h" @@ -51,7 +53,7 @@ x2w_startup::SrvRefusalStamp stamp(std::uint64_t generation, std::uint64_t commi s.valid = true; s.generation = generation; s.base = 0x7000000000ull; - s.size = 0x200000; + s.size = 0x20000; // 128 KiB reservation s.commit = commit; s.flags = 1; return s; @@ -63,101 +65,113 @@ int main(int argc, char** argv) { if (argc == 3 && std::strcmp(argv[1], "--mutate") == 0) mutation = argv[2]; using namespace x2w_startup; + const std::uint64_t kHalf = 0x10000; // 64 KiB { SrvRefusalCache cache; const auto key = request(0x7000001000ull, 0); - check("an empty cache misses", !cache.hit(key, stamp(5, 0x1000), 100)); - cache.note(key, stamp(5, 0x1000), 100); - check("the same request, generation and stamp hit", cache.hit(key, stamp(5, 0x1000), 150)); - check("a hit repeats", cache.hit(key, stamp(5, 0x1000), 160)); + check("an empty cache misses", !cache.hit(key, stamp(5, 0), 100)); + cache.note(key, stamp(5, 0), 100, true); + check("a memory independent refusal hits for the same request and generation", cache.hit(key, stamp(5, 0), 150)); + check("a hit repeats", cache.hit(key, stamp(5, 0), 160)); + // The commit state is irrelevant to such a refusal: it was decided without reading memory. + check("a memory independent refusal ignores the committed total", cache.hit(key, stamp(5, kHalf), 170)); } { SrvRefusalCache cache; const auto key = request(0x7000001000ull, 0); - cache.note(key, stamp(5, 0x1000), 100); - const bool hit = cache.hit(key, stamp(6, 0x1000), 110); + cache.note(key, stamp(5, 0), 100, true); + const bool hit = cache.hit(key, stamp(6, 0), 110); check("a new placement generation misses (a resource may now cover the address)", mutated("generation") ? hit : !hit); } { + // Reported sequence: reserve 128 KiB, commit the upper 64 KiB, the slot-70 request refuses; decommit the + // upper half, commit and fill the lower half (same base, same reservation, same committed total), retry at once. SrvRefusalCache cache; - const auto key = request(0x7000001000ull, 0); - cache.note(key, stamp(5, 0x1000), 100); - const bool hit = cache.hit(key, stamp(5, 0x2000), 110); - check("more committed bytes in the allocation miss (the buffer may now be readable)", mutated("commit") ? hit : !hit); - auto moved = stamp(5, 0x1000); + const auto key = request(0x7000000000ull, 0); + const auto upper_committed = stamp(5, kHalf); + const auto lower_committed = stamp(5, kHalf); // identical stamp: the move is invisible + cache.note(key, upper_committed, 100, false); + bool hit = cache.hit(key, lower_committed, 101); + if (mutated("memory")) hit = cache.hit(key, lower_committed, 101, true) || hit; + check("the page move with an equal stamp runs the full path", !hit); + check("a memory dependent refusal never hits by default", !cache.hit(key, upper_committed, 102)); + // Opt-in accepts exactly this staleness, so it must be off unless asked for. + check("the opt-in reuses a memory dependent refusal for an equal stamp", cache.hit(key, upper_committed, 103, true)); + check("the opt-in still misses on a different committed total", !cache.hit(key, stamp(5, 2 * kHalf), 104, true)); + auto moved = stamp(5, kHalf); moved.base += 0x10000; - check("another allocation base misses", !cache.hit(key, moved, 110)); - auto resized = stamp(5, 0x1000); - resized.size += 0x10000; - check("another allocation size misses", !cache.hit(key, resized, 110)); - auto flagged = stamp(5, 0x1000); + check("the opt-in misses on another base", !cache.hit(key, moved, 104, true)); + auto flagged = stamp(5, kHalf); flagged.flags = 2; - check("other allocation flags miss", !cache.hit(key, flagged, 110)); + check("the opt-in misses on other flags", !cache.hit(key, flagged, 104, true)); + check("the opt-in misses on a new generation", !cache.hit(key, stamp(6, kHalf), 104, true)); } { SrvRefusalCache cache; - cache.note(request(0x7000001000ull, 0), stamp(5, 0x1000), 100); - const bool other_view = cache.hit(request(0x7000001000ull, 8), stamp(5, 0x1000), 110); + cache.note(request(0x7000001000ull, 0), stamp(5, 0), 100, true); + const bool other_view = cache.hit(request(0x7000001000ull, 8), stamp(5, 0), 110); check("another view of the same address misses", mutated("key") ? other_view : !other_view); - check("another address misses", !cache.hit(request(0x7000002000ull, 0), stamp(5, 0x1000), 110)); + check("another address misses", !cache.hit(request(0x7000002000ull, 0), stamp(5, 0), 110)); auto other_device = request(0x7000001000ull, 0); other_device.device += 0x100; - const bool device_hit = cache.hit(other_device, stamp(5, 0x1000), 110); + const bool device_hit = cache.hit(other_device, stamp(5, 0), 110); check("the same request on another device misses (placement lookups are per device)", mutated("device") ? device_hit : !device_hit); auto wider = request(0x7000001000ull, 0); wider.span_bytes += 4; - check("another span misses", !cache.hit(wider, stamp(5, 0x1000), 110)); + check("another span misses", !cache.hit(wider, stamp(5, 0), 110)); auto resource = request(0x7000001000ull, 0); resource.resource_b += 1; - check("another resource width misses", !cache.hit(resource, stamp(5, 0x1000), 110)); + check("another resource width misses", !cache.hit(resource, stamp(5, 0), 110)); } { SrvRefusalCache cache; const auto key = request(0x7000001000ull, 0); - cache.note(key, stamp(5, 0x1000), 100); - const bool old_hit = cache.hit(key, stamp(5, 0x1000), 100 + SrvRefusalCache::kMaxAgeMs + 1); + cache.note(key, stamp(5, 0), 100, true); + const bool old_hit = cache.hit(key, stamp(5, 0), 100 + SrvRefusalCache::kMaxAgeMs + 1); check("an entry older than the age limit misses", mutated("age") ? old_hit : !old_hit); check("an entry exactly at the age limit still hits", [&] { SrvRefusalCache fresh; - fresh.note(key, stamp(5, 0x1000), 100); - return fresh.hit(key, stamp(5, 0x1000), 100 + SrvRefusalCache::kMaxAgeMs); + fresh.note(key, stamp(5, 0), 100, true); + return fresh.hit(key, stamp(5, 0), 100 + SrvRefusalCache::kMaxAgeMs); }()); check("a clock that went backwards misses", [&] { SrvRefusalCache fresh; - fresh.note(key, stamp(5, 0x1000), 100); - return !fresh.hit(key, stamp(5, 0x1000), 50); + fresh.note(key, stamp(5, 0), 100, true); + return !fresh.hit(key, stamp(5, 0), 50); }()); } { SrvRefusalCache cache; const auto key = request(0x7000001000ull, 0); - cache.note(key, stamp(5, 0x1000), 100); + cache.note(key, stamp(5, 0), 100, true); bool all = true; - for (std::uint32_t i = 0; i < SrvRefusalCache::kMaxHits; ++i) all = cache.hit(key, stamp(5, 0x1000), 110) && all; + for (std::uint32_t i = 0; i < SrvRefusalCache::kMaxHits; ++i) all = cache.hit(key, stamp(5, 0), 110) && all; check("the entry hits up to the hit limit", all); - const bool over = cache.hit(key, stamp(5, 0x1000), 110); + const bool over = cache.hit(key, stamp(5, 0), 110); check("past the hit limit the full path runs again", mutated("hits") ? over : !over); - cache.note(key, stamp(5, 0x1000), 120); // the full path refused again and re-noted - check("a re-noted entry hits again", cache.hit(key, stamp(5, 0x1000), 121)); + cache.note(key, stamp(5, 0), 120, true); // the full path refused again and re-noted + check("a re-noted entry hits again", cache.hit(key, stamp(5, 0), 121)); } { SrvRefusalCache cache; const auto key = request(0x7000001000ull, 0); - SrvRefusalStamp unreadable = stamp(5, 0x1000); + SrvRefusalStamp unreadable = stamp(5, kHalf); unreadable.valid = false; - cache.note(key, unreadable, 100); - const bool hit = cache.hit(key, unreadable, 110); - check("a stamp that could not be read is never cached", mutated("invalid") ? hit : !hit); - check("and never hits", !cache.hit(key, unreadable, 110)); + cache.note(key, unreadable, 100, false); + const bool hit = cache.hit(key, unreadable, 110, true); + check("a memory dependent refusal with an unreadable stamp is never cached", mutated("invalid") ? hit : !hit); + // An unreadable stamp does not matter to a memory independent refusal. + cache.note(key, unreadable, 100, true); + check("a memory independent refusal does not need the stamp", cache.hit(key, unreadable, 110)); } { SrvRefusalCache cache; const auto key = request(0x7000001000ull, 0); - cache.note(key, stamp(5, 0x1000), 100); + cache.note(key, stamp(5, 0), 100, true); cache.clear(); - check("clear forgets everything", !cache.hit(key, stamp(5, 0x1000), 110)); + check("clear forgets everything", !cache.hit(key, stamp(5, 0), 110)); const auto before = srv_placement_generation().load(); note_placement_change(); check("note_placement_change advances the generation", srv_placement_generation().load() == before + 1); From 9f27526889d3df9b58e9bd45394f0f49b07f2d44 Mon Sep 17 00:00:00 2001 From: c1 Date: Thu, 26 Nov 2026 11:28:47 +0100 Subject: [PATCH 5/8] fix: cache memory-dependent SRV refusals with an exact witness page --- CMakeLists.txt | 2 +- src/startup_stubs/d3d12_memory_srv.inl | 58 +++--- src/startup_stubs/placed_buffer_range.h | 13 +- src/startup_stubs/srv_refusal_cache.h | 78 +++++--- tests/startup_srv_refusal_cache_check.cpp | 227 ++++++++++++++-------- 5 files changed, 239 insertions(+), 139 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index ea44cf354d..b72caae214 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -2139,7 +2139,7 @@ add_executable(startup_srv_refusal_cache_check tests/startup_srv_refusal_cache_c target_include_directories(startup_srv_refusal_cache_check PRIVATE src) target_compile_features(startup_srv_refusal_cache_check PRIVATE cxx_std_17) add_test(NAME startup_srv_refusal_cache COMMAND startup_srv_refusal_cache_check) -foreach(mutation IN ITEMS generation memory key device age hits invalid) +foreach(mutation IN ITEMS generation witness stamp key device age hits unproven) add_test(NAME startup_srv_refusal_cache_${mutation}_control COMMAND startup_srv_refusal_cache_check --mutate ${mutation}) set_tests_properties(startup_srv_refusal_cache_${mutation}_control PROPERTIES WILL_FAIL TRUE) endforeach() diff --git a/src/startup_stubs/d3d12_memory_srv.inl b/src/startup_stubs/d3d12_memory_srv.inl index f0c0e21a8a..49d7e124bd 100644 --- a/src/startup_stubs/d3d12_memory_srv.inl +++ b/src/startup_stubs/d3d12_memory_srv.inl @@ -294,31 +294,40 @@ void clear_unplaced_buffers(Wrapper* device) } } -// memory_independent (out, optional): set when a nullptr answer was decided by the request and the stand-in state -// alone (a live resource overlaps, no page extent, a placed buffer owns the page), not by what is committed at the -// address. Only such refusals are exact enough to cache (srv_refusal_cache.h). +// refusal (out, optional): when a nullptr answer is exactly provable, the proof that keeps a cached copy of it exact +// (srv_refusal_cache.h): decided by the request and stand-in state alone (independent), by a fully committed +// allocation the buffer does not fit (fully_committed), or by one page that is not committed (witness_page). +// A nullptr from a later step carries no proof (proven stays false). Wrapper* unplaced_memory_buffer(Wrapper* device, u64 address, u64 span_bytes, const D3D12_RESOURCE_DESC& requested_desc, - bool* memory_independent = nullptr) + x2w_startup::SrvRefusalProof* refusal = nullptr) { - if (memory_independent) *memory_independent = false; + if (refusal) *refusal = x2w_startup::SrvRefusalProof{}; + const auto prove = [&](x2w_startup::SrvRefusalKind kind, u64 witness = 0, u64 base = 0) { + if (refusal) *refusal = x2w_startup::SrvRefusalProof{kind, witness, base, true}; + }; if (address_resource_overlap(address, span_bytes)) { - if (memory_independent) *memory_independent = true; + prove(x2w_startup::SrvRefusalKind::independent); return nullptr; } u64 page_start = 0, page_span = 0; if (!x2w_startup::unplaced_buffer_extent(address, span_bytes, page_start, page_span)) { - if (memory_independent) *memory_independent = true; + prove(x2w_startup::SrvRefusalKind::independent); return nullptr; } x2w_startup::PlacedBufferRange memory{}; if (!x2w_startup::measure_placed_buffer(reinterpret_cast(page_start), page_span, memory) || - !memory.covered) + !memory.covered) { + if (memory.region_info) + prove(x2w_startup::SrvRefusalKind::fully_committed); + else if (memory.witness) + prove(x2w_startup::SrvRefusalKind::witness_page, memory.witness, reinterpret_cast(memory.base)); return nullptr; + } const auto nearby = placed_buffer_range(device, page_start, page_span, true); if (nearby.reject || nearby.owner) { - if (memory_independent) *memory_independent = true; + prove(x2w_startup::SrvRefusalKind::independent); return nullptr; } @@ -710,25 +719,23 @@ x2w_startup::SrvRefusalKey buffer_refusal_key(const Wrapper* device, const D3D12 return key; } -// Refusals that depend on what is committed at the address are not cached unless X2W_SRV_REFUSAL_CACHE_MEMORY is -// set: commit and decommit happen behind the stand-ins and a region stamp cannot see pages that move with the same -// total, so a retry right after the title commits the buffer could be refused again for up to 250 ms. -bool srv_refusal_cache_memory_enabled() -{ - static const bool enabled = x2w_local::env_on("X2W_SRV_REFUSAL_CACHE_MEMORY"); - return enabled; -} - -// The generation first, then (opt-in only) the memory: a change between the two reads makes the entry stale, never fresh. +// The generation first, then the allocation: a change between the two reads makes the entry stale, never fresh. x2w_startup::SrvRefusalStamp buffer_refusal_stamp(u64 address) { x2w_startup::SrvRefusalStamp stamp; stamp.generation = x2w_startup::srv_placement_generation().load(std::memory_order_acquire); - if (srv_refusal_cache_memory_enabled()) - stamp.valid = x2w_startup::region_stamp(reinterpret_cast(address), stamp.base, stamp.size, stamp.commit, stamp.flags); + stamp.valid = x2w_startup::region_stamp(reinterpret_cast(address), stamp.base, stamp.size, stamp.commit, stamp.flags); return stamp; } +// A cached witness_page refusal still holds while its page is not committed in the allocation the walk started from. +bool buffer_refusal_page_still_uncommitted(const x2w_startup::SrvRefusalProof& proof) +{ + MEMORY_BASIC_INFORMATION page{}; + if (VirtualQuery(reinterpret_cast(proof.witness), &page, sizeof(page)) != sizeof(page)) return true; + return page.State != MEM_COMMIT || (proof.base != 0 && reinterpret_cast(page.AllocationBase) != proof.base); +} + void __stdcall device_memory_srv(Wrapper* self, const D3D12_RESOURCE_DESC* resource, const MemoryShaderResourceView* input, u64 destination) { @@ -762,15 +769,15 @@ void __stdcall device_memory_srv(Wrapper* self, const D3D12_RESOURCE_DESC* resou const u64 span_bytes = (input->view.Buffer.FirstElement + input->view.Buffer.NumElements) * elem_bytes; const auto refusal_key = buffer_refusal_key(self, *resource, *input, span_bytes); const auto refusal_stamp = buffer_refusal_stamp(input->address); - if (buffer_refusal_cache().hit(refusal_key, refusal_stamp, GetTickCount64(), srv_refusal_cache_memory_enabled())) { + if (buffer_refusal_cache().hit(refusal_key, refusal_stamp, GetTickCount64(), buffer_refusal_page_still_uncommitted)) { refuse_memory_srv(refused, "unavailable buffer at the supplied address", "buffer_unavailable", resource, input, destination); return; } Wrapper* buffer = existing_memory_buffer(self, input->address, span_bytes); - bool memory_independent = false; + x2w_startup::SrvRefusalProof refusal_proof; if (!buffer) { - buffer = unplaced_memory_buffer(self, input->address, span_bytes, *resource, &memory_independent); + buffer = unplaced_memory_buffer(self, input->address, span_bytes, *resource, &refusal_proof); } const ResourceInfo* info = buffer ? resource_info(buffer) : nullptr; D3D12_SHADER_RESOURCE_VIEW_DESC adjusted{}; @@ -778,7 +785,8 @@ void __stdcall device_memory_srv(Wrapper* self, const D3D12_RESOURCE_DESC* resou !x2w_startup::resolve_buffer_srv_desc(reinterpret_cast(buffer->own().title_memory), info->console.Width, input->address, input->view, adjusted)) { // A buffer that was found (placed or unplaced) and does not fit the view is decided by its recorded size. - buffer_refusal_cache().note(refusal_key, refusal_stamp, GetTickCount64(), memory_independent || buffer != nullptr); + if (buffer) refusal_proof = x2w_startup::SrvRefusalProof{x2w_startup::SrvRefusalKind::independent, 0, 0, true}; + buffer_refusal_cache().note(refusal_key, refusal_stamp, GetTickCount64(), refusal_proof); refuse_memory_srv(refused, "unavailable buffer at the supplied address", "buffer_unavailable", resource, input, destination); return; diff --git a/src/startup_stubs/placed_buffer_range.h b/src/startup_stubs/placed_buffer_range.h index f72e2b4725..46c5f43d99 100644 --- a/src/startup_stubs/placed_buffer_range.h +++ b/src/startup_stubs/placed_buffer_range.h @@ -30,6 +30,10 @@ struct PlacedBufferRange { bool covered = false; // [base, address + width) is committed and belongs to that allocation bool region_info = false; // proven by one region-information call, without VirtualQuery unsigned queries = 0; // VirtualQuery calls made, for the stand-in's totals + // Why a buffer is not covered, for the refusal cache (srv_refusal_cache.h): the first page, from the allocation + // base to the end of the buffer, that is not committed in that allocation. 0 when none was found (covered, or the + // answer came from the region information alone). + std::uintptr_t witness = 0; }; // exact is what slot 133 uses. The other two exist only for the negative controls in @@ -118,7 +122,10 @@ inline bool measure_placed_buffer(const void* address, std::uint64_t width, Plac // The walk from the base, stopped at the end of the buffer: regions after it cannot change the answer. MEMORY_BASIC_INFORMATION info{}; ++out.queries; - if (VirtualQuery(address, &info, sizeof(info)) != sizeof(info) || info.State != MEM_COMMIT) return false; + if (VirtualQuery(address, &info, sizeof(info)) != sizeof(info) || info.State != MEM_COMMIT) { + out.witness = start; // the address itself is not committed + return false; + } out.base = info.AllocationBase; out.type = info.Type; if (width > UINTPTR_MAX - start) return true; // the end does not exist; the full walk refuses it too @@ -128,8 +135,10 @@ inline bool measure_placed_buffer(const void* address, std::uint64_t width, Plac while (cursor < end) { ++out.queries; if (!VirtualQuery(reinterpret_cast(cursor), ®ion, sizeof(region)) || - region.AllocationBase != out.base || region.State != MEM_COMMIT) + region.AllocationBase != out.base || region.State != MEM_COMMIT) { + out.witness = cursor; // the walk stopped here: this page is not committed in the allocation return true; + } cursor = reinterpret_cast(region.BaseAddress) + region.RegionSize; } out.covered = true; diff --git a/src/startup_stubs/srv_refusal_cache.h b/src/startup_stubs/srv_refusal_cache.h index c788c0c914..9776d2fff9 100644 --- a/src/startup_stubs/srv_refusal_cache.h +++ b/src/startup_stubs/srv_refusal_cache.h @@ -13,16 +13,21 @@ // - the same stand-in state: the placement generation, which advances whenever a resource is indexed, retired, // published or released, or an unplaced buffer is created or dropped (note_placement_change); // - an entry younger than kMaxAgeMs and used fewer than kMaxHits times. -// Two kinds of refusal exist, and only one is exact: -// - memory independent: decided by the request and by stand-in state alone (a live resource overlaps, the span has no +// Three kinds of refusal exist, each with its own exact proof (SrvRefusalKind): +// - independent: decided by the request and by stand-in state alone (a live resource overlaps, the span has no // page extent, a placed buffer owns the page, the found buffer is too small for the view). The key and the -// placement generation prove it, so it is cached by default; -// - memory dependent: decided by what is committed at the address. Commit and decommit happen behind the stand-ins, -// and a region-information stamp (base, size, committed bytes, flags) cannot see pages that move with the same -// total (reserve 128 KiB, commit the upper half, refuse; decommit it, commit the lower half, retry at once: the -// stamp is identical but the buffer is now readable). Such a refusal is cached only when the caller opts in -// (allow_memory_dependent), accepting that a retry within kMaxAgeMs can be refused again. -// A miss runs the full resolution unchanged. The default lookup never refuses what the full path would publish. +// placement generation prove it; +// - fully_committed: the allocation holding the address is private and every byte of it is committed, and the +// buffer does not fit the allocation. A region-information stamp (base, size, committed bytes, flags) with the +// committed bytes equal to the size cannot hide a page move: there is no uncommitted page left to move; +// - witness_page: the walk from the allocation base found a page that is not committed (or belongs to another +// allocation) before the end of the buffer. The refusal holds exactly as long as that one page is still not +// committed in the same allocation, so a hit re-asks only that page (the caller's still_refuses) and the +// allocation base. Commit and decommit happen behind the stand-ins, and a committed-byte total cannot see pages +// that move with the same total (reserve 128 KiB, commit the upper half, refuse; decommit it, commit the lower +// half, retry at once: the totals are equal but the witness page is now committed, so the entry misses). +// A refusal decided by a later step that no proof covers is not cached. A miss runs the full resolution unchanged. +// A hit never refuses what the full path would publish. #include #include @@ -60,6 +65,15 @@ struct SrvRefusalKey { } }; +enum class SrvRefusalKind : std::uint8_t { independent, fully_committed, witness_page }; + +struct SrvRefusalProof { + SrvRefusalKind kind = SrvRefusalKind::independent; + std::uint64_t witness = 0; // witness_page: an address of the page that is not committed + std::uint64_t base = 0; // witness_page: the allocation base the walk started from + bool proven = false; // false: nothing proves this refusal, it is not cached +}; + struct SrvRefusalStamp { bool valid = false; // the region information could be read std::uint64_t generation = 0; @@ -81,31 +95,43 @@ class SrvRefusalCache { static constexpr std::uint32_t kMaxHits = 1024; // True when this request was refused under the same stand-in and memory state a moment ago. - bool hit(const SrvRefusalKey& key, const SrvRefusalStamp& stamp, std::uint64_t now_ms, - bool allow_memory_dependent = false) + // still_refuses(proof) answers a witness_page entry: the page is still not committed in the allocation. + template + bool hit(const SrvRefusalKey& key, const SrvRefusalStamp& stamp, std::uint64_t now_ms, StillRefuses&& still_refuses) { + SrvRefusalProof proof; + { + std::lock_guard lock(mutex_); + const Entry& e = entries_[slot(key)]; + if (!e.used || !(e.key == key) || now_ms < e.noted_ms || now_ms - e.noted_ms > kMaxAgeMs || e.hits >= kMaxHits || + e.stamp.generation != stamp.generation) + return false; + proof = e.proof; + if (proof.kind == SrvRefusalKind::fully_committed && !(e.stamp == stamp)) return false; + // base 0: the address page itself was not committed, no allocation was involved. + if (proof.kind == SrvRefusalKind::witness_page && proof.base != 0 && !(stamp.valid && stamp.base == proof.base)) + return false; + } + // The page question is asked outside the lock; the entry is re-checked before it counts a hit. + if (proof.kind == SrvRefusalKind::witness_page && !still_refuses(proof)) return false; std::lock_guard lock(mutex_); Entry& e = entries_[slot(key)]; - if (!e.used || !(e.key == key) || now_ms < e.noted_ms || - now_ms - e.noted_ms > kMaxAgeMs || e.hits >= kMaxHits) { - return false; - } - if (e.memory_independent) { - if (e.stamp.generation != stamp.generation) return false; - } else if (!allow_memory_dependent || !(e.stamp == stamp)) { - return false; - } + if (!e.used || !(e.key == key) || e.hits >= kMaxHits || e.stamp.generation != stamp.generation) return false; ++e.hits; return true; } - // Remember a refusal the full resolution just produced. memory_independent: it does not depend on what is - // committed at the address (see above); the stamp's generation is then the only state it needs. - void note(const SrvRefusalKey& key, const SrvRefusalStamp& stamp, std::uint64_t now_ms, bool memory_independent) + // Remember a refusal the full resolution just produced, with the proof that keeps it exact. A proof that needs the + // memory stamp is refused when the stamp could not be read. + void note(const SrvRefusalKey& key, const SrvRefusalStamp& stamp, std::uint64_t now_ms, const SrvRefusalProof& proof) { - if (!memory_independent && !stamp.valid) return; + if (!proof.proven) return; + const bool needs_stamp = proof.kind == SrvRefusalKind::fully_committed || + (proof.kind == SrvRefusalKind::witness_page && proof.base != 0); + if (needs_stamp && !stamp.valid) return; + if (proof.kind == SrvRefusalKind::witness_page && proof.witness == 0) return; std::lock_guard lock(mutex_); - entries_[slot(key)] = Entry{true, key, stamp, now_ms, 0, memory_independent}; + entries_[slot(key)] = Entry{true, key, stamp, now_ms, 0, proof}; } void clear() @@ -121,7 +147,7 @@ class SrvRefusalCache { SrvRefusalStamp stamp; std::uint64_t noted_ms = 0; std::uint32_t hits = 0; - bool memory_independent = false; + SrvRefusalProof proof; }; static std::size_t slot(const SrvRefusalKey& k) diff --git a/tests/startup_srv_refusal_cache_check.cpp b/tests/startup_srv_refusal_cache_check.cpp index 8e58217cf9..a613ad24cb 100644 --- a/tests/startup_srv_refusal_cache_check.cpp +++ b/tests/startup_srv_refusal_cache_check.cpp @@ -1,18 +1,22 @@ // Checks the negative cache of refused buffer memory SRVs (device slot 70, src/startup_stubs/srv_refusal_cache.h) -// without a device. A refusal decided by the request and the stand-in state alone (memory independent) is reused for -// the same request and placement generation. A refusal that depends on what is committed at the address is never -// reused by the default lookup: pages can move with the same committed total (reserve 128 KiB, commit the upper -// 64 KiB, refuse; decommit it, commit the lower 64 KiB, retry at once), which no region stamp can see. +// without a device. Every cached refusal carries an exact proof: +// independent: same request and placement generation; +// fully_committed: the allocation is fully committed and its stamp is unchanged; +// witness_page: the one page found uncommitted is still uncommitted in the same allocation. +// The reported page move (reserve 128 KiB, commit the upper 64 KiB, refuse; decommit it, commit the lower 64 KiB, +// retry at once; same base, size and committed total) must miss, because its witness page is now committed. // --mutate generation: expect a changed placement generation to still hit. -// --mutate memory: expect the default lookup to reuse a memory dependent refusal (the page-move case). +// --mutate witness: expect the page move to still hit (the witness page is not asked). +// --mutate stamp: expect a fully_committed entry to hit under a changed stamp. // --mutate key: expect a different view to hit an entry noted for another view. // --mutate device: expect the same request on another device to hit an entry noted for the first device. // --mutate age: expect an entry older than the age limit to still hit. // --mutate hits: expect an entry used more than the hit limit to still hit. -// --mutate invalid: expect a memory dependent entry with an unreadable stamp to hit under the opt-in. +// --mutate unproven: expect a refusal without a proof to be cached. // Each mutated run is a negative control and must fail. #include "startup_stubs/srv_refusal_cache.h" +#include #include #include @@ -33,9 +37,29 @@ void check(const char* name, bool condition) std::printf("FAIL %s\n", name); } -x2w_startup::SrvRefusalKey request(std::uint64_t address, std::uint64_t first_element) +using namespace x2w_startup; + +constexpr std::uint64_t kBase = 0x7000000000ull; +constexpr std::uint64_t kPage = 0x10000; // 64 KiB + +// A fake allocation of two 64 KiB pages: which are committed. The real question is a VirtualQuery of one page. +std::array committed{}; + +bool page_still_uncommitted(const SrvRefusalProof& proof) { - x2w_startup::SrvRefusalKey key; + if (mutated("witness")) return true; + return !committed[(proof.witness - kBase) / kPage]; +} + +bool never_asked(const SrvRefusalProof&) +{ + check("only a witness_page entry asks about a page", false); + return true; +} + +SrvRefusalKey request(std::uint64_t address, std::uint64_t first_element) +{ + SrvRefusalKey key; key.device = 0x5000; key.address = address; key.span_bytes = 0x4000; @@ -47,131 +71,164 @@ x2w_startup::SrvRefusalKey request(std::uint64_t address, std::uint64_t first_el return key; } -x2w_startup::SrvRefusalStamp stamp(std::uint64_t generation, std::uint64_t commit) +SrvRefusalStamp stamp(std::uint64_t generation, std::uint64_t commit) { - x2w_startup::SrvRefusalStamp s; + SrvRefusalStamp s; s.valid = true; s.generation = generation; - s.base = 0x7000000000ull; - s.size = 0x20000; // 128 KiB reservation + s.base = kBase; + s.size = 2 * kPage; // 128 KiB reservation s.commit = commit; s.flags = 1; return s; } +SrvRefusalProof independent() +{ + return SrvRefusalProof{SrvRefusalKind::independent, 0, 0, true}; +} + +SrvRefusalProof fully_committed() +{ + return SrvRefusalProof{SrvRefusalKind::fully_committed, 0, 0, true}; +} + +SrvRefusalProof witness_page(std::uint64_t page) +{ + return SrvRefusalProof{SrvRefusalKind::witness_page, kBase + page * kPage, kBase, true}; +} + } // namespace int main(int argc, char** argv) { if (argc == 3 && std::strcmp(argv[1], "--mutate") == 0) mutation = argv[2]; - using namespace x2w_startup; - const std::uint64_t kHalf = 0x10000; // 64 KiB { SrvRefusalCache cache; - const auto key = request(0x7000001000ull, 0); - check("an empty cache misses", !cache.hit(key, stamp(5, 0), 100)); - cache.note(key, stamp(5, 0), 100, true); - check("a memory independent refusal hits for the same request and generation", cache.hit(key, stamp(5, 0), 150)); - check("a hit repeats", cache.hit(key, stamp(5, 0), 160)); - // The commit state is irrelevant to such a refusal: it was decided without reading memory. - check("a memory independent refusal ignores the committed total", cache.hit(key, stamp(5, kHalf), 170)); + const auto key = request(kBase + 0x1000, 0); + check("an empty cache misses", !cache.hit(key, stamp(5, 0), 100, never_asked)); + cache.note(key, stamp(5, 0), 100, independent()); + check("an independent refusal hits for the same request and generation", cache.hit(key, stamp(5, 0), 150, never_asked)); + check("a hit repeats", cache.hit(key, stamp(5, 0), 160, never_asked)); + check("an independent refusal ignores the memory", cache.hit(key, stamp(5, kPage), 170, never_asked)); + const bool hit = cache.hit(key, stamp(6, 0), 180, never_asked); + check("a new placement generation misses (a resource may now cover the address)", mutated("generation") ? hit : !hit); + } + { + // The reported sequence. Request at the allocation base; only the upper page is committed. + SrvRefusalCache cache; + const auto key = request(kBase, 0); + committed = {false, true}; + cache.note(key, stamp(5, kPage), 100, witness_page(0)); + check("the refusal still holds while the witness page is uncommitted", cache.hit(key, stamp(5, kPage), 101, page_still_uncommitted)); + // Decommit the upper page, commit the lower one: same base, same reservation, same committed total. + committed = {true, false}; + check("the equal stamp does not hide the page move", stamp(5, kPage) == stamp(5, kPage)); + check("after the page move the full path runs (the witness page is committed)", + !cache.hit(key, stamp(5, kPage), 102, page_still_uncommitted)); + // A request that starts in the upper page walks from the base too: the witness is still the lower page. + committed = {false, true}; + const auto upper = request(kBase + kPage, 0); + cache.note(upper, stamp(5, kPage), 110, witness_page(0)); + check("a request in the upper page is proven by the same witness", cache.hit(upper, stamp(5, kPage), 111, page_still_uncommitted)); + committed = {true, true}; + check("committing the witness page makes it miss", !cache.hit(upper, stamp(5, 2 * kPage), 112, page_still_uncommitted)); } { SrvRefusalCache cache; - const auto key = request(0x7000001000ull, 0); - cache.note(key, stamp(5, 0), 100, true); - const bool hit = cache.hit(key, stamp(6, 0), 110); - check("a new placement generation misses (a resource may now cover the address)", mutated("generation") ? hit : !hit); + const auto key = request(kBase, 0); + committed = {false, true}; + cache.note(key, stamp(5, kPage), 100, witness_page(0)); + auto other_allocation = stamp(5, kPage); + other_allocation.base += 0x100000; + check("another allocation base misses", !cache.hit(key, other_allocation, 101, page_still_uncommitted)); + SrvRefusalStamp unreadable = stamp(5, kPage); + unreadable.valid = false; + check("an unreadable allocation stamp misses", !cache.hit(key, unreadable, 101, page_still_uncommitted)); + check("a new generation misses", !cache.hit(key, stamp(6, kPage), 101, page_still_uncommitted)); + cache.note(request(kBase, 1), unreadable, 100, witness_page(0)); + check("a witness entry that needs the allocation is not cached without a stamp", + !cache.hit(request(kBase, 1), stamp(5, kPage), 101, page_still_uncommitted)); + // The address page itself was uncommitted: no allocation is involved (base 0), only that page is asked. + SrvRefusalProof address_page{SrvRefusalKind::witness_page, kBase, 0, true}; + committed = {false, false}; + cache.note(request(kBase, 2), unreadable, 100, address_page); + check("an uncommitted address hits without an allocation stamp", cache.hit(request(kBase, 2), unreadable, 101, page_still_uncommitted)); + committed = {true, false}; + check("a committed address misses", !cache.hit(request(kBase, 2), unreadable, 102, page_still_uncommitted)); } { - // Reported sequence: reserve 128 KiB, commit the upper 64 KiB, the slot-70 request refuses; decommit the - // upper half, commit and fill the lower half (same base, same reservation, same committed total), retry at once. SrvRefusalCache cache; - const auto key = request(0x7000000000ull, 0); - const auto upper_committed = stamp(5, kHalf); - const auto lower_committed = stamp(5, kHalf); // identical stamp: the move is invisible - cache.note(key, upper_committed, 100, false); - bool hit = cache.hit(key, lower_committed, 101); - if (mutated("memory")) hit = cache.hit(key, lower_committed, 101, true) || hit; - check("the page move with an equal stamp runs the full path", !hit); - check("a memory dependent refusal never hits by default", !cache.hit(key, upper_committed, 102)); - // Opt-in accepts exactly this staleness, so it must be off unless asked for. - check("the opt-in reuses a memory dependent refusal for an equal stamp", cache.hit(key, upper_committed, 103, true)); - check("the opt-in still misses on a different committed total", !cache.hit(key, stamp(5, 2 * kHalf), 104, true)); - auto moved = stamp(5, kHalf); - moved.base += 0x10000; - check("the opt-in misses on another base", !cache.hit(key, moved, 104, true)); - auto flagged = stamp(5, kHalf); - flagged.flags = 2; - check("the opt-in misses on other flags", !cache.hit(key, flagged, 104, true)); - check("the opt-in misses on a new generation", !cache.hit(key, stamp(6, kHalf), 104, true)); + const auto key = request(kBase, 0); + cache.note(key, stamp(5, 2 * kPage), 100, fully_committed()); + check("a fully committed allocation hits under the same stamp", cache.hit(key, stamp(5, 2 * kPage), 101, never_asked)); + const bool hit = cache.hit(key, stamp(5, kPage), 102, never_asked); + check("a fully committed refusal misses when the stamp changes", mutated("stamp") ? hit : !hit); + auto resized = stamp(5, 2 * kPage); + resized.size += kPage; + check("a resized allocation misses", !cache.hit(key, resized, 102, never_asked)); + auto moved = stamp(5, 2 * kPage); + moved.base += kPage; + check("another base misses", !cache.hit(key, moved, 102, never_asked)); } { SrvRefusalCache cache; - cache.note(request(0x7000001000ull, 0), stamp(5, 0), 100, true); - const bool other_view = cache.hit(request(0x7000001000ull, 8), stamp(5, 0), 110); + cache.note(request(kBase + 0x1000, 0), stamp(5, 0), 100, independent()); + const bool other_view = cache.hit(request(kBase + 0x1000, 8), stamp(5, 0), 110, never_asked); check("another view of the same address misses", mutated("key") ? other_view : !other_view); - check("another address misses", !cache.hit(request(0x7000002000ull, 0), stamp(5, 0), 110)); - auto other_device = request(0x7000001000ull, 0); + check("another address misses", !cache.hit(request(kBase + 0x2000, 0), stamp(5, 0), 110, never_asked)); + auto other_device = request(kBase + 0x1000, 0); other_device.device += 0x100; - const bool device_hit = cache.hit(other_device, stamp(5, 0), 110); + const bool device_hit = cache.hit(other_device, stamp(5, 0), 110, never_asked); check("the same request on another device misses (placement lookups are per device)", mutated("device") ? device_hit : !device_hit); - auto wider = request(0x7000001000ull, 0); + auto wider = request(kBase + 0x1000, 0); wider.span_bytes += 4; - check("another span misses", !cache.hit(wider, stamp(5, 0), 110)); - auto resource = request(0x7000001000ull, 0); + check("another span misses", !cache.hit(wider, stamp(5, 0), 110, never_asked)); + auto resource = request(kBase + 0x1000, 0); resource.resource_b += 1; - check("another resource width misses", !cache.hit(resource, stamp(5, 0), 110)); + check("another resource width misses", !cache.hit(resource, stamp(5, 0), 110, never_asked)); } { SrvRefusalCache cache; - const auto key = request(0x7000001000ull, 0); - cache.note(key, stamp(5, 0), 100, true); - const bool old_hit = cache.hit(key, stamp(5, 0), 100 + SrvRefusalCache::kMaxAgeMs + 1); + const auto key = request(kBase, 0); + cache.note(key, stamp(5, 0), 100, independent()); + const bool old_hit = cache.hit(key, stamp(5, 0), 100 + SrvRefusalCache::kMaxAgeMs + 1, never_asked); check("an entry older than the age limit misses", mutated("age") ? old_hit : !old_hit); - check("an entry exactly at the age limit still hits", [&] { - SrvRefusalCache fresh; - fresh.note(key, stamp(5, 0), 100, true); - return fresh.hit(key, stamp(5, 0), 100 + SrvRefusalCache::kMaxAgeMs); - }()); - check("a clock that went backwards misses", [&] { - SrvRefusalCache fresh; - fresh.note(key, stamp(5, 0), 100, true); - return !fresh.hit(key, stamp(5, 0), 50); - }()); + SrvRefusalCache fresh; + fresh.note(key, stamp(5, 0), 100, independent()); + check("an entry exactly at the age limit still hits", fresh.hit(key, stamp(5, 0), 100 + SrvRefusalCache::kMaxAgeMs, never_asked)); + SrvRefusalCache backwards; + backwards.note(key, stamp(5, 0), 100, independent()); + check("a clock that went backwards misses", !backwards.hit(key, stamp(5, 0), 50, never_asked)); } { SrvRefusalCache cache; - const auto key = request(0x7000001000ull, 0); - cache.note(key, stamp(5, 0), 100, true); + const auto key = request(kBase, 0); + cache.note(key, stamp(5, 0), 100, independent()); bool all = true; - for (std::uint32_t i = 0; i < SrvRefusalCache::kMaxHits; ++i) all = cache.hit(key, stamp(5, 0), 110) && all; + for (std::uint32_t i = 0; i < SrvRefusalCache::kMaxHits; ++i) all = cache.hit(key, stamp(5, 0), 110, never_asked) && all; check("the entry hits up to the hit limit", all); - const bool over = cache.hit(key, stamp(5, 0), 110); + const bool over = cache.hit(key, stamp(5, 0), 110, never_asked); check("past the hit limit the full path runs again", mutated("hits") ? over : !over); - cache.note(key, stamp(5, 0), 120, true); // the full path refused again and re-noted - check("a re-noted entry hits again", cache.hit(key, stamp(5, 0), 121)); + cache.note(key, stamp(5, 0), 120, independent()); // the full path refused again and re-noted + check("a re-noted entry hits again", cache.hit(key, stamp(5, 0), 121, never_asked)); } { SrvRefusalCache cache; - const auto key = request(0x7000001000ull, 0); - SrvRefusalStamp unreadable = stamp(5, kHalf); - unreadable.valid = false; - cache.note(key, unreadable, 100, false); - const bool hit = cache.hit(key, unreadable, 110, true); - check("a memory dependent refusal with an unreadable stamp is never cached", mutated("invalid") ? hit : !hit); - // An unreadable stamp does not matter to a memory independent refusal. - cache.note(key, unreadable, 100, true); - check("a memory independent refusal does not need the stamp", cache.hit(key, unreadable, 110)); + const auto key = request(kBase, 0); + SrvRefusalProof none = independent(); + none.proven = mutated("unproven"); + cache.note(key, stamp(5, 0), 100, none); + check("a refusal without a proof is never cached", !cache.hit(key, stamp(5, 0), 101, never_asked)); } { SrvRefusalCache cache; - const auto key = request(0x7000001000ull, 0); - cache.note(key, stamp(5, 0), 100, true); + const auto key = request(kBase, 0); + cache.note(key, stamp(5, 0), 100, independent()); cache.clear(); - check("clear forgets everything", !cache.hit(key, stamp(5, 0), 110)); + check("clear forgets everything", !cache.hit(key, stamp(5, 0), 110, never_asked)); const auto before = srv_placement_generation().load(); note_placement_change(); check("note_placement_change advances the generation", srv_placement_generation().load() == before + 1); From 79d926f0f3b27b89a8b94c78f9e3f144637194f7 Mon Sep 17 00:00:00 2001 From: c1 Date: Thu, 26 Nov 2026 13:09:05 +0100 Subject: [PATCH 6/8] fix: advance the SRV refusal generation when a released resource is referenced again --- src/startup_stubs/d3d12_xs_device.cpp | 10 ++++++++-- src/startup_stubs/srv_refusal_cache.h | 7 +++++++ tests/startup_srv_refusal_cache_check.cpp | 5 +++++ 3 files changed, 20 insertions(+), 2 deletions(-) diff --git a/src/startup_stubs/d3d12_xs_device.cpp b/src/startup_stubs/d3d12_xs_device.cpp index 87fe37261e..429d3c5160 100644 --- a/src/startup_stubs/d3d12_xs_device.cpp +++ b/src/startup_stubs/d3d12_xs_device.cpp @@ -994,14 +994,20 @@ HRESULT __stdcall query_interface(Wrapper* self, const GUID* iid, void** out) *out = nullptr; HRESULT hr = E_NOINTERFACE; if (is_base_iid(*iid) || kind_for(*iid) == self->own().kind) { - InterlockedIncrement(&self->own().refs); + const auto refs = InterlockedIncrement(&self->own().refs); + if (self->own().kind == resource_kind && self->own().title_memory) x2w_startup::note_resource_reference(refs); *out = self; hr = S_OK; } log("x2w-d3d12 %s::QueryInterface riid=%s -> 0x%08lx", kind_names[self->own().kind], text, static_cast(hr)); return hr; } -ULONG __stdcall add_ref(Wrapper* self) { return static_cast(InterlockedIncrement(&self->own().refs)); } +ULONG __stdcall add_ref(Wrapper* self) +{ + const auto refs = InterlockedIncrement(&self->own().refs); + if (self->own().kind == resource_kind && self->own().title_memory) x2w_startup::note_resource_reference(refs); + return static_cast(refs); +} // X2W_D3D12_LINEAR_BUFFERS (opt-in): the shared or copied backing of slot 133's linear buffers // (src/startup_stubs/linear_buffer_backing.h). Unused while the switch is off. x2w_startup::LinearBuffers& linear_buffers() diff --git a/src/startup_stubs/srv_refusal_cache.h b/src/startup_stubs/srv_refusal_cache.h index 9776d2fff9..1d5e10ff8c 100644 --- a/src/startup_stubs/srv_refusal_cache.h +++ b/src/startup_stubs/srv_refusal_cache.h @@ -49,6 +49,13 @@ inline void note_placement_change() srv_placement_generation().fetch_add(1, std::memory_order_acq_rel); } +// Call with the reference count a resource has just reached by add_ref / query_interface: the step from zero back to +// one makes it live again for existing_memory_buffer, so a refusal cached while it was released is stale. +inline void note_resource_reference(long refs_after_increment) +{ + if (refs_after_increment == 1) note_placement_change(); +} + struct SrvRefusalKey { std::uint64_t device = 0; // the device wrapper: every placement lookup is per device std::uint64_t address = 0; diff --git a/tests/startup_srv_refusal_cache_check.cpp b/tests/startup_srv_refusal_cache_check.cpp index a613ad24cb..59129288a3 100644 --- a/tests/startup_srv_refusal_cache_check.cpp +++ b/tests/startup_srv_refusal_cache_check.cpp @@ -232,6 +232,11 @@ int main(int argc, char** argv) const auto before = srv_placement_generation().load(); note_placement_change(); check("note_placement_change advances the generation", srv_placement_generation().load() == before + 1); + note_resource_reference(2); + note_resource_reference(3); + check("a reference added to a live resource keeps the generation", srv_placement_generation().load() == before + 1); + note_resource_reference(1); + check("a resource referenced again from zero advances the generation", srv_placement_generation().load() == before + 2); } if (failures) { From eb6b918b3ec07213b3b27a2f111e9fea94d4ea37 Mon Sep 17 00:00:00 2001 From: tedin7 <110300616+tedin7@users.noreply.github.com> Date: Sat, 28 Nov 2026 00:21:59 +0100 Subject: [PATCH 7/8] test: read the retry-write addresses by name in the slot 70 refusal check --- tests/startup_address_buffer_srv_check.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/tests/startup_address_buffer_srv_check.py b/tests/startup_address_buffer_srv_check.py index a318a18560..4f97ac93ef 100644 --- a/tests/startup_address_buffer_srv_check.py +++ b/tests/startup_address_buffer_srv_check.py @@ -36,7 +36,7 @@ def check_refusal_lines(log): ] expected.extend( prefix + "unavailable buffer at the supplied address: reason=buffer_unavailable " - + WIDE_BUFFER + rf" dest=({HEX}) dest_in_view_heap=1 address=({HEX}) address_readable={readable}" + + WIDE_BUFFER + rf" dest=(?P{HEX}) dest_in_view_heap=1 address=(?P
{HEX}) address_readable={readable}" for readable in (0, 1) # reserved base, live narrow placement ) lines = [line.rstrip() for line in log.splitlines() if "Device::slot70" in line] @@ -47,8 +47,8 @@ def check_refusal_lines(log): match = re.fullmatch(pattern, line) if not match: raise AssertionError(f"slot 70 line does not match\n line {line}\n expected {pattern}") - if match.groups(): - dest, address = match.groups() + if match.groupdict().get("dest"): + dest, address = match["dest"], match["address"] write = rf"x2w-d3d12 memory SRV written \d+: dest={dest} address={address} " + WIDE_BUFFER count = sum(re.fullmatch(write, entry) is not None for entry in writes) if count != 1: From 780f53fd4c6601104e7e89e51d02b0853502dbfc Mon Sep 17 00:00:00 2001 From: tedin7 <110300616+tedin7@users.noreply.github.com> Date: Sat, 28 Nov 2026 22:48:19 +0100 Subject: [PATCH 8/8] test: pin the refusal cache key compare with a request that shares the slot, for every key field --- tests/startup_srv_refusal_cache_check.cpp | 29 +++++++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/tests/startup_srv_refusal_cache_check.cpp b/tests/startup_srv_refusal_cache_check.cpp index 59129288a3..1928c74ae4 100644 --- a/tests/startup_srv_refusal_cache_check.cpp +++ b/tests/startup_srv_refusal_cache_check.cpp @@ -19,6 +19,7 @@ #include #include #include +#include namespace { @@ -239,6 +240,34 @@ int main(int argc, char** argv) check("a resource referenced again from zero advances the generation", srv_placement_generation().load() == before + 2); } + { + // Two different requests that land in the same cache slot must not share a refusal: the key compare, not the + // slot, decides a hit. For each key field find (through the cache's own eviction) a key that shares the slot. + using Field = std::uint64_t SrvRefusalKey::*; + const struct { const char* name; Field field; } fields[] = { + {"device", &SrvRefusalKey::device}, {"address", &SrvRefusalKey::address}, {"span", &SrvRefusalKey::span_bytes}, + {"view_a", &SrvRefusalKey::view_a}, {"view_b", &SrvRefusalKey::view_b}, {"view_c", &SrvRefusalKey::view_c}, + {"resource_a", &SrvRefusalKey::resource_a}, {"resource_b", &SrvRefusalKey::resource_b}}; + for (const auto& f : fields) { + const auto first = request(kBase + 0x1000, 0); + bool found = false; + for (std::uint64_t n = 1; n < 20000 && !found; ++n) { + auto other = first; + other.*(f.field) += n * 0x10; + SrvRefusalCache probe; + probe.note(first, stamp(5, 0), 100, independent()); + probe.note(other, stamp(5, 0), 100, independent()); + if (probe.hit(first, stamp(5, 0), 101, never_asked)) continue; // another slot: first is still cached + found = true; + SrvRefusalCache cache; + cache.note(other, stamp(5, 0), 100, independent()); + check((std::string("a colliding request differing in ") + f.name + " misses").c_str(), + !cache.hit(first, stamp(5, 0), 101, never_asked)); + } + check((std::string("found a slot collision for ") + f.name).c_str(), found); + } + } + if (failures) { std::printf("%d check(s) failed\n", failures); return 1;