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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
3 changes: 3 additions & 0 deletions src/startup_stubs/d3d12_capture.inl
Original file line number Diff line number Diff line change
Expand Up @@ -540,12 +540,14 @@ void index_resource(const Wrapper* w, const ResourceInfo& info)
const u64 base = reinterpret_cast<u64>(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.
Expand All @@ -570,6 +572,7 @@ void retire_placement(Wrapper* w)
}
found->second.placement = Placement::none;
}
x2w_startup::note_placement_change();
Comment thread
tedin7 marked this conversation as resolved.
Resolved
}
ReleaseSRWLockExclusive(&note_lock);
}
Expand Down
94 changes: 88 additions & 6 deletions src/startup_stubs/d3d12_memory_srv.inl
Original file line number Diff line number Diff line change
Expand Up @@ -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<void*>(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<u64>(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
Expand Down Expand Up @@ -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;
}

Expand Down Expand Up @@ -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;
}

Expand Down Expand Up @@ -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<u64>(&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<u64>(device);
key.address = input.address;
key.span_bytes = span_bytes;
key.view_a = (u64{static_cast<UINT>(view.Format)} << 32) | (u64{static_cast<UINT>(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<UINT>(view.Buffer.Flags);
key.resource_a = (u64{static_cast<UINT>(resource.Dimension)} << 32) | static_cast<UINT>(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<const void*>(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<const void*>(proof.witness), &page, sizeof(page)) != sizeof(page) ||
page.State != MEM_COMMIT || (proof.base != 0 && reinterpret_cast<u64>(page.AllocationBase) != proof.base);
});
return still_uncommitted;
}

void __stdcall device_memory_srv(Wrapper* self, const D3D12_RESOURCE_DESC* resource,
const MemoryShaderResourceView* input, u64 destination)
{
Expand Down Expand Up @@ -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;
Comment thread
tedin7 marked this conversation as resolved.
Resolved
}
D3D12_SHADER_RESOURCE_VIEW_DESC adjusted{};
const auto resolve = [&](Wrapper* candidate) {
const auto* info = candidate ? resource_info(candidate) : nullptr;
Expand All @@ -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;
Expand Down
17 changes: 14 additions & 3 deletions src/startup_stubs/d3d12_xs_device.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -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<unsigned long>(hr));
return hr;
}
ULONG __stdcall add_ref(Wrapper* self) { return static_cast<ULONG>(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<ULONG>(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()
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -6288,7 +6298,7 @@ HRESULT publish_placed_buffer(Wrapper* self, void* address, const D3D12_RESOURCE
std::optional<TableWriteLock> 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<const Wrapper*>(w), reinterpret_cast<u64>(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.
Expand Down Expand Up @@ -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);
Expand Down
30 changes: 28 additions & 2 deletions src/startup_stubs/placed_buffer_range.h
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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<std::uintptr_t>(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)
Expand Down Expand Up @@ -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
Expand All @@ -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<const void*>(cursor), &region, 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<std::uintptr_t>(region.BaseAddress) + region.RegionSize;
}
out.covered = true;
Expand Down
Loading
Loading