diff --git a/CMakeLists.txt b/CMakeLists.txt index edcbd1f454..798b23942a 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -2551,6 +2551,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 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() # 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 b8b82b1646..d4a955a225 100644 --- a/src/startup_stubs/d3d12_capture.inl +++ b/src/startup_stubs/d3d12_capture.inl @@ -540,12 +540,14 @@ 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, bool desktop_buffer = false, D3D12_RESOURCE_STATES initial_state = D3D12_RESOURCE_STATE_COMMON) { if (!w || !console) return; x2w_startup::ExclusiveNoteLock guard(note_lock); + x2w_startup::note_placement_change(); TableWriteLock tables; const ResourceInfo info{*console, bytes, Placement::none, nullptr, initial_state, desktop_buffer}; // Record and index change together or not at all (store_indexed); mode 2 leaves the index out. @@ -570,6 +572,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 9d98b3eaee..6ac69c5878 100644 --- a/src/startup_stubs/d3d12_memory_srv.inl +++ b/src/startup_stubs/d3d12_memory_srv.inl @@ -290,27 +290,46 @@ void clear_unplaced_buffers(Wrapper* device) } it->resource.Reset(); it = unplaced_buffers.erase(it); + x2w_startup::note_placement_change(); } else { ++it; } } } +// A refusal proof describes a failure determined by the request, placement, or memory state. Wrapper* unplaced_memory_buffer(Wrapper* device, u64 address, u64 span_bytes, const D3D12_RESOURCE_DESC& requested_desc, - u64 elem_bytes, bool raw) + u64 elem_bytes, bool raw, x2w_startup::SrvRefusalProof* refusal) { - if (address_resource_overlap(address, span_bytes)) return nullptr; + 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)) { + 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 (!x2w_startup::unplaced_buffer_extent(address, span_bytes, page_start, page_span)) { + 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) return nullptr; + if (nearby.reject || nearby.owner) { + prove(x2w_startup::SrvRefusalKind::independent); + return nullptr; + } // A buffer view addresses whole elements from its base. When the base is the 64 KiB page start and the view address is not // a multiple of the element size past it, no FirstElement can name the address: back the view with an upload copy that @@ -450,6 +469,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, exact, native_resource, w}); + x2w_startup::note_placement_change(); return w; } @@ -573,6 +593,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; } @@ -696,6 +718,54 @@ 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 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; + 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 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); + x2w_local::outside_run_breaks([&] { + 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) +{ + bool still_uncommitted = false; + x2w_local::outside_run_breaks([&] { + MEMORY_BASIC_INFORMATION page{}; + still_uncommitted = VirtualQuery(reinterpret_cast(proof.witness), &page, sizeof(page)) != sizeof(page) || + page.State != MEM_COMMIT || (proof.base != 0 && reinterpret_cast(page.AllocationBase) != proof.base); + }); + return still_uncommitted; +} + void __stdcall device_memory_srv(Wrapper* self, const D3D12_RESOURCE_DESC* resource, const MemoryShaderResourceView* input, u64 destination) { @@ -727,6 +797,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(self, *resource, *input, span_bytes); + const auto refusal_stamp = buffer_refusal_stamp(input->address); + 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; + } D3D12_SHADER_RESOURCE_VIEW_DESC adjusted{}; const auto resolve = [&](Wrapper* candidate) { const auto* info = candidate ? resource_info(candidate) : nullptr; @@ -735,13 +812,18 @@ void __stdcall device_memory_srv(Wrapper* self, const D3D12_RESOURCE_DESC* resou input->address, input->view, adjusted); }; Wrapper* buffer = existing_memory_buffer(self, input->address, span_bytes); + x2w_startup::SrvRefusalProof refusal_proof; bool resolved = resolve(buffer); if (!buffer || (!resolved && buffer->own().unplaced_srv_backing)) { buffer = unplaced_memory_buffer(self, input->address, span_bytes, *resource, elem_bytes, - input->view.Buffer.Flags == D3D12_BUFFER_SRV_FLAG_RAW); + input->view.Buffer.Flags == D3D12_BUFFER_SRV_FLAG_RAW, &refusal_proof); resolved = resolve(buffer); } if (!resolved) { + // A backing that cannot represent the view is rejected by its recorded extent and the view layout. + if (buffer && resource_info(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/d3d12_xs_device.cpp b/src/startup_stubs/d3d12_xs_device.cpp index 978b86993d..7b66c561f3 100644 --- a/src/startup_stubs/d3d12_xs_device.cpp +++ b/src/startup_stubs/d3d12_xs_device.cpp @@ -62,6 +62,7 @@ #include "startup_stubs/clear_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" @@ -1179,14 +1180,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() @@ -1233,6 +1240,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) @@ -6288,7 +6298,7 @@ HRESULT publish_placed_buffer(Wrapper* self, void* address, const D3D12_RESOURCE std::optional tables; const HRESULT hr = x2w_startup::publish_placement(note_lock, [&tables]() -> auto& { tables.emplace(); return resource_infos(); }, group.by_start, group.max_width, static_cast(w), reinterpret_cast(address), record, - [&] { index_resource(w, record); }); + [&] { index_resource(w, record); x2w_startup::note_placement_change(); }); tables.reset(); if (FAILED(hr)) { // The caller has never received this wrapper; release its desktop resource and storage. @@ -6858,6 +6868,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 27d6400788..1e786f110a 100644 --- a/src/startup_stubs/placed_buffer_range.h +++ b/src/startup_stubs/placed_buffer_range.h @@ -32,6 +32,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 @@ -72,6 +76,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; +} + namespace placed_detail { // One pass of measure_placed_buffer; out is reset first, so a second pass replaces the first. inline bool measure_once(const void* address, std::uint64_t width, PlacedBufferRange& out, PlacedProof proof) @@ -101,7 +122,10 @@ inline bool measure_once(const void* address, std::uint64_t width, PlacedBufferR // 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 @@ -111,8 +135,10 @@ inline bool measure_once(const void* address, std::uint64_t width, PlacedBufferR 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 new file mode 100644 index 0000000000..1d5e10ff8c --- /dev/null +++ b/src/startup_stubs/srv_refusal_cache.h @@ -0,0 +1,172 @@ +#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); +// - an entry younger than kMaxAgeMs and used fewer than kMaxHits times. +// 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; +// - 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 +#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); +} + +// 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; + 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 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; + } +}; + +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; + 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. + // 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) || e.hits >= kMaxHits || e.stamp.generation != stamp.generation) return false; + ++e.hits; + return true; + } + + // 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 (!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, proof}; + } + + 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; + SrvRefusalProof proof; + }; + + static std::size_t slot(const SrvRefusalKey& k) + { + std::uint64_t h = 1469598103934665603ull; + 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); + } + + std::mutex mutex_; + std::array entries_{}; +}; + +} // namespace x2w_startup diff --git a/tests/startup_address_buffer_srv_check.py b/tests/startup_address_buffer_srv_check.py index 6d0ba47b36..4f97ac93ef 100644 --- a/tests/startup_address_buffer_srv_check.py +++ b/tests/startup_address_buffer_srv_check.py @@ -7,6 +7,10 @@ from startup_address_srv_check import draw_texture HEX = r"0x[0-9a-f]+" +WIDE_BUFFER = ( + r"res\{dim=1 fmt=0 size=65536x1x1 mips=1 layout=0x1 flags=0x0 align=0 samples=1/0\} " + r"view\{dim=1 fmt=39 map=0x1688 first=0 count=16384 stride=0 flags=0x1 \(buffer views are not supported\)\}" +) def check_refusal_lines(log): @@ -30,12 +34,25 @@ def check_refusal_lines(log): buffer_unavailable.replace("FIRST", "0"), # unplaced raw view at page + 1 buffer_unavailable.replace("FIRST", "0"), # unplaced raw view before stride-16 publication ] + expected.extend( + prefix + "unavailable buffer at the supplied address: reason=buffer_unavailable " + + 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] if len(lines) != len(expected): raise AssertionError(f"{len(lines)} slot 70 lines, expected {len(expected)}:\n" + "\n".join(lines)) + writes = [line.rstrip() for line in log.splitlines() if "memory SRV written" in line] for line, pattern in zip(lines, expected): - if not re.fullmatch(pattern, line): + 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.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: + raise AssertionError(f"expected one retry write to {dest} from {address}, got {count}") def check(directory, consumer, backend): @@ -56,13 +73,13 @@ def check(directory, consumer, backend): ) if actual is None: return 77 - values = (17, 63, 141, 141, 99, 17, 201, 201, 55, 77, 55, 201, 201, 173, 173) + values = (17, 63, 141, 141, 99, 17, 201, 201, 55, 77, 55, 201, 201, 173, 173, 219, 227) row = b"".join(bytes((v, 0, 0, 255)) for v in values) expected = row * 4 if actual != expected: raise AssertionError(f"actual {actual.hex()} expected {expected.hex()}") check_refusal_lines(trap_log.read_text(errors="replace")) - print(f"{backend}: buffer memory SRV (raw base, raw interior, unplaced buffer, structured, refused unaligned, refused acceleration structure view, unplaced structured view at a page offset the stride does not divide, unplaced buffer in a large allocation copied) exact") + print(f"{backend}: all {len(values) * 4} buffer SRV pixels exact; page move and placement release each published on retry") return 0 diff --git a/tests/startup_address_srv.cpp b/tests/startup_address_srv.cpp index 0033e03da1..aeff02a4ef 100644 --- a/tests/startup_address_srv.cpp +++ b/tests/startup_address_srv.cpp @@ -866,6 +866,43 @@ int draw_address_buffer_srvs(ID3D12Device* desktop, void* guest, void* list) structured.address = ptr(structured_only + 0x10c); invoke(guest, 70, ptr(&desc), ptr(&structured), cpu); draw(14); + + constexpr UINT half = 65536; + auto wide = desc; + wide.Width = half; + raw.view.Buffer.NumElements = half / sizeof(std::uint32_t); + + // Move the commitment within one reservation. The allocation base, size and committed total stay the same. + // Use a fresh destination so the first successful write has its own diagnostic. + static auto* const moved = static_cast(VirtualAlloc(nullptr, 2 * half, MEM_RESERVE, PAGE_READWRITE)); + if (!moved || !VirtualAlloc(moved + half, half, MEM_COMMIT, PAGE_READWRITE)) return 57; + if (!bind_view_table(guest, list, cpu)) return 42; + raw.address = ptr(moved); + auto start = GetTickCount64(); + invoke(guest, 70, ptr(&wide), ptr(&raw), cpu); + if (!VirtualFree(moved + half, half, MEM_DECOMMIT) || !VirtualAlloc(moved, half, MEM_COMMIT, PAGE_READWRITE)) + return 58; + *reinterpret_cast(moved) = 219; + if (GetTickCount64() - start >= 250) return 59; // Keep the retry within the refusal cache lifetime. + invoke(guest, 70, ptr(&wide), ptr(&raw), cpu); + draw(15); + + // A live narrow placement prevents fallback to the full allocation. Its release changes placement + // generation while leaving the allocation and the request intact. + static auto* const retired = static_cast( + VirtualAlloc(nullptr, half, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)); + if (!retired) return 60; + retired[0] = 227; + void* narrow = nullptr; + if (FAILED(static_cast(invoke(guest, 133, ptr(retired), ptr(&desc), D3D12_RESOURCE_STATE_COMMON, + 0, ptr(&__uuidof(ID3D12Resource)), ptr(&narrow)))) || !narrow) return 61; + if (!bind_view_table(guest, list, cpu)) return 42; + raw.address = ptr(retired); + start = GetTickCount64(); + invoke(guest, 70, ptr(&wide), ptr(&raw), cpu); + if (invoke(narrow, 2) != 0 || GetTickCount64() - start >= 250) return 62; + invoke(guest, 70, ptr(&wide), ptr(&raw), cpu); + draw(16); return 0; } diff --git a/tests/startup_srv_refusal_cache_check.cpp b/tests/startup_srv_refusal_cache_check.cpp new file mode 100644 index 0000000000..1928c74ae4 --- /dev/null +++ b/tests/startup_srv_refusal_cache_check.cpp @@ -0,0 +1,277 @@ +// Checks the negative cache of refused buffer memory SRVs (device slot 70, src/startup_stubs/srv_refusal_cache.h) +// 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 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 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 +#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); +} + +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) +{ + 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; + key.view_a = 0x1234; + key.view_b = first_element; + key.view_c = 64; + key.resource_a = 1; + key.resource_b = 0x10000; + return key; +} + +SrvRefusalStamp stamp(std::uint64_t generation, std::uint64_t commit) +{ + SrvRefusalStamp s; + s.valid = true; + s.generation = generation; + 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]; + + { + SrvRefusalCache cache; + 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(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)); + } + { + SrvRefusalCache cache; + 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(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(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, never_asked); + check("the same request on another device misses (placement lookups are per device)", + mutated("device") ? device_hit : !device_hit); + auto wider = request(kBase + 0x1000, 0); + wider.span_bytes += 4; + 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, never_asked)); + } + { + SrvRefusalCache cache; + 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); + 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(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, never_asked) && all; + check("the entry hits up to the hit limit", all); + 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, 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(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(kBase, 0); + cache.note(key, stamp(5, 0), 100, independent()); + cache.clear(); + 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); + 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); + } + + { + // 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; + } + std::printf("srv refusal cache checks passed\n"); + return 0; +} diff --git a/tests/startup_stream_draw.cpp b/tests/startup_stream_draw.cpp index d59971e41b..b93768206e 100644 --- a/tests/startup_stream_draw.cpp +++ b/tests/startup_stream_draw.cpp @@ -402,7 +402,7 @@ int check_stream_draw(IDXGIAdapter* adapter, void* guest, void* pso, const char* // The translated MRT formats draw one pixel; the other formats keep the 8x4 target. const bool single = typed; const bool legacy = !single; - const UINT width = bc_chain ? 384 : bc7 ? (bc7->small4k ? 48 : bc7->width) : bc ? 4 * 128 : single ? 1 : GetEnvironmentVariableW(L"X2W_TEST_ADDRESS_BUFFER_SRV", nullptr, 0) ? 15 : 8; + const UINT width = bc_chain ? 384 : bc7 ? (bc7->small4k ? 48 : bc7->width) : bc ? 4 * 128 : single ? 1 : GetEnvironmentVariableW(L"X2W_TEST_ADDRESS_BUFFER_SRV", nullptr, 0) ? 17 : 8; const UINT height = bc_chain ? 32 : bc7 ? bc7->height : bc ? 128 : single ? 1 : 4; ComPtr desktop; if (FAILED(D3D12CreateDevice(adapter, D3D_FEATURE_LEVEL_12_0, IID_PPV_ARGS(&desktop)))) return 20;