diff --git a/CHANGELOG.md b/CHANGELOG.md index ce5215d2..178aeac5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,7 +10,7 @@ Guest execution uses original, purpose-built test programs. Commercial Xbox game remains unsupported. ### Added -- `D3D12ConfigureVirtualMemoryX` records a BetterXen-defined version-1 region checked against the Lockhart or Anaconda title limit and `bx_xmem_query_region`. Any other block, including null, stays a logged `S_OK` and is not written. A recognised region is backed by one `WRITE_BACK` / `L0` heap and a persistently mapped buffer; `CreateHeap` of that size returns the backing heap, and `cpu_pointer` in that block is the map address. Placed resources stay on a 64 KiB grid. Live heaps are charged on create and credited on the final Release against the same xmem title budget. `test_d3d12_placed.exe` keeps that heap, writes through the pointer, and checks a fence-separated GPU copy in both directions (#464). +- `D3D12ConfigureVirtualMemoryX` copies a BetterXen version-1 block only when the first 8 bytes are magic `BXVM` (`0x4D565842`) and the struct size. The caller's pointer is not kept. `cpu_pointer` is written only before that call returns (the current persistent map, or 0). After `CreateHeap` builds the backing heap, a second call with the same region reads the map and does not recreate the heap. `CreateHeap` returns that one `WRITE_BACK` / `L0` heap only when the block sets `BX_D3D12_VMEM_FLAG_BACKING_HEAP` and the desc is `CUSTOM`, `WRITE_BACK`, `L0`, `D3D12_HEAP_FLAG_NONE`, alignment 0 or 64 KiB, node masks 0 or 1, and the configured size. Every other `CreateHeap` forwards the desc unchanged and returns the host `HRESULT`, wrapped so the live-heap charge against the xmem title budget is credited on the final `Release` (`E_OUTOFMEMORY` only when that budget is exceeded). The wrapper answers `ID3D12Heap1` when the host heap does. `CreatePlacedResource` on any other heap is forwarded unchanged. On the backing heap the offset must be a multiple of the alignment `GetResourceAllocationInfo` reports and the resource must fit. A null output pointer on `CreateHeap` or `CreatePlacedResource` is forwarded to the host with no budget charge and no wrapper. `test_d3d12_placed.exe` checks aliasing, ordinary heaps, small-resource placement, `ID3D12Heap1`, config lifetime, the write-through pointer, and a fence-separated GPU copy in both directions (#464). - `dxbc-accc` now reaches Windows guests as `bx_shader_bridge.dll`, the x86-64 Windows build of the same crate (#445). It exports exactly the three `bx_shader_bridge.h` entry points and needs no MinGW runtime DLL. `shader-transpiler/crates/dxbc-accc/guest/build.sh` builds the DLL and checks its exports and imports. It also builds `check_bridge.exe`, a C guest program compiled against the frozen header, which sends a real DXC SM 6.6 blob and eight synthetic containers (DXIL with and without trailing bytes, `ACCC`/`FSPX` v1 and v0, dual, legacy `SHEX`, malformed) through the DLL loaded by full path. It checks classification (exact chunk sizes, root signature flag, header digest, declared size), prepare (only the declared container is copied), free, and prints a DXIL vs. `ACCC` count. The build script always uses `/target` and rustup's toolchain, and checks the whole Export Address Table and an import allowlist. On one Apple M5 Pro with CrossOver 26.3, in a prefix and a D3DMetal bottle, it reported `dxil=3 accc_only=2 dual=1 legacy=1 invalid=2` and passed. Synthetic containers only. Staging the DLL in `build-shims`, an `abi/defs` export list, and the `d3d12_xs` PSO hook (#466) are separate changes. - `xgameruntime.dll!QueryApiImpl` now serves offline `XGameSave` and `XPackage` as COM `IUnknown` objects under BetterXen synthetic keys (#468, not yet closed). A title linked against Microsoft's `xgameruntime.lib` does not request these keys. Every synthetic key and COM slot order now lives in `shims/xgameruntime/synthetic_keys.h`, the single place to find or replace them. Signatures, structure layouts, `E_GS_*` values and container-name rules follow the public Microsoft Learn reference. - **XGameSave:** provider init, containers, updates, blob writes, submit and read (both asynchronous), enumeration and the close calls. Saves are separated by SCID: each container is one file under `C:\bx_pls\\saves\\`, replaced atomically on submit. A named mutex per SCID directory serializes access across threads and processes. Damaged files (truncated, trailing bytes, duplicate or NUL-bearing names) read as `ERROR_FILE_CORRUPT`, and enumeration skips them and unreadable files with a log line. Offline choices where the reference is silent (16 MiB including blob names, 256-byte blob names, no sync, retry after a failed submit) are listed in `game_save.cpp`. diff --git a/shims/d3d12_xs/vmem.cpp b/shims/d3d12_xs/vmem.cpp index 626f7630..68427fcc 100644 --- a/shims/d3d12_xs/vmem.cpp +++ b/shims/d3d12_xs/vmem.cpp @@ -9,17 +9,31 @@ /* * The configured region is backed by one CUSTOM WRITE_BACK / L0 heap and a buffer - * that stays mapped. CreateHeap of that size returns that heap. atesahmet0 and - * Arths17 measured this for #473: WRITE_BACK or WRITE_COMBINE on L0 is shared - * memory, and both OpenExistingHeap methods return E_NOTIMPL. This file does not - * call them. OpenExistingHeapFromFileMapping also needs a section handle that - * bx_xmem_region_info does not carry. This file does not request L1 and does not - * treat an xmem address as a GPU pointer. - * Any other size is a normal host heap. Heap alignment values 0, 64 KiB and 4 MiB: - * https://learn.microsoft.com/en-us/windows/win32/api/d3d12/ns-d3d12-d3d12_heap_desc - * Placed offsets are a multiple of the resource alignment and stay inside the heap, - * tightened here to 64 KiB: + * that stays mapped. That heap is created with D3D12_HEAP_FLAG_NONE, 64 KiB + * alignment, and node masks 0. CreateHeap returns it only for the explicit + * opt-in desc documented in vmem.h. atesahmet0 and Arths17 measured this for + * #473: WRITE_BACK or WRITE_COMBINE on L0 is shared memory, and both + * OpenExistingHeap methods return E_NOTIMPL. This file does not call them. + * This file does not request L1 and does not treat an xmem address as a GPU pointer. + * + * Any other CreateHeap forwards the caller's D3D12_HEAP_DESC unmodified and + * returns the host HRESULT. The wrapper and the live-heap xmem budget charge + * are the only differences: charge on create, credit on the wrapper's final + * Release, E_OUTOFMEMORY only when that budget is exceeded. + * A null out pointer is forwarded unchanged to the host. + * vkd3d on CrossOver 26.2 faults on that pointer with or without this shim. + * https://learn.microsoft.com/en-us/windows/win32/api/d3d12/nf-d3d12-id3d12device-createheap + * + * CreatePlacedResource on any heap other than the backing heap is forwarded + * the same way, with no extra checks. On the backing heap the offset must be a + * multiple of the alignment GetResourceAllocationInfo reports, the resource + * must fit, and an upload or readback heap (not this CUSTOM heap) must use the + * initial state Microsoft Learn requires: * https://learn.microsoft.com/en-us/windows/win32/api/d3d12/nf-d3d12-id3d12device-createplacedresource + * https://learn.microsoft.com/en-us/windows/win32/api/d3d12/nf-d3d12-id3d12device-getresourceallocationinfo + * Heap alignment values 0, 64 KiB and 4 MiB, and ID3D12Heap1: + * https://learn.microsoft.com/en-us/windows/win32/api/d3d12/ns-d3d12-d3d12_heap_desc + * https://learn.microsoft.com/en-us/windows/win32/api/d3d12/nn-d3d12-id3d12heap1 * Non-custom heap properties use UNKNOWN CPU page and memory pool: * https://learn.microsoft.com/en-us/windows/win32/api/d3d12/ns-d3d12-d3d12_heap_properties */ @@ -27,29 +41,22 @@ namespace { constexpr uint64_t k64K = 64ull * 1024ull; -constexpr uint64_t k4M = 4ull * 1024ull * 1024ull; constexpr uint32_t kConfigVersion = 1; -constexpr uint32_t kForwardedFlags = - static_cast(D3D12_HEAP_FLAG_DENY_BUFFERS) | - static_cast(D3D12_HEAP_FLAG_DENY_RT_DS_TEXTURES) | - static_cast(D3D12_HEAP_FLAG_DENY_NON_RT_DS_TEXTURES) | - static_cast(D3D12_HEAP_FLAG_ALLOW_SHADER_ATOMICS) | - static_cast(D3D12_HEAP_FLAG_CREATE_NOT_RESIDENT) | - static_cast(D3D12_HEAP_FLAG_CREATE_NOT_ZEROED); - struct Record { bool configured = false; + bool backing_opt_in = false; bx_hardware_profile_t profile = BX_PROFILE_LOCKHART; uint64_t title_limit = 0; bool have_region = false; + uint64_t config_base = 0; + uint64_t config_size = 0; bx_xmem_region_info_t region{}; /* Bytes of host heaps still alive. D3DMetal keeps freed memory in its own pool, so this counts live heaps only: charge on create, credit on the final Release. It does not assume the OS reclaimed the pages. */ uint64_t charged_private_bytes = 0; uint64_t cpu_pointer = 0; - BxD3d12VirtualMemoryConfig* config_block = nullptr; class BxChargedHeap* backing = nullptr; ID3D12Resource* backing_buffer = nullptr; }; @@ -90,55 +97,6 @@ const char* profile_name(bx_hardware_profile_t profile) { return profile == BX_PROFILE_ANACONDA ? "anaconda" : "lockhart"; } -bool node_masks_ok(UINT creation, UINT visible) { - const UINT creation_bit = creation == 0 ? 1u : creation; - const UINT visible_bits = visible == 0 ? creation_bit : visible; - if (creation != 0 && (creation & (creation - 1u)) != 0) { - return false; - } - return (visible_bits & creation_bit) == creation_bit; -} - -HRESULT check_heap_shape(const D3D12_HEAP_DESC* desc) { - if (desc->Properties.MemoryPoolPreference == D3D12_MEMORY_POOL_L1) { - return E_INVALIDARG; - } - const uint64_t align = desc->Alignment == 0 ? k64K : desc->Alignment; - if (align != k64K && align != k4M) { - return E_INVALIDARG; - } - if (desc->SizeInBytes == 0 || desc->SizeInBytes % align != 0 || desc->SizeInBytes % k64K != 0) { - return E_INVALIDARG; - } - switch (desc->Properties.Type) { - case D3D12_HEAP_TYPE_DEFAULT: - case D3D12_HEAP_TYPE_UPLOAD: - case D3D12_HEAP_TYPE_READBACK: - if (desc->Properties.CPUPageProperty != D3D12_CPU_PAGE_PROPERTY_UNKNOWN || - desc->Properties.MemoryPoolPreference != D3D12_MEMORY_POOL_UNKNOWN) { - return E_INVALIDARG; - } - break; - case D3D12_HEAP_TYPE_CUSTOM: - if (desc->Properties.CPUPageProperty == D3D12_CPU_PAGE_PROPERTY_UNKNOWN || - desc->Properties.MemoryPoolPreference == D3D12_MEMORY_POOL_UNKNOWN) { - return E_INVALIDARG; - } - break; - default: - return E_INVALIDARG; - } - if (!node_masks_ok(desc->Properties.CreationNodeMask, desc->Properties.VisibleNodeMask)) { - return E_INVALIDARG; - } - return S_OK; -} - -bool heap_riid(REFIID riid) { - return riid == __uuidof(IUnknown) || riid == __uuidof(ID3D12Object) || riid == __uuidof(ID3D12DeviceChild) || - riid == __uuidof(ID3D12Pageable) || riid == __uuidof(ID3D12Heap); -} - /* Private host heaps count against the same Lockhart/Anaconda cap as xmem. */ bool try_charge(uint64_t bytes) { Guard guard(g_section); @@ -169,32 +127,40 @@ void release_charge(uint64_t bytes) { /* * Holds the budget charge for one private host heap and drops it on the last Release. - * QueryInterface for ID3D12Heap and its base interfaces returns this object, so - * bx_unwrap sees IID_BxProxyHost and CreatePlacedResource receives the host heap. - * A CreateHeap riid outside that set cannot be observed here: the host pointer is - * returned and the charge stays until process exit. Callers in this tree request - * ID3D12Heap. + * QueryInterface for ID3D12Heap, and for ID3D12Heap1 when the host heap answers it, + * returns this object. bx_unwrap sees IID_BxProxyHost and receives the host heap. + * GetProtectedResourceSession forwards to the host ID3D12Heap1. + * https://learn.microsoft.com/en-us/windows/win32/api/d3d12/nn-d3d12-id3d12heap1 */ -class BxChargedHeap final : public ID3D12Heap { +class BxChargedHeap final : public ID3D12Heap1 { public: - static BxChargedHeap* create(ID3D12Heap* host, uint64_t bytes) { - return new (std::nothrow) BxChargedHeap(host, bytes); + static BxChargedHeap* create(ID3D12Heap* host, ID3D12Heap1* host1, uint64_t bytes) { + return new (std::nothrow) BxChargedHeap(host, host1, bytes); } HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, void** ppv) override { if (!ppv) { return E_POINTER; } - if (heap_riid(riid)) { + *ppv = nullptr; + if (riid == __uuidof(IUnknown) || riid == __uuidof(ID3D12Object) || riid == __uuidof(ID3D12DeviceChild) || + riid == __uuidof(ID3D12Pageable) || riid == __uuidof(ID3D12Heap)) { *ppv = static_cast(this); AddRef(); return S_OK; } + if (riid == __uuidof(ID3D12Heap1)) { + if (!host1_) { + return E_NOINTERFACE; + } + *ppv = static_cast(this); + AddRef(); + return S_OK; + } if (riid == IID_BxProxyHost) { *ppv = host_; return S_OK; } - *ppv = nullptr; return E_NOINTERFACE; } @@ -206,6 +172,9 @@ public: /* Final Release of a live heap. D3DMetal may pool the pages after this, so the budget credit is the live-heap count, not a physical-memory drop. */ release_charge(bytes_); + if (host1_) { + host1_->Release(); + } if (host_) { host_->Release(); } @@ -226,41 +195,93 @@ public: HRESULT STDMETHODCALLTYPE SetName(LPCWSTR name) override { return host_->SetName(name); } HRESULT STDMETHODCALLTYPE GetDevice(REFIID riid, void** ppv) override { return host_->GetDevice(riid, ppv); } D3D12_HEAP_DESC* STDMETHODCALLTYPE GetDesc(D3D12_HEAP_DESC* ret) override { return host_->GetDesc(ret); } + HRESULT STDMETHODCALLTYPE GetProtectedResourceSession(REFIID riid, void** session) override { + if (!session) { + return E_POINTER; + } + *session = nullptr; + if (!host1_) { + return E_NOINTERFACE; + } + return host1_->GetProtectedResourceSession(riid, session); + } private: - BxChargedHeap(ID3D12Heap* host, uint64_t bytes) : host_(host), bytes_(bytes) {} + BxChargedHeap(ID3D12Heap* host, ID3D12Heap1* host1, uint64_t bytes) : host_(host), host1_(host1), bytes_(bytes) { + if (host_) { + host_->AddRef(); + } + if (host1_) { + host1_->AddRef(); + } + } ~BxChargedHeap() = default; ID3D12Heap* host_; + ID3D12Heap1* host1_; uint64_t bytes_; LONG refs_ = 1; }; -bool region_matches(const D3D12_HEAP_DESC* desc, const Record& snap, bx_xmem_region_info_t* live) { - if (!snap.configured || !snap.have_region || desc->SizeInBytes != snap.region.size_bytes) { +struct RegionSnap { + bool eligible = false; + uint64_t base = 0; + uint64_t size = 0; +}; + +RegionSnap region_snap() { + Guard guard(g_section); + RegionSnap snap; + snap.eligible = g_record.configured && g_record.backing_opt_in && g_record.have_region && g_record.config_size != 0; + snap.base = g_record.region.base_va; + snap.size = g_record.config_size; + return snap; +} + +bool region_still_mapped(const RegionSnap& snap) { + if (!snap.eligible || snap.size == 0) { return false; } - if (!bx_xmem_query_region(snap.region.base_va, live) || live->base_va != snap.region.base_va || - live->size_bytes == 0 || snap.region.size_bytes % live->size_bytes != 0) { + bx_xmem_region_info_t live{}; + if (!bx_xmem_query_region(snap.base, &live) || live.base_va != snap.base || live.size_bytes == 0 || + snap.size % live.size_bytes != 0) { return false; } - const uint64_t page = live->size_bytes; - for (uint64_t offset = 0; offset < snap.region.size_bytes; offset += page) { + const uint64_t page = live.size_bytes; + for (uint64_t offset = 0; offset < snap.size; offset += page) { bx_xmem_region_info_t part{}; - if (!bx_xmem_query_region(snap.region.base_va + offset, &part) || - part.base_va != snap.region.base_va + offset || part.size_bytes != page) { + if (!bx_xmem_query_region(snap.base + offset, &part) || part.base_va != snap.base + offset || + part.size_bytes != page) { return false; } } - live->size_bytes = snap.region.size_bytes; return true; } -void publish_cpu_pointer(uint64_t pointer) { - g_record.cpu_pointer = pointer; - if (g_record.config_block) { - g_record.config_block->cpu_pointer = pointer; +/* True only for the explicit backing-heap request documented in vmem.h. */ +bool backing_request(const D3D12_HEAP_DESC* desc) { + if (!desc) { + return false; } + if (desc->Properties.Type != D3D12_HEAP_TYPE_CUSTOM || + desc->Properties.CPUPageProperty != D3D12_CPU_PAGE_PROPERTY_WRITE_BACK || + desc->Properties.MemoryPoolPreference != D3D12_MEMORY_POOL_L0) { + return false; + } + if (desc->Alignment != 0 && desc->Alignment != k64K) { + return false; + } + if (desc->Flags != D3D12_HEAP_FLAG_NONE) { + return false; + } + if (desc->Properties.CreationNodeMask > 1 || desc->Properties.VisibleNodeMask > 1) { + return false; + } + const RegionSnap snap = region_snap(); + if (!snap.eligible || desc->SizeInBytes != snap.size) { + return false; + } + return region_still_mapped(snap); } HRESULT host_private_heap(BxDeviceProxy* self, const D3D12_HEAP_DESC* desc, REFIID riid, void** out); @@ -289,6 +310,7 @@ HRESULT ensure_backing(BxDeviceProxy* self, uint64_t bytes, REFIID riid, void** desc.Properties.Type = D3D12_HEAP_TYPE_CUSTOM; desc.Properties.CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_WRITE_BACK; desc.Properties.MemoryPoolPreference = D3D12_MEMORY_POOL_L0; + desc.Flags = D3D12_HEAP_FLAG_NONE; void* created = nullptr; HRESULT hr = host_private_heap(self, &desc, __uuidof(ID3D12Heap), &created); if (FAILED(hr) || !created) { @@ -331,40 +353,45 @@ HRESULT ensure_backing(BxDeviceProxy* self, uint64_t bytes, REFIID riid, void** } g_record.backing = wrap; g_record.backing_buffer = resource; - publish_cpu_pointer(reinterpret_cast(mapped)); + /* Remember the map. The caller's config block is not stored and is not written here. */ + g_record.cpu_pointer = reinterpret_cast(mapped); } return return_backing(riid, out); } HRESULT host_private_heap(BxDeviceProxy* self, const D3D12_HEAP_DESC* desc, REFIID riid, void** out) { + /* desc is forwarded unmodified. The charge follows the wrapper, including ID3D12Heap1. */ if (!try_charge(desc->SizeInBytes)) { bx_log_emit(BX_LOG_WARN, "d3d12_xs", "heap_budget", "CreateHeap exceeds the Lockhart/Anaconda xmem title budget"); return E_OUTOFMEMORY; } void* raw = nullptr; - HRESULT hr = self->h_ID3D12Device->CreateHeap(desc, __uuidof(ID3D12Heap), &raw); + HRESULT hr = self->h_ID3D12Device->CreateHeap(desc, riid, &raw); if (FAILED(hr) || !raw) { release_charge(desc->SizeInBytes); return FAILED(hr) ? hr : E_FAIL; } - auto* host = static_cast(raw); - if (!heap_riid(riid)) { - /* Charge cannot follow an interface this wrapper does not implement. - The first heap is dropped. If the caller's CreateHeap succeeds, the - charge stays until process exit. See BxChargedHeap. */ - host->Release(); - bx_log_emit(BX_LOG_WARN, "d3d12_xs", "heap_budget", - "CreateHeap riid is not ID3D12Heap; the charge stays until process exit"); - hr = self->h_ID3D12Device->CreateHeap(desc, riid, out); - if (FAILED(hr)) { - release_charge(desc->SizeInBytes); - } - return hr; + auto* unknown = static_cast(raw); + ID3D12Heap* host = nullptr; + const HRESULT heap_hr = unknown->QueryInterface(__uuidof(ID3D12Heap), reinterpret_cast(&host)); + if (FAILED(heap_hr) || !host) { + unknown->Release(); + release_charge(desc->SizeInBytes); + return FAILED(heap_hr) ? heap_hr : E_NOINTERFACE; } - BxChargedHeap* wrap = BxChargedHeap::create(host, desc->SizeInBytes); + ID3D12Heap1* host1 = nullptr; + void* probed = nullptr; + if (host->QueryInterface(__uuidof(ID3D12Heap1), &probed) == S_OK && probed) { + host1 = static_cast(probed); + } + BxChargedHeap* wrap = BxChargedHeap::create(host, host1, desc->SizeInBytes); + if (host1) { + host1->Release(); + } + host->Release(); + unknown->Release(); if (!wrap) { - host->Release(); release_charge(desc->SizeInBytes); return E_OUTOFMEMORY; } @@ -376,71 +403,85 @@ HRESULT host_private_heap(BxDeviceProxy* self, const D3D12_HEAP_DESC* desc, REFI return hr; } +bool is_backing_heap(ID3D12Heap* heap) { + if (!heap) { + return false; + } + BxChargedHeap* backing = nullptr; + { + Guard guard(g_section); + backing = g_record.backing; + if (!backing) { + return false; + } + backing->AddRef(); + } + IUnknown* want = nullptr; + IUnknown* got = nullptr; + const HRESULT want_hr = backing->QueryInterface(IID_IUnknown, reinterpret_cast(&want)); + const HRESULT got_hr = heap->QueryInterface(IID_IUnknown, reinterpret_cast(&got)); + const bool same = SUCCEEDED(want_hr) && SUCCEEDED(got_hr) && want == got; + if (want) { + want->Release(); + } + if (got) { + got->Release(); + } + backing->Release(); + return same; +} + +void log_placed(UINT64 offset, HRESULT hr) { + char detail[160]; + std::snprintf(detail, sizeof(detail), "CreatePlacedResource offset=%llu hr=0x%08lx", + static_cast(offset), static_cast(hr)); + bx_log_emit(FAILED(hr) ? BX_LOG_WARN : BX_LOG_INFO, "d3d12_xs", "placed_resource", detail); +} + HRESULT STDMETHODCALLTYPE create_heap(BxDeviceProxy* self, const D3D12_HEAP_DESC* desc, REFIID riid, void** out) { BX_D3D_TRACE("ID3D12Device", "CreateHeap"); - if (!out) { - return E_POINTER; - } - *out = nullptr; if (!self || !self->h_ID3D12Device) { + if (out) { + *out = nullptr; + } BX_VTABLE_STUB_LOG("ID3D12Device", 28u, "CreateHeap"); return E_NOTIMPL; } if (!desc) { + if (out) { + *out = nullptr; + } return E_INVALIDARG; } - if ((static_cast(desc->Flags) & ~kForwardedFlags) != 0) { - BX_VTABLE_STUB_LOG("ID3D12Device", 28u, "CreateHeap"); - return E_NOTIMPL; + if (!out) { + /* A null out pointer is forwarded unchanged to the host. + * vkd3d on CrossOver 26.2 faults on that pointer with or without this shim. + */ + return self->h_ID3D12Device->CreateHeap(desc, riid, nullptr); } - HRESULT hr = check_heap_shape(desc); - if (FAILED(hr)) { - return hr; - } - - Record snap; - { - Guard guard(g_section); - snap = g_record; - } - bx_xmem_region_info_t live{}; - if (region_matches(desc, snap, &live)) { - return ensure_backing(self, live.size_bytes, riid, out); + *out = nullptr; + if (backing_request(desc)) { + return ensure_backing(self, desc->SizeInBytes, riid, out); } return host_private_heap(self, desc, riid, out); } -HRESULT STDMETHODCALLTYPE create_placed(BxDeviceProxy* self, ID3D12Heap* heap, UINT64 offset, - const D3D12_RESOURCE_DESC* desc, D3D12_RESOURCE_STATES state, - const D3D12_CLEAR_VALUE* clear, REFIID riid, void** out) { - BX_D3D_TRACE("ID3D12Device", "CreatePlacedResource"); - if (!out) { - return E_POINTER; - } - *out = nullptr; - if (!self || !self->h_ID3D12Device) { - BX_VTABLE_STUB_LOG("ID3D12Device", 29u, "CreatePlacedResource"); - return E_NOTIMPL; - } - if (!heap || !desc || (offset % k64K) != 0) { +HRESULT validate_backing_placement(ID3D12Device* device, ID3D12Heap* heap, UINT64 offset, const D3D12_RESOURCE_DESC* desc, + D3D12_RESOURCE_STATES state, const D3D12_CLEAR_VALUE* clear) { + if (!heap || !desc) { return E_INVALIDARG; } if (desc->Dimension == D3D12_RESOURCE_DIMENSION_BUFFER && clear) { return E_INVALIDARG; } - D3D12_HEAP_DESC heap_desc = heap->GetDesc(); - if (heap_desc.SizeInBytes % k64K != 0) { - return E_INVALIDARG; - } if (heap_desc.Properties.Type == D3D12_HEAP_TYPE_UPLOAD && state != D3D12_RESOURCE_STATE_GENERIC_READ) { return E_INVALIDARG; } if (heap_desc.Properties.Type == D3D12_HEAP_TYPE_READBACK && state != D3D12_RESOURCE_STATE_COPY_DEST) { return E_INVALIDARG; } - - D3D12_RESOURCE_ALLOCATION_INFO info = self->h_ID3D12Device->GetResourceAllocationInfo(0, 1, desc); + D3D12_RESOURCE_ALLOCATION_INFO info = device->GetResourceAllocationInfo(0, 1, desc); if (info.SizeInBytes == 0 || info.SizeInBytes == ~0ull) { return E_INVALIDARG; } @@ -450,17 +491,62 @@ HRESULT STDMETHODCALLTYPE create_placed(BxDeviceProxy* self, ID3D12Heap* heap, U if (offset > heap_desc.SizeInBytes || info.SizeInBytes > heap_desc.SizeInBytes - offset) { return E_INVALIDARG; } + return S_OK; +} +HRESULT STDMETHODCALLTYPE create_placed(BxDeviceProxy* self, ID3D12Heap* heap, UINT64 offset, + const D3D12_RESOURCE_DESC* desc, D3D12_RESOURCE_STATES state, + const D3D12_CLEAR_VALUE* clear, REFIID riid, void** out) { + BX_D3D_TRACE("ID3D12Device", "CreatePlacedResource"); + if (!self || !self->h_ID3D12Device) { + if (out) { + *out = nullptr; + } + BX_VTABLE_STUB_LOG("ID3D12Device", 29u, "CreatePlacedResource"); + return E_NOTIMPL; + } + if (!out) { + /* A null out pointer is forwarded unchanged to the host. + * vkd3d on CrossOver 26.2 faults on that pointer with or without this shim. + */ + if (is_backing_heap(heap)) { + const HRESULT check_hr = validate_backing_placement(self->h_ID3D12Device, heap, offset, desc, state, clear); + if (FAILED(check_hr)) { + log_placed(offset, check_hr); + return check_hr; + } + } + ID3D12Heap* host_heap = bx_unwrap(heap); + const HRESULT hr = + self->h_ID3D12Device->CreatePlacedResource(host_heap, offset, desc, state, clear, riid, nullptr); + log_placed(offset, hr); + return hr; + } + *out = nullptr; + if (is_backing_heap(heap)) { + const HRESULT check_hr = validate_backing_placement(self->h_ID3D12Device, heap, offset, desc, state, clear); + if (FAILED(check_hr)) { + log_placed(offset, check_hr); + return check_hr; + } + } ID3D12Heap* host_heap = bx_unwrap(heap); - HRESULT hr = self->h_ID3D12Device->CreatePlacedResource(host_heap, offset, desc, state, clear, riid, out); - char detail[160]; - std::snprintf(detail, sizeof(detail), "CreatePlacedResource offset=%llu bytes=%llu hr=0x%08lx", - static_cast(offset), static_cast(info.SizeInBytes), - static_cast(hr)); - bx_log_emit(FAILED(hr) ? BX_LOG_WARN : BX_LOG_INFO, "d3d12_xs", "placed_resource", detail); + const HRESULT hr = + self->h_ID3D12Device->CreatePlacedResource(host_heap, offset, desc, state, clear, riid, out); + log_placed(offset, hr); return hr; } +struct ConfigHeader { + uint32_t magic; + uint32_t struct_size; +}; +static_assert(sizeof(ConfigHeader) == 8, "config probe is the 8-byte header"); + +void write_cpu_pointer(void* config, uint64_t pointer) { + std::memcpy(static_cast(config) + offsetof(BxD3d12VirtualMemoryConfig, cpu_pointer), &pointer, sizeof(pointer)); +} + } // namespace extern "C" HRESULT bx_d3d12_configure_virtual_memory(void* config) { @@ -469,8 +555,21 @@ extern "C" HRESULT bx_d3d12_configure_virtual_memory(void* config) { BX_STUB_LOG("d3d12_xs.dll", "D3D12ConfigureVirtualMemoryX"); return S_OK; } - const auto* in = static_cast(config); - if (in->version != kConfigVersion || in->flags != 0 || in->reserved != 0) { + /* + * PVOID has no size. Read 8 bytes, and only then the rest of a block that + * names this struct. A mismatch is left untouched. + */ + ConfigHeader header{}; + std::memcpy(&header, config, sizeof(header)); + if (header.magic != BX_D3D12_VMEM_MAGIC || header.struct_size != sizeof(BxD3d12VirtualMemoryConfig)) { + BX_STUB_LOG("d3d12_xs.dll", "D3D12ConfigureVirtualMemoryX"); + return S_OK; + } + + BxD3d12VirtualMemoryConfig in{}; + std::memcpy(&in, config, sizeof(in)); + const uint32_t unknown_flags = in.flags & ~BX_D3D12_VMEM_FLAG_BACKING_HEAP; + if (in.version != kConfigVersion || unknown_flags != 0 || in.reserved != 0) { /* A console parameter block is not this struct. Leave those bytes alone. */ BX_STUB_LOG("d3d12_xs.dll", "D3D12ConfigureVirtualMemoryX"); return S_OK; @@ -479,25 +578,25 @@ extern "C" HRESULT bx_d3d12_configure_virtual_memory(void* config) { const bx_runtime_config_t* cfg = bx_get_runtime_config(); const uint64_t cap = title_limit(); const auto profile = (cfg && cfg->profile == BX_PROFILE_ANACONDA) ? BX_PROFILE_ANACONDA : BX_PROFILE_LOCKHART; - if (in->size_bytes != 0 && (in->size_bytes % k64K != 0 || in->size_bytes > cap)) { + if (in.size_bytes != 0 && (in.size_bytes % k64K != 0 || in.size_bytes > cap)) { return E_INVALIDARG; } bx_xmem_stats_t stats{}; bx_xmem_get_internal_stats(&stats); - if (in->size_bytes != 0 && stats.title_limit_bytes != 0 && in->size_bytes > stats.title_limit_bytes) { + if (in.size_bytes != 0 && stats.title_limit_bytes != 0 && in.size_bytes > stats.title_limit_bytes) { return E_INVALIDARG; } bx_xmem_region_info_t region{}; bool have_region = false; - if (in->base_va != 0) { + if (in.base_va != 0) { bx_xmem_region_info_t first{}; - if (!bx_xmem_query_region(in->base_va, &first) || first.size_bytes == 0 || first.base_va != in->base_va || + if (!bx_xmem_query_region(in.base_va, &first) || first.size_bytes == 0 || first.base_va != in.base_va || first.base_va % k64K != 0 || first.size_bytes % k64K != 0) { return E_INVALIDARG; } - const uint64_t span = in->size_bytes != 0 ? in->size_bytes : first.size_bytes; + const uint64_t span = in.size_bytes != 0 ? in.size_bytes : first.size_bytes; if (span < first.size_bytes || span % first.size_bytes != 0) { return E_INVALIDARG; } @@ -513,13 +612,14 @@ extern "C" HRESULT bx_d3d12_configure_virtual_memory(void* config) { have_region = true; } - auto* block = static_cast(config); + const uint64_t new_base = have_region ? region.base_va : in.base_va; + const uint64_t new_size = have_region ? region.size_bytes : in.size_bytes; BxChargedHeap* old_heap = nullptr; ID3D12Resource* old_buffer = nullptr; + uint64_t published = 0; { Guard guard(g_section); - const bool same = have_region && g_record.have_region && g_record.region.base_va == region.base_va && - g_record.region.size_bytes == region.size_bytes; + const bool same = g_record.configured && g_record.config_base == new_base && g_record.config_size == new_size; if (!same) { old_heap = g_record.backing; old_buffer = g_record.backing_buffer; @@ -528,13 +628,17 @@ extern "C" HRESULT bx_d3d12_configure_virtual_memory(void* config) { g_record.cpu_pointer = 0; } g_record.configured = true; + g_record.backing_opt_in = (in.flags & BX_D3D12_VMEM_FLAG_BACKING_HEAP) != 0; g_record.profile = profile; g_record.title_limit = cap; g_record.have_region = have_region; + g_record.config_base = new_base; + g_record.config_size = new_size; g_record.region = have_region ? region : bx_xmem_region_info_t{}; - g_record.config_block = block; - block->cpu_pointer = g_record.cpu_pointer; + published = g_record.cpu_pointer; } + /* The only write to caller memory, and it happens before this call returns. */ + write_cpu_pointer(config, published); if (old_buffer) { old_buffer->Unmap(0, nullptr); old_buffer->Release(); diff --git a/shims/d3d12_xs/vmem.h b/shims/d3d12_xs/vmem.h index b41d3f07..6fb4cb8b 100644 --- a/shims/d3d12_xs/vmem.h +++ b/shims/d3d12_xs/vmem.h @@ -7,19 +7,50 @@ /* * BetterXen-defined parameter block for D3D12ConfigureVirtualMemoryX. - * version is 1. flags and reserved must be 0. + * + * The export is PVOID and the frozen ABI has no size argument (abi/ is out of + * scope). The first 8 bytes are therefore the minimum dereference: magic then + * the struct size. Magic is 'BXVM' (0x4D565842). struct_size must equal + * sizeof(BxD3d12VirtualMemoryConfig). Any other pointer, including null, is not + * this struct: the call logs the unimplemented-API stub and returns S_OK. It + * does not read past those 8 bytes and it does not write. + * + * A block whose magic and size match is then checked in full. version is 1. + * flags may be 0 or BX_D3D12_VMEM_FLAG_BACKING_HEAP. Any other flag bit, or a + * non-zero reserved word, is not this struct either (logged S_OK, no write). + * A recognised block with a bad size or a base_va that bx_xmem_query_region + * does not resolve still returns E_INVALIDARG and is not written. + * * base_va is 0, or an address bx_xmem_query_region resolves. It is not a GPU pointer. * size_bytes is 0 or a 64 KiB multiple that does not exceed the active title limit. - * cpu_pointer is an output. It is the persistent Map address of the WRITE_BACK buffer - * that backs the region, or 0 until that heap has been created. The block passed here - * must stay alive until the matching CreateHeap returns, because that is when a 0 - * becomes the map address. There is no separate export for this pointer. - * A null argument, or a block whose version is not 1 or whose flags or reserved - * word is non-zero, is not this struct. That call logs the unimplemented-API stub - * and returns S_OK. It does not store the pointer and does not write cpu_pointer. + * + * The call copies what it needs. The caller's pointer is not kept. cpu_pointer + * is written only before this call returns: the persistent Map address of the + * WRITE_BACK buffer if that backing heap already exists, otherwise 0. CreateHeap + * does not write the block. A caller that needs the address after the backing + * heap has been created calls D3D12ConfigureVirtualMemoryX again with the same + * region (same base_va and size). That second call does not reset or recreate + * the backing heap. It writes the current map into the new block. + * + * CreateHeap returns that backing heap only when all of the following hold: + * the block opted in with BX_D3D12_VMEM_FLAG_BACKING_HEAP, the region size is + * non-zero, and the desc is the heap this file creates for the region: + * Type CUSTOM, CPUPageProperty WRITE_BACK, MemoryPoolPreference L0, + * SizeInBytes equal to the configured region, Alignment 0 or 64 KiB, + * Flags exactly D3D12_HEAP_FLAG_NONE (the flag set used when the backing heap + * is created), and CreationNodeMask and VisibleNodeMask each 0 or 1. + * Any other CreateHeap is the host CreateHeap. The desc is not modified. + * The live-heap xmem budget charge (taken on create, dropped on the wrapper's + * final Release) is the budget difference, and the returned object is the wrapper. + * * The layout must match tests/conformance/test_d3d12_placed/main.cpp. */ +constexpr uint32_t BX_D3D12_VMEM_MAGIC = 0x4D565842u; +constexpr uint32_t BX_D3D12_VMEM_FLAG_BACKING_HEAP = 0x1u; + struct BxD3d12VirtualMemoryConfig { + uint32_t magic; + uint32_t struct_size; uint32_t version; uint32_t flags; uint64_t base_va; @@ -27,11 +58,15 @@ struct BxD3d12VirtualMemoryConfig { uint64_t reserved; uint64_t cpu_pointer; }; -static_assert(sizeof(BxD3d12VirtualMemoryConfig) == 40, "config block is 40 bytes"); -static_assert(offsetof(BxD3d12VirtualMemoryConfig, base_va) == 8, "base_va offset"); -static_assert(offsetof(BxD3d12VirtualMemoryConfig, size_bytes) == 16, "size_bytes offset"); -static_assert(offsetof(BxD3d12VirtualMemoryConfig, reserved) == 24, "reserved offset"); -static_assert(offsetof(BxD3d12VirtualMemoryConfig, cpu_pointer) == 32, "cpu_pointer offset"); +static_assert(sizeof(BxD3d12VirtualMemoryConfig) == 48, "config block is 48 bytes"); +static_assert(offsetof(BxD3d12VirtualMemoryConfig, magic) == 0, "magic offset"); +static_assert(offsetof(BxD3d12VirtualMemoryConfig, struct_size) == 4, "struct_size offset"); +static_assert(offsetof(BxD3d12VirtualMemoryConfig, version) == 8, "version offset"); +static_assert(offsetof(BxD3d12VirtualMemoryConfig, flags) == 12, "flags offset"); +static_assert(offsetof(BxD3d12VirtualMemoryConfig, base_va) == 16, "base_va offset"); +static_assert(offsetof(BxD3d12VirtualMemoryConfig, size_bytes) == 24, "size_bytes offset"); +static_assert(offsetof(BxD3d12VirtualMemoryConfig, reserved) == 32, "reserved offset"); +static_assert(offsetof(BxD3d12VirtualMemoryConfig, cpu_pointer) == 40, "cpu_pointer offset"); extern "C" HRESULT bx_d3d12_configure_virtual_memory(void* config); diff --git a/tests/conformance/test_d3d12_placed/main.cpp b/tests/conformance/test_d3d12_placed/main.cpp index 4e6f7334..187c9942 100644 --- a/tests/conformance/test_d3d12_placed/main.cpp +++ b/tests/conformance/test_d3d12_placed/main.cpp @@ -2,10 +2,10 @@ * M2-C1 (#464): D3D12ConfigureVirtualMemoryX and placed resources. * * The configuration block is BetterXen-defined and must match shims/d3d12_xs/vmem.h. - * cpu_pointer is an output of the config block: the persistent map of the one - * WRITE_BACK / L0 heap that backs the region. The device and that heap are created - * once and kept for the whole run. Acceptance writes this file's pattern through - * that pointer, with no Unmap, and checks a fence-separated GPU copy in both directions. + * The export is PVOID with no size, so the block starts with magic 'BXVM' and the + * struct size. cpu_pointer is written only during that call. After the backing heap + * exists, a second call with the same region reads the persistent map. That map is + * the WRITE_BACK buffer used by the write-through and the fence-separated GPU copy. */ #ifndef WIDL_EXPLICIT_AGGREGATE_RETURNS #define WIDL_EXPLICIT_AGGREGATE_RETURNS @@ -31,6 +31,8 @@ __declspec(dllimport) PVOID WINAPI XMemMapPhysicalPages(PVOID base, SIZE_T count } struct BxD3d12VirtualMemoryConfig { + uint32_t magic; + uint32_t struct_size; uint32_t version; uint32_t flags; uint64_t base_va; @@ -38,14 +40,20 @@ struct BxD3d12VirtualMemoryConfig { uint64_t reserved; uint64_t cpu_pointer; }; -static_assert(sizeof(BxD3d12VirtualMemoryConfig) == 40, "config block is 40 bytes"); -static_assert(offsetof(BxD3d12VirtualMemoryConfig, base_va) == 8, "base_va offset"); -static_assert(offsetof(BxD3d12VirtualMemoryConfig, size_bytes) == 16, "size_bytes offset"); -static_assert(offsetof(BxD3d12VirtualMemoryConfig, reserved) == 24, "reserved offset"); -static_assert(offsetof(BxD3d12VirtualMemoryConfig, cpu_pointer) == 32, "cpu_pointer offset"); +static_assert(sizeof(BxD3d12VirtualMemoryConfig) == 48, "config block is 48 bytes"); +static_assert(offsetof(BxD3d12VirtualMemoryConfig, magic) == 0, "magic offset"); +static_assert(offsetof(BxD3d12VirtualMemoryConfig, struct_size) == 4, "struct_size offset"); +static_assert(offsetof(BxD3d12VirtualMemoryConfig, version) == 8, "version offset"); +static_assert(offsetof(BxD3d12VirtualMemoryConfig, flags) == 12, "flags offset"); +static_assert(offsetof(BxD3d12VirtualMemoryConfig, base_va) == 16, "base_va offset"); +static_assert(offsetof(BxD3d12VirtualMemoryConfig, size_bytes) == 24, "size_bytes offset"); +static_assert(offsetof(BxD3d12VirtualMemoryConfig, reserved) == 32, "reserved offset"); +static_assert(offsetof(BxD3d12VirtualMemoryConfig, cpu_pointer) == 40, "cpu_pointer offset"); namespace { +constexpr uint32_t kMagic = 0x4D565842u; +constexpr uint32_t kFlagBacking = 0x1u; constexpr uint32_t kVersion = 1; constexpr uint64_t kAlign = D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT; constexpr uint32_t kBufBytes = 64; @@ -58,11 +66,14 @@ constexpr uint32_t kFootprint = kTexH * kRowPitch; constexpr uint32_t kUploadBytes = kPlacement + kFootprint; constexpr uint64_t kRegionBytes = kAlign * 2; +static_assert(kMagic == 0x4D565842u, "magic is BXVM"); +static_assert(kFlagBacking == 0x1u, "backing-heap opt-in is bit 0"); static_assert(kAlign == 65536, "placement alignment is 64 KiB"); static_assert(kRowPitch == 256, "texture row pitch is 256 bytes"); static_assert(kPlacement == 512, "texture placement alignment is 512 bytes"); static_assert(kBufBytes <= kRowPitch, "buffer pattern fits in the first texture row"); static_assert(kFootprint <= kAlign, "texture footprint fits in one 64 KiB page"); +static_assert(kRegionBytes == 128ull * 1024ull, "configured region is 128 KiB"); int g_checks = 0; int g_failures = 0; @@ -72,7 +83,7 @@ bool check(bool ok, const char* fmt, ...) { g_checks++; if (!ok) { g_failures++; - char msg[384]; + char msg[512]; va_list ap; va_start(ap, fmt); std::vsnprintf(msg, sizeof(msg), fmt, ap); @@ -174,17 +185,44 @@ uint32_t count_texture(const uint8_t* got) { return match; } -D3D12_HEAP_DESC heap_desc(uint64_t bytes, D3D12_HEAP_FLAGS flags) { - D3D12_HEAP_DESC desc = {}; +BxD3d12VirtualMemoryConfig make_block(uint64_t base, uint64_t size, uint32_t flags) { + BxD3d12VirtualMemoryConfig block{}; + block.magic = kMagic; + block.struct_size = static_cast(sizeof(block)); + block.version = kVersion; + block.flags = flags; + block.base_va = base; + block.size_bytes = size; + return block; +} + +bool inputs_unchanged(const BxD3d12VirtualMemoryConfig& got, const BxD3d12VirtualMemoryConfig& sent) { + return got.magic == sent.magic && got.struct_size == sent.struct_size && got.version == sent.version && + got.flags == sent.flags && got.base_va == sent.base_va && got.size_bytes == sent.size_bytes && + got.reserved == sent.reserved; +} + +D3D12_HEAP_DESC heap_of(D3D12_HEAP_TYPE type, uint64_t bytes, D3D12_HEAP_FLAGS flags) { + D3D12_HEAP_DESC desc{}; desc.SizeInBytes = bytes; - desc.Properties.Type = D3D12_HEAP_TYPE_DEFAULT; - desc.Alignment = kAlign; + desc.Properties.Type = type; desc.Flags = flags; return desc; } +D3D12_HEAP_DESC backing_desc() { + D3D12_HEAP_DESC desc{}; + desc.SizeInBytes = kRegionBytes; + desc.Alignment = 0; + desc.Properties.Type = D3D12_HEAP_TYPE_CUSTOM; + desc.Properties.CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_WRITE_BACK; + desc.Properties.MemoryPoolPreference = D3D12_MEMORY_POOL_L0; + desc.Flags = D3D12_HEAP_FLAG_NONE; + return desc; +} + D3D12_RESOURCE_DESC buffer_desc(uint64_t bytes) { - D3D12_RESOURCE_DESC desc = {}; + D3D12_RESOURCE_DESC desc{}; desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; desc.Width = bytes; desc.Height = 1; @@ -197,7 +235,7 @@ D3D12_RESOURCE_DESC buffer_desc(uint64_t bytes) { } D3D12_RESOURCE_DESC texture_desc() { - D3D12_RESOURCE_DESC desc = {}; + D3D12_RESOURCE_DESC desc{}; desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; desc.Width = kTexW; desc.Height = kTexH; @@ -209,6 +247,37 @@ D3D12_RESOURCE_DESC texture_desc() { return desc; } +bool same_object(IUnknown* a, IUnknown* b) { + if (!a || !b) { + return false; + } + IUnknown* ua = nullptr; + IUnknown* ub = nullptr; + const HRESULT ha = a->QueryInterface(__uuidof(IUnknown), reinterpret_cast(&ua)); + const HRESULT hb = b->QueryInterface(__uuidof(IUnknown), reinterpret_cast(&ub)); + const bool same = ha == S_OK && hb == S_OK && ua && ua == ub; + if (ua) ua->Release(); + if (ub) ub->Release(); + return same; +} + +ID3D12Device* open_host_device() { + using CreateFn = HRESULT(WINAPI*)(IUnknown*, D3D_FEATURE_LEVEL, REFIID, void**); + HMODULE mod = LoadLibraryA("d3d12.dll"); + if (!mod) { + return nullptr; + } + auto create = reinterpret_cast(reinterpret_cast(GetProcAddress(mod, "D3D12CreateDevice"))); + if (!create) { + return nullptr; + } + ID3D12Device* device = nullptr; + if (create(nullptr, D3D_FEATURE_LEVEL_11_0, __uuidof(ID3D12Device), reinterpret_cast(&device)) != S_OK) { + return nullptr; + } + return device; +} + bool wait_fence(ID3D12CommandQueue* queue, ID3D12Fence* fence, UINT64 value) { HRESULT hr = queue->Signal(fence, value); if (hr != S_OK) { @@ -230,6 +299,39 @@ bool wait_fence(ID3D12CommandQueue* queue, ID3D12Fence* fence, UINT64 value) { static_cast(fence->GetCompletedValue())); } +struct StackSync { + uint64_t base; + uint64_t size; + HANDLE ready; + HANDLE done; + HRESULT hr; + int intact; +}; + +DWORD WINAPI stack_config_thread(LPVOID param) { + auto* sync = static_cast(param); + BxD3d12VirtualMemoryConfig block = make_block(sync->base, sync->size, kFlagBacking); + sync->hr = D3D12ConfigureVirtualMemoryX(&block); + volatile uint8_t* raw = reinterpret_cast(&block); + for (size_t i = 0; i < sizeof(block); ++i) { + raw[i] = 0xA5; + } + SetEvent(sync->ready); + WaitForSingleObject(sync->done, INFINITE); + int intact = 1; + for (size_t i = 0; i < sizeof(block); ++i) { + if (raw[i] != 0xA5) { + intact = 0; + } + } + sync->intact = intact; + return 0; +} + +void expect_bytes_unchanged(void* block, const void* before, size_t bytes, const char* what) { + check(std::memcmp(block, before, bytes) == 0, "%s leaves every byte unchanged", what); +} + } // namespace int main() { @@ -243,35 +345,94 @@ int main() { const char* profile = cfg->profile == BX_PROFILE_ANACONDA ? "anaconda" : "lockhart"; check(D3D12ConfigureVirtualMemoryX(nullptr) == S_OK, "null configuration is a logged stub that returns S_OK"); - uint8_t foreign[sizeof(BxD3d12VirtualMemoryConfig)]; - std::memset(foreign, 0, sizeof(foreign)); - const uint32_t foreign_version = 0x12345678u; - std::memcpy(foreign, &foreign_version, sizeof(foreign_version)); - std::memset(foreign + 32, 0xA5, 8); - uint8_t foreign_before[sizeof(foreign)]; - std::memcpy(foreign_before, foreign, sizeof(foreign)); - check(D3D12ConfigureVirtualMemoryX(foreign) == S_OK, "an unrecognised block returns S_OK"); - check(std::memcmp(foreign, foreign_before, sizeof(foreign)) == 0, - "an unrecognised block, including the sentinel at bytes 32..39, is left unchanged"); - BxD3d12VirtualMemoryConfig bad = {2u, 0u, 0u, 0u, 0u, 0u}; - const BxD3d12VirtualMemoryConfig bad_before = bad; + + uint8_t wrong_magic[64]; + std::memset(wrong_magic, 0xA5, sizeof(wrong_magic)); + uint8_t wrong_magic_before[64]; + std::memcpy(wrong_magic_before, wrong_magic, sizeof(wrong_magic)); + check(D3D12ConfigureVirtualMemoryX(wrong_magic) == S_OK, "wrong magic returns S_OK"); + expect_bytes_unchanged(wrong_magic, wrong_magic_before, sizeof(wrong_magic), "wrong magic"); + + uint8_t wrong_size[64]; + std::memset(wrong_size, 0xA5, sizeof(wrong_size)); + const uint32_t magic = kMagic; + const uint32_t short_size = 24; + std::memcpy(wrong_size, &magic, sizeof(magic)); + std::memcpy(wrong_size + 4, &short_size, sizeof(short_size)); + uint8_t wrong_size_before[64]; + std::memcpy(wrong_size_before, wrong_size, sizeof(wrong_size)); + check(D3D12ConfigureVirtualMemoryX(wrong_size) == S_OK, "right magic with the wrong struct size returns S_OK"); + expect_bytes_unchanged(wrong_size, wrong_size_before, sizeof(wrong_size), "wrong struct size"); + + SYSTEM_INFO sys{}; + GetSystemInfo(&sys); + const SIZE_T page_bytes = sys.dwPageSize ? sys.dwPageSize : 4096; + void* edge_mem = VirtualAlloc(nullptr, page_bytes * 2, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE); + check(edge_mem != nullptr, "VirtualAlloc for the 8-byte header probe"); + if (edge_mem) { + DWORD edge_old = 0; + auto* edge_base = static_cast(edge_mem); + check(VirtualProtect(edge_base + page_bytes, page_bytes, PAGE_NOACCESS, &edge_old) != 0, + "page after the header probe is NOACCESS"); + uint8_t* edge = edge_base + page_bytes - 8; + uint32_t bad_magic = 0x11223344u; + uint32_t bad_size = 0x55667788u; + std::memcpy(edge, &bad_magic, 4); + std::memcpy(edge + 4, &bad_size, 4); + HRESULT edge_hr = D3D12ConfigureVirtualMemoryX(edge); + check(edge_hr == S_OK, "wrong magic at a page edge returns S_OK without reading past 8 bytes hr=0x%08lx", + ul(edge_hr)); + uint32_t good_magic = kMagic; + uint32_t eight = 8; + std::memcpy(edge, &good_magic, 4); + std::memcpy(edge + 4, &eight, 4); + edge_hr = D3D12ConfigureVirtualMemoryX(edge); + check(edge_hr == S_OK, "right magic and wrong size at a page edge returns S_OK hr=0x%08lx", ul(edge_hr)); + VirtualProtect(edge_base + page_bytes, page_bytes, PAGE_READWRITE, &edge_old); + VirtualFree(edge_mem, 0, MEM_RELEASE); + } + + BxD3d12VirtualMemoryConfig bad = make_block(0, 0, 0); + bad.version = 2; + bad.cpu_pointer = 0xA5A5A5A5A5A5A5A5ull; + BxD3d12VirtualMemoryConfig bad_before = bad; check(D3D12ConfigureVirtualMemoryX(&bad) == S_OK, "version 2 is an unrecognised block and returns S_OK"); - check(std::memcmp(&bad, &bad_before, sizeof(bad)) == 0, "version 2 block bytes stay unchanged"); - bad = {kVersion, 1u, 0u, 0u, 0u, 0u}; - const BxD3d12VirtualMemoryConfig flags_before = bad; - check(D3D12ConfigureVirtualMemoryX(&bad) == S_OK, "non-zero flags are an unrecognised block and return S_OK"); - check(std::memcmp(&bad, &flags_before, sizeof(bad)) == 0, "non-zero flags block bytes stay unchanged"); - bad = {kVersion, 0u, 0u, 1000u, 0u, 0u}; - check(D3D12ConfigureVirtualMemoryX(&bad) == E_INVALIDARG, "size that is not a multiple of 64 KiB must be rejected"); - bad = {kVersion, 0u, 0u, cfg->title_memory_limit_bytes + kAlign, 0u, 0u}; - check(D3D12ConfigureVirtualMemoryX(&bad) == E_INVALIDARG, "size above the title limit must be rejected"); - bad = {kVersion, 0u, 0u, 0u, 1u, 0u}; - const BxD3d12VirtualMemoryConfig reserved_before = bad; + expect_bytes_unchanged(&bad, &bad_before, sizeof(bad), "version 2"); + + bad = make_block(0, 0, 0x2u); + bad.cpu_pointer = 0xA5A5A5A5A5A5A5A5ull; + bad_before = bad; + check(D3D12ConfigureVirtualMemoryX(&bad) == S_OK, "unknown flag bit 0x2 is an unrecognised block and returns S_OK"); + expect_bytes_unchanged(&bad, &bad_before, sizeof(bad), "unknown flag bit"); + + bad = make_block(0, 0, 0); + bad.reserved = 1; + bad.cpu_pointer = 0xA5A5A5A5A5A5A5A5ull; + bad_before = bad; check(D3D12ConfigureVirtualMemoryX(&bad) == S_OK, "a non-zero reserved word is an unrecognised block and returns S_OK"); - check(std::memcmp(&bad, &reserved_before, sizeof(bad)) == 0, "non-zero reserved block bytes stay unchanged"); - bad = {kVersion, 0u, 0x1000u, kAlign, 0u, 0u}; + expect_bytes_unchanged(&bad, &bad_before, sizeof(bad), "non-zero reserved"); + + bad = make_block(0, 1000, 0); + bad.cpu_pointer = 0xA5A5A5A5A5A5A5A5ull; + bad_before = bad; + check(D3D12ConfigureVirtualMemoryX(&bad) == E_INVALIDARG, "size that is not a multiple of 64 KiB must be rejected"); + expect_bytes_unchanged(&bad, &bad_before, sizeof(bad), "rejected size"); + + bad = make_block(0, cfg->title_memory_limit_bytes + kAlign, 0); + bad.cpu_pointer = 0xA5A5A5A5A5A5A5A5ull; + bad_before = bad; + check(D3D12ConfigureVirtualMemoryX(&bad) == E_INVALIDARG, "size above the title limit must be rejected"); + expect_bytes_unchanged(&bad, &bad_before, sizeof(bad), "rejected title limit"); + + bad = make_block(0x1000, kAlign, 0); check(D3D12ConfigureVirtualMemoryX(&bad) == E_INVALIDARG, "a VA that is not an xmem region must be rejected"); + BxD3d12VirtualMemoryConfig opt_only = make_block(0, 0, kFlagBacking); + const BxD3d12VirtualMemoryConfig opt_sent = opt_only; + check(D3D12ConfigureVirtualMemoryX(&opt_only) == S_OK, "BACKING_HEAP alone is a recognised block"); + check(inputs_unchanged(opt_only, opt_sent), "BACKING_HEAP input fields stay unchanged"); + check(opt_only.cpu_pointer == 0, "BACKING_HEAP with no heap yet writes cpu_pointer 0"); + SIZE_T page_count = 2; ULONG_PTR pages[2] = {}; uint8_t* view = nullptr; @@ -285,70 +446,414 @@ int main() { } } check(mapped, "xmem must map two contiguous 64 KiB pages"); - - BxD3d12VirtualMemoryConfig config = {}; - config.version = kVersion; - config.base_va = reinterpret_cast(view); - config.size_bytes = kRegionBytes; - const BxD3d12VirtualMemoryConfig sent = config; - HRESULT hr = mapped ? D3D12ConfigureVirtualMemoryX(&config) : E_FAIL; - check(hr == S_OK, "D3D12ConfigureVirtualMemoryX(valid) hr=0x%08lx", ul(hr)); - check(config.version == sent.version && config.flags == sent.flags && config.base_va == sent.base_va && - config.size_bytes == sent.size_bytes && config.reserved == sent.reserved, - "configuration input fields must be left unchanged"); - check(config.cpu_pointer == 0, "cpu_pointer stays 0 until the backing heap exists"); + const uint64_t region_base = reinterpret_cast(view); ID3D12Device* device = nullptr; - hr = D3D12XboxCreateDevice(nullptr, __uuidof(ID3D12Device), reinterpret_cast(&device)); + HRESULT hr = D3D12XboxCreateDevice(nullptr, __uuidof(ID3D12Device), reinterpret_cast(&device)); if (!check(hr == S_OK && device, "D3D12XboxCreateDevice hr=0x%08lx", ul(hr))) { - std::fprintf(stderr, "FAIL: test_d3d12_placed (no device; %d of %d checks failed)\n", g_failures, g_checks); + std::fprintf(stderr, "FAIL: test_d3d12_placed (no device. %d of %d checks failed)\n", g_failures, g_checks); return 1; } + ID3D12Device* host = open_host_device(); + check(host != nullptr, "host d3d12.dll device opened for ordinary-heap comparison"); - ID3D12Heap* rejected = nullptr; - D3D12_HEAP_DESC bad_align = heap_desc(kAlign, D3D12_HEAP_FLAG_NONE); - bad_align.Alignment = 4096; - hr = device->CreateHeap(&bad_align, __uuidof(ID3D12Heap), reinterpret_cast(&rejected)); - check(hr == E_INVALIDARG && rejected == nullptr, "heap alignment 4096 must be rejected without a heap hr=0x%08lx", - ul(hr)); + BxD3d12VirtualMemoryConfig plain_region = make_block(region_base, kRegionBytes, 0); + hr = mapped ? D3D12ConfigureVirtualMemoryX(&plain_region) : E_FAIL; + check(hr == S_OK, "region without the opt-in flag hr=0x%08lx", ul(hr)); + check(plain_region.cpu_pointer == 0, "cpu_pointer stays 0 until the backing heap exists"); - ID3D12Heap* heap = nullptr; - D3D12_HEAP_DESC region_desc = heap_desc(kRegionBytes, D3D12_HEAP_FLAG_NONE); - hr = device->CreateHeap(®ion_desc, __uuidof(ID3D12Heap), reinterpret_cast(&heap)); - check(hr == S_OK && heap, "configured-region heap hr=0x%08lx", ul(hr)); - if (heap) { - D3D12_HEAP_DESC got = heap->GetDesc(); + D3D12_HEAP_DESC custom_desc = backing_desc(); + ID3D12Heap* custom_a = nullptr; + ID3D12Heap* custom_b = nullptr; + hr = device->CreateHeap(&custom_desc, __uuidof(ID3D12Heap), reinterpret_cast(&custom_a)); + HRESULT hr_b = device->CreateHeap(&custom_desc, __uuidof(ID3D12Heap), reinterpret_cast(&custom_b)); + check(hr == S_OK && hr_b == S_OK && custom_a && custom_b, "CUSTOM heaps without the opt-in hr=0x%08lx/0x%08lx", + ul(hr), ul(hr_b)); + check(!same_object(custom_a, custom_b), "without the opt-in, two CUSTOM WRITE_BACK L0 heaps are distinct"); + if (custom_a && custom_b) { + D3D12_HEAP_DESC got_a = custom_a->GetDesc(); + D3D12_HEAP_DESC got_b = custom_b->GetDesc(); + check(got_a.Properties.Type == D3D12_HEAP_TYPE_CUSTOM && got_b.Properties.Type == D3D12_HEAP_TYPE_CUSTOM, + "opt-in-off CUSTOM heaps keep type CUSTOM"); + check(got_a.Properties.CPUPageProperty == D3D12_CPU_PAGE_PROPERTY_WRITE_BACK && + got_b.Properties.CPUPageProperty == D3D12_CPU_PAGE_PROPERTY_WRITE_BACK, + "opt-in-off CUSTOM heaps keep WRITE_BACK"); + } + + StackSync sync{}; + sync.base = region_base; + sync.size = kRegionBytes; + sync.hr = E_FAIL; + sync.intact = 0; + sync.ready = CreateEventA(nullptr, FALSE, FALSE, nullptr); + sync.done = CreateEventA(nullptr, FALSE, FALSE, nullptr); + HANDLE stack_thread = nullptr; + if (mapped && sync.ready && sync.done) { + stack_thread = CreateThread(nullptr, 0, stack_config_thread, &sync, 0, nullptr); + } + check(stack_thread != nullptr, "stack config thread started"); + if (stack_thread) { + const DWORD ready = WaitForSingleObject(sync.ready, 10000); + check(ready == WAIT_OBJECT_0 && sync.hr == S_OK, "stack block configure returned S_OK before CreateHeap (wait=%lu hr=0x%08lx)", + ready, ul(sync.hr)); + } + + void* dead_page = VirtualAlloc(nullptr, 4096, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE); + check(dead_page != nullptr, "VirtualAlloc for the config lifetime page"); + if (dead_page && mapped) { + auto* dead_block = static_cast(dead_page); + *dead_block = make_block(region_base, kRegionBytes, kFlagBacking); + hr = D3D12ConfigureVirtualMemoryX(dead_block); + check(hr == S_OK, "page config before it is made inaccessible hr=0x%08lx", ul(hr)); + DWORD dead_old = 0; + check(VirtualProtect(dead_page, 4096, PAGE_NOACCESS, &dead_old) != 0, + "config page is PAGE_NOACCESS before CreateHeap"); + } + + BxD3d12VirtualMemoryConfig live = make_block(region_base, kRegionBytes, kFlagBacking); + const BxD3d12VirtualMemoryConfig live_sent = live; + hr = mapped ? D3D12ConfigureVirtualMemoryX(&live) : E_FAIL; + check(hr == S_OK, "live configure before the backing heap hr=0x%08lx", ul(hr)); + check(inputs_unchanged(live, live_sent), "live configure leaves input fields unchanged"); + check(live.cpu_pointer == 0, "live cpu_pointer is 0 before the backing heap exists"); + + ID3D12Heap* backing = nullptr; + hr = device->CreateHeap(&custom_desc, __uuidof(ID3D12Heap), reinterpret_cast(&backing)); + check(hr == S_OK && backing, "explicit backing CreateHeap hr=0x%08lx", ul(hr)); + if (backing) { + D3D12_HEAP_DESC got = backing->GetDesc(); check(got.Properties.Type == D3D12_HEAP_TYPE_CUSTOM, "backing heap type is CUSTOM"); check(got.Properties.CPUPageProperty == D3D12_CPU_PAGE_PROPERTY_WRITE_BACK, "backing heap is WRITE_BACK"); check(got.Properties.MemoryPoolPreference == D3D12_MEMORY_POOL_L0, "backing heap is L0"); + check(got.Flags == D3D12_HEAP_FLAG_NONE, "backing heap flags are NONE"); check(got.SizeInBytes == kRegionBytes && (got.Alignment == 0 || got.Alignment == kAlign), "backing heap is the 128 KiB region on a 64 KiB alignment"); } - check(config.cpu_pointer != 0, "cpu_pointer is the persistent map of the backing heap"); + check(!same_object(custom_a, backing) && !same_object(custom_b, backing), + "CUSTOM heaps created without the opt-in are not the backing heap"); + + live.cpu_pointer = 0; + hr = D3D12ConfigureVirtualMemoryX(&live); + check(hr == S_OK && live.cpu_pointer != 0, "second configure writes the non-zero map hr=0x%08lx ptr=0x%llx", ul(hr), + static_cast(live.cpu_pointer)); + const uint64_t map_pointer = live.cpu_pointer; + live.cpu_pointer = 0; + hr = D3D12ConfigureVirtualMemoryX(&live); + check(hr == S_OK && live.cpu_pointer == map_pointer, "another configure of the same region writes the same map"); + + ID3D12Heap* again = nullptr; + hr = device->CreateHeap(&custom_desc, __uuidof(ID3D12Heap), reinterpret_cast(&again)); + check(hr == S_OK && same_object(again, backing), "a later explicit request returns the same backing heap"); + if (again) again->Release(); + + D3D12_HEAP_DESC upload_region = heap_of(D3D12_HEAP_TYPE_UPLOAD, kRegionBytes, D3D12_HEAP_FLAG_NONE); + D3D12_HEAP_DESC deny_region = heap_of(D3D12_HEAP_TYPE_DEFAULT, kRegionBytes, D3D12_HEAP_FLAG_DENY_BUFFERS); + ID3D12Heap* upload_same = nullptr; + ID3D12Heap* deny_same = nullptr; + ID3D12Heap* upload_host = nullptr; + ID3D12Heap* deny_host = nullptr; + HRESULT upload_hr = device->CreateHeap(&upload_region, __uuidof(ID3D12Heap), reinterpret_cast(&upload_same)); + HRESULT deny_hr = device->CreateHeap(&deny_region, __uuidof(ID3D12Heap), reinterpret_cast(&deny_same)); + HRESULT upload_host_hr = host ? host->CreateHeap(&upload_region, __uuidof(ID3D12Heap), reinterpret_cast(&upload_host)) + : E_FAIL; + HRESULT deny_host_hr = host ? host->CreateHeap(&deny_region, __uuidof(ID3D12Heap), reinterpret_cast(&deny_host)) + : E_FAIL; + check(upload_hr == S_OK && upload_same, "128 KiB UPLOAD heap hr=0x%08lx", ul(upload_hr)); + check(deny_hr == S_OK && deny_same, "128 KiB DEFAULT|DENY_BUFFERS heap hr=0x%08lx", ul(deny_hr)); + check(upload_hr == upload_host_hr && deny_hr == deny_host_hr, + "same-size ordinary heaps match the host (upload 0x%08lx/0x%08lx deny 0x%08lx/0x%08lx)", ul(upload_hr), + ul(upload_host_hr), ul(deny_hr), ul(deny_host_hr)); + check(!same_object(upload_same, backing) && !same_object(deny_same, backing) && !same_object(upload_same, deny_same), + "UPLOAD and DEFAULT|DENY_BUFFERS heaps are distinct from the backing heap and from each other"); + if (upload_same && upload_host && deny_same && deny_host) { + D3D12_HEAP_DESC up = upload_same->GetDesc(); + D3D12_HEAP_DESC up_h = upload_host->GetDesc(); + D3D12_HEAP_DESC deny = deny_same->GetDesc(); + D3D12_HEAP_DESC deny_h = deny_host->GetDesc(); + check(up.Properties.Type == D3D12_HEAP_TYPE_UPLOAD && up.Properties.Type == up_h.Properties.Type, + "128 KiB UPLOAD GetDesc type stays UPLOAD"); + check(deny.Properties.Type == D3D12_HEAP_TYPE_DEFAULT && deny.Properties.Type == deny_h.Properties.Type, + "128 KiB DEFAULT GetDesc type stays DEFAULT"); + check(up.Flags == up_h.Flags && deny.Flags == deny_h.Flags, "ordinary heap flags match the host heap"); + check(up.Properties.Type != D3D12_HEAP_TYPE_CUSTOM && deny.Properties.Type != D3D12_HEAP_TYPE_CUSTOM, + "ordinary heaps do not report CUSTOM"); + } + + D3D12_HEAP_DESC upload_odd = heap_of(D3D12_HEAP_TYPE_UPLOAD, 100000, D3D12_HEAP_FLAG_NONE); + ID3D12Heap* odd = nullptr; + ID3D12Heap* odd_host = nullptr; + HRESULT odd_hr = device->CreateHeap(&upload_odd, __uuidof(ID3D12Heap), reinterpret_cast(&odd)); + HRESULT odd_host_hr = host ? host->CreateHeap(&upload_odd, __uuidof(ID3D12Heap), reinterpret_cast(&odd_host)) + : E_FAIL; + uint64_t odd_size = 0; + uint64_t odd_host_size = 0; + check(odd_hr == S_OK && odd, "100000-byte UPLOAD heap hr=0x%08lx", ul(odd_hr)); + check(odd_hr == odd_host_hr, "100000-byte UPLOAD HRESULT matches the host (hooked=0x%08lx host=0x%08lx)", ul(odd_hr), + ul(odd_host_hr)); + if (odd && odd_host) { + D3D12_HEAP_DESC og = odd->GetDesc(); + D3D12_HEAP_DESC oh = odd_host->GetDesc(); + odd_size = og.SizeInBytes; + odd_host_size = oh.SizeInBytes; + check(og.SizeInBytes == oh.SizeInBytes && og.Properties.Type == D3D12_HEAP_TYPE_UPLOAD && + og.Properties.Type == oh.Properties.Type && og.Flags == oh.Flags, + "100000-byte UPLOAD GetDesc matches the host (size %llu type %d flags 0x%x)", + static_cast(og.SizeInBytes), static_cast(og.Properties.Type), + static_cast(og.Flags)); + } + std::printf("upload_100000 hooked=0x%08lx host=0x%08lx size=%llu host_size=%llu\n", ul(odd_hr), ul(odd_host_hr), + static_cast(odd_size), static_cast(odd_host_size)); + std::fflush(stdout); + + D3D12_HEAP_DESC align_probe = heap_of(D3D12_HEAP_TYPE_DEFAULT, kAlign, D3D12_HEAP_FLAG_NONE); + align_probe.Alignment = 4096; + ID3D12Heap* align_hook = nullptr; + ID3D12Heap* align_host = nullptr; + HRESULT align_hr = device->CreateHeap(&align_probe, __uuidof(ID3D12Heap), reinterpret_cast(&align_hook)); + HRESULT align_host_hr = + host ? host->CreateHeap(&align_probe, __uuidof(ID3D12Heap), reinterpret_cast(&align_host)) : E_FAIL; + check(align_hr == align_host_hr, "alignment 4096 CreateHeap matches the host (hooked=0x%08lx host=0x%08lx)", + ul(align_hr), ul(align_host_hr)); + if (FAILED(align_hr)) { + check(align_hook == nullptr, "failed alignment-4096 CreateHeap does not return a heap"); + } + + if (stack_thread && sync.done) { + SetEvent(sync.done); + const DWORD joined = WaitForSingleObject(stack_thread, 10000); + check(joined == WAIT_OBJECT_0 && sync.intact == 1, + "stack config block was not written after the call returned (wait=%lu intact=%d)", joined, sync.intact); + CloseHandle(stack_thread); + stack_thread = nullptr; + } + if (dead_page) { + DWORD dead_old = 0; + VirtualProtect(dead_page, 4096, PAGE_READWRITE, &dead_old); + VirtualFree(dead_page, 0, MEM_RELEASE); + dead_page = nullptr; + std::printf("config_page_noaccess_survived=1\n"); + std::fflush(stdout); + } + + BxD3d12VirtualMemoryConfig opted_out = make_block(region_base, kRegionBytes, 0); + hr = D3D12ConfigureVirtualMemoryX(&opted_out); + check(hr == S_OK && opted_out.cpu_pointer == map_pointer, + "same region without the flag keeps the backing heap and writes the same map hr=0x%08lx", ul(hr)); + ID3D12Heap* custom_later = nullptr; + hr = device->CreateHeap(&custom_desc, __uuidof(ID3D12Heap), reinterpret_cast(&custom_later)); + check(hr == S_OK && custom_later && !same_object(custom_later, backing), + "CUSTOM WRITE_BACK L0 without the opt-in is a separate ordinary heap hr=0x%08lx", ul(hr)); + if (custom_later) { + D3D12_HEAP_DESC later = custom_later->GetDesc(); + check(later.Properties.Type == D3D12_HEAP_TYPE_CUSTOM && + later.Properties.CPUPageProperty == D3D12_CPU_PAGE_PROPERTY_WRITE_BACK && + later.Properties.MemoryPoolPreference == D3D12_MEMORY_POOL_L0, + "opt-in-off heap keeps the CUSTOM WRITE_BACK L0 desc it requested"); + } + + live.flags = kFlagBacking; + live.cpu_pointer = 0; + hr = D3D12ConfigureVirtualMemoryX(&live); + check(hr == S_OK && live.cpu_pointer == map_pointer, "restoring the opt-in does not recreate the backing heap"); + + uint64_t small_align = 0; + uint64_t small_bytes = 0; + HRESULT small_hr = E_FAIL; + HRESULT small_host_hr = E_FAIL; + ID3D12Resource* small_res = nullptr; + ID3D12Resource* small_host_res = nullptr; + ID3D12Heap* small_heap = nullptr; + ID3D12Heap* small_host_heap = nullptr; + { + struct Candidate { + const char* name; + UINT width; + UINT height; + DXGI_FORMAT format; + }; + const Candidate candidates[] = { + {"rgba8_1x1", 1, 1, DXGI_FORMAT_R8G8B8A8_UNORM}, {"rgba8_4x4", 4, 4, DXGI_FORMAT_R8G8B8A8_UNORM}, + {"rgba8_8x8", 8, 8, DXGI_FORMAT_R8G8B8A8_UNORM}, {"r8_8x8", 8, 8, DXGI_FORMAT_R8_UNORM}, + {"r8_16x16", 16, 16, DXGI_FORMAT_R8_UNORM}, {"rgba8_16x16", 16, 16, DXGI_FORMAT_R8G8B8A8_UNORM}, + }; + ID3D12Device* probe = host ? host : device; + D3D12_RESOURCE_DESC chosen{}; + bool have_chosen = false; + bool chose_4k = false; + for (const Candidate& candidate : candidates) { + D3D12_RESOURCE_DESC desc = texture_desc(); + desc.Width = candidate.width; + desc.Height = candidate.height; + desc.Format = candidate.format; + desc.Alignment = D3D12_SMALL_RESOURCE_PLACEMENT_ALIGNMENT; + D3D12_RESOURCE_ALLOCATION_INFO info = probe->GetResourceAllocationInfo(0, 1, &desc); + std::printf("small_resource %s alloc_align=%llu alloc_bytes=%llu desc_align=%llu\n", candidate.name, + static_cast(info.Alignment), static_cast(info.SizeInBytes), + static_cast(desc.Alignment)); + const bool usable = info.Alignment != 0 && info.Alignment != ~0ull && info.SizeInBytes != 0 && + info.SizeInBytes != ~0ull && info.Alignment < kAlign; + if (!usable) { + continue; + } + if (info.Alignment == D3D12_SMALL_RESOURCE_PLACEMENT_ALIGNMENT) { + chosen = desc; + small_align = info.Alignment; + small_bytes = info.SizeInBytes; + have_chosen = true; + chose_4k = true; + } else if (!chose_4k && (!have_chosen || info.Alignment < small_align)) { + chosen = desc; + small_align = info.Alignment; + small_bytes = info.SizeInBytes; + have_chosen = true; + } + } + std::fflush(stdout); + const uint64_t place_at = have_chosen ? small_align : 4096ull; + D3D12_RESOURCE_DESC placed_desc = have_chosen ? chosen : texture_desc(); + if (!have_chosen) { + placed_desc.Alignment = D3D12_SMALL_RESOURCE_PLACEMENT_ALIGNMENT; + D3D12_RESOURCE_ALLOCATION_INFO info = probe->GetResourceAllocationInfo(0, 1, &placed_desc); + small_align = info.Alignment; + small_bytes = info.SizeInBytes; + std::printf("small_placement: no alignment below 64 KiB. Comparing offset 4096 with the host " + "(reported align=%llu bytes=%llu)\n", + static_cast(info.Alignment), static_cast(info.SizeInBytes)); + } + const uint64_t need = place_at + (small_bytes == 0 || small_bytes == ~0ull ? kAlign : small_bytes); + uint64_t heap_bytes = (need + (kAlign - 1)) & ~(kAlign - 1); + if (heap_bytes < kAlign) { + heap_bytes = kAlign; + } + D3D12_HEAP_DESC small_heap_desc = heap_of(D3D12_HEAP_TYPE_DEFAULT, heap_bytes, D3D12_HEAP_FLAG_NONE); + hr = device->CreateHeap(&small_heap_desc, __uuidof(ID3D12Heap), reinterpret_cast(&small_heap)); + HRESULT host_heap_hr = + host ? host->CreateHeap(&small_heap_desc, __uuidof(ID3D12Heap), reinterpret_cast(&small_host_heap)) + : E_FAIL; + check(hr == host_heap_hr && (FAILED(hr) || small_heap), + "ordinary heap for small placement matches the host (hooked=0x%08lx host=0x%08lx bytes=%llu)", ul(hr), + ul(host_heap_hr), static_cast(heap_bytes)); + if (small_heap) { + small_hr = device->CreatePlacedResource(small_heap, place_at, &placed_desc, D3D12_RESOURCE_STATE_COPY_DEST, + nullptr, __uuidof(ID3D12Resource), reinterpret_cast(&small_res)); + } + if (small_host_heap) { + small_host_hr = host->CreatePlacedResource(small_host_heap, place_at, &placed_desc, D3D12_RESOURCE_STATE_COPY_DEST, + nullptr, __uuidof(ID3D12Resource), + reinterpret_cast(&small_host_res)); + } + std::printf("small_placement align=%llu offset=%llu bytes=%llu hooked=0x%08lx host=0x%08lx chose_4k=%d\n", + static_cast(small_align), static_cast(place_at), + static_cast(small_bytes), ul(small_hr), ul(small_host_hr), chose_4k ? 1 : 0); + std::fflush(stdout); + check(small_hr == small_host_hr, "ordinary small-resource placement matches the host (hooked=0x%08lx host=0x%08lx)", + ul(small_hr), ul(small_host_hr)); + if (have_chosen) { + check(small_hr == S_OK && small_res, "small resource placed at runtime alignment %llu hr=0x%08lx", + static_cast(place_at), ul(small_hr)); + } + } + + HRESULT heap1_hr = E_FAIL; + HRESULT heap1_host_hr = E_FAIL; + ID3D12Heap* heap1_base = nullptr; + ID3D12Heap* heap1_host_base = nullptr; + ID3D12Heap1* heap1 = nullptr; + ID3D12Heap1* heap1_host = nullptr; + { + D3D12_HEAP_DESC plain = heap_of(D3D12_HEAP_TYPE_DEFAULT, kAlign, D3D12_HEAP_FLAG_NONE); + hr = device->CreateHeap(&plain, __uuidof(ID3D12Heap), reinterpret_cast(&heap1_base)); + HRESULT host_base_hr = + host ? host->CreateHeap(&plain, __uuidof(ID3D12Heap), reinterpret_cast(&heap1_host_base)) : E_FAIL; + check(hr == S_OK && heap1_base, "heap used for ID3D12Heap1 hr=0x%08lx", ul(hr)); + heap1_hr = heap1_base ? heap1_base->QueryInterface(__uuidof(ID3D12Heap1), reinterpret_cast(&heap1)) + : E_FAIL; + heap1_host_hr = heap1_host_base + ? heap1_host_base->QueryInterface(__uuidof(ID3D12Heap1), reinterpret_cast(&heap1_host)) + : E_FAIL; + std::printf("ID3D12Heap1 hooked=0x%08lx host=0x%08lx base_host=0x%08lx\n", ul(heap1_hr), ul(heap1_host_hr), + ul(host_base_hr)); + std::fflush(stdout); + check(heap1_hr == heap1_host_hr, "ID3D12Heap1 QueryInterface matches the host (hooked=0x%08lx host=0x%08lx)", + ul(heap1_hr), ul(heap1_host_hr)); + if (heap1_host_hr == S_OK) { + check(heap1_hr == S_OK && heap1, "hooked CreateHeap heap answers ID3D12Heap1"); + IUnknown* session = nullptr; + IUnknown* session_host = nullptr; + const HRESULT session_hr = + heap1->GetProtectedResourceSession(__uuidof(IUnknown), reinterpret_cast(&session)); + const HRESULT session_host_hr = + heap1_host->GetProtectedResourceSession(__uuidof(IUnknown), reinterpret_cast(&session_host)); + std::printf("GetProtectedResourceSession hooked=0x%08lx host=0x%08lx\n", ul(session_hr), ul(session_host_hr)); + check(session_hr == session_host_hr, "GetProtectedResourceSession matches the host (hooked=0x%08lx host=0x%08lx)", + ul(session_hr), ul(session_host_hr)); + if (session) session->Release(); + if (session_host) session_host->Release(); + ID3D12Heap1* created = nullptr; + ID3D12Heap1* created_host = nullptr; + const HRESULT created_hr = + device->CreateHeap(&plain, __uuidof(ID3D12Heap1), reinterpret_cast(&created)); + const HRESULT created_host_hr = + host->CreateHeap(&plain, __uuidof(ID3D12Heap1), reinterpret_cast(&created_host)); + std::printf("CreateHeap ID3D12Heap1 hooked=0x%08lx host=0x%08lx\n", ul(created_hr), ul(created_host_hr)); + check(created_hr == S_OK && created && created_hr == created_host_hr, + "CreateHeap riid ID3D12Heap1 returns a heap (hooked=0x%08lx host=0x%08lx)", ul(created_hr), + ul(created_host_hr)); + if (created) created->Release(); + if (created_host) created_host->Release(); + } else { + std::printf("ID3D12Heap1: host cannot answer it (hr=0x%08lx). Hooked result matches.\n", ul(heap1_host_hr)); + ID3D12Heap1* created = nullptr; + ID3D12Heap1* created_host = nullptr; + const HRESULT created_hr = + device->CreateHeap(&plain, __uuidof(ID3D12Heap1), reinterpret_cast(&created)); + const HRESULT created_host_hr = + host ? host->CreateHeap(&plain, __uuidof(ID3D12Heap1), reinterpret_cast(&created_host)) : E_FAIL; + std::printf("CreateHeap ID3D12Heap1 hooked=0x%08lx host=0x%08lx\n", ul(created_hr), ul(created_host_hr)); + std::fflush(stdout); + check(created_hr == created_host_hr, + "CreateHeap riid ID3D12Heap1 matches the host (hooked=0x%08lx host=0x%08lx)", ul(created_hr), + ul(created_host_hr)); + if (created) created->Release(); + if (created_host) created_host->Release(); + } + } ID3D12Resource* placed_buf = nullptr; ID3D12Resource* placed_tex = nullptr; - if (heap) { + if (backing) { D3D12_RESOURCE_DESC tiny = buffer_desc(kBufBytes); - ID3D12Resource* misaligned = nullptr; - hr = device->CreatePlacedResource(heap, 4096, &tiny, D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, - __uuidof(ID3D12Resource), reinterpret_cast(&misaligned)); - check(hr == E_INVALIDARG && misaligned == nullptr, "placed offset 4096 must be rejected hr=0x%08lx", ul(hr)); - if (misaligned) misaligned->Release(); + D3D12_RESOURCE_ALLOCATION_INFO tiny_info = device->GetResourceAllocationInfo(0, 1, &tiny); + std::printf("backing_buffer_alloc align=%llu bytes=%llu\n", static_cast(tiny_info.Alignment), + static_cast(tiny_info.SizeInBytes)); + std::fflush(stdout); + if (tiny_info.Alignment != 0 && tiny_info.SizeInBytes != 0 && tiny_info.SizeInBytes != ~0ull && + (4096ull % tiny_info.Alignment) != 0) { + ID3D12Resource* misaligned = nullptr; + hr = device->CreatePlacedResource(backing, 4096, &tiny, D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, + __uuidof(ID3D12Resource), reinterpret_cast(&misaligned)); + check(hr == E_INVALIDARG && misaligned == nullptr, + "backing heap rejects offset 4096 because allocation alignment is %llu hr=0x%08lx", + static_cast(tiny_info.Alignment), ul(hr)); + if (misaligned) misaligned->Release(); + } else { + check(false, "backing buffer alignment %llu does not make offset 4096 a real rejection", + static_cast(tiny_info.Alignment)); + } D3D12_RESOURCE_DESC buf_desc = buffer_desc(kUploadBytes); - hr = device->CreatePlacedResource(heap, 0, &buf_desc, D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, + hr = device->CreatePlacedResource(backing, 0, &buf_desc, D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, __uuidof(ID3D12Resource), reinterpret_cast(&placed_buf)); check(hr == S_OK && placed_buf, "placed buffer at offset 0 hr=0x%08lx", ul(hr)); D3D12_RESOURCE_DESC tex_desc = texture_desc(); - hr = device->CreatePlacedResource(heap, kAlign, &tex_desc, D3D12_RESOURCE_STATE_COPY_DEST, nullptr, + hr = device->CreatePlacedResource(backing, kAlign, &tex_desc, D3D12_RESOURCE_STATE_COPY_DEST, nullptr, __uuidof(ID3D12Resource), reinterpret_cast(&placed_tex)); check(hr == S_OK && placed_tex, "placed RGBA8 texture at offset 64 KiB hr=0x%08lx", ul(hr)); } ID3D12Resource* readback = nullptr; - D3D12_HEAP_PROPERTIES readback_props = {}; + D3D12_HEAP_PROPERTIES readback_props{}; readback_props.Type = D3D12_HEAP_TYPE_READBACK; D3D12_RESOURCE_DESC staging_desc = buffer_desc(kUploadBytes); if (placed_buf && placed_tex) { @@ -365,9 +870,8 @@ int main() { int flush_ok = 0; const char* texture_path = "not_run"; HRESULT texture_hr = E_FAIL; - const UINT64 cpu_va = reinterpret_cast(view); - uint8_t* cpu = config.cpu_pointer != 0 ? reinterpret_cast(static_cast(config.cpu_pointer)) - : nullptr; + const UINT64 cpu_va = region_base; + uint8_t* cpu = map_pointer != 0 ? reinterpret_cast(static_cast(map_pointer)) : nullptr; if (readback && placed_buf && placed_tex && cpu) { std::memset(cpu, 0, kUploadBytes); write_buffer_pattern(cpu); @@ -379,7 +883,7 @@ int main() { std::printf("texture_path=%s hr=0x%08lx\n", texture_path, ul(texture_hr)); std::fflush(stdout); - D3D12_COMMAND_QUEUE_DESC queue_desc = {}; + D3D12_COMMAND_QUEUE_DESC queue_desc{}; queue_desc.Type = D3D12_COMMAND_LIST_TYPE_DIRECT; ID3D12CommandQueue* queue = nullptr; ID3D12CommandAllocator* allocator = nullptr; @@ -400,7 +904,7 @@ int main() { ID3D12Resource* upload = nullptr; if (list && queue && fence) { - D3D12_TEXTURE_COPY_LOCATION src = {}; + D3D12_TEXTURE_COPY_LOCATION src{}; src.pResource = placed_buf; src.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT; src.PlacedFootprint.Offset = kPlacement; @@ -410,14 +914,14 @@ int main() { src.PlacedFootprint.Footprint.Depth = 1; src.PlacedFootprint.Footprint.RowPitch = kRowPitch; if (texture_hr != S_OK) { - D3D12_TEXTURE_COPY_LOCATION dst = {}; + D3D12_TEXTURE_COPY_LOCATION dst{}; dst.pResource = placed_tex; dst.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX; list->CopyTextureRegion(&dst, 0, 0, 0, &src, nullptr); } list->CopyBufferRegion(readback, 0, placed_buf, 0, kBufBytes); - D3D12_RESOURCE_BARRIER to_src = {}; + D3D12_RESOURCE_BARRIER to_src{}; to_src.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; to_src.Transition.pResource = placed_tex; to_src.Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES; @@ -425,10 +929,10 @@ int main() { to_src.Transition.StateAfter = D3D12_RESOURCE_STATE_COPY_SOURCE; list->ResourceBarrier(1, &to_src); - D3D12_TEXTURE_COPY_LOCATION back_src = {}; + D3D12_TEXTURE_COPY_LOCATION back_src{}; back_src.pResource = placed_tex; back_src.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX; - D3D12_TEXTURE_COPY_LOCATION back_dst = {}; + D3D12_TEXTURE_COPY_LOCATION back_dst{}; back_dst.pResource = readback; back_dst.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT; back_dst.PlacedFootprint = src.PlacedFootprint; @@ -440,7 +944,7 @@ int main() { queue->ExecuteCommandLists(1, lists); check(wait_fence(queue, fence, 1), "GPU queue must retire the placed-resource copy"); - D3D12_HEAP_PROPERTIES upload_props = {}; + D3D12_HEAP_PROPERTIES upload_props{}; upload_props.Type = D3D12_HEAP_TYPE_UPLOAD; D3D12_RESOURCE_DESC upload_desc = buffer_desc(kBufBytes); hr = device->CreateCommittedResource(&upload_props, D3D12_HEAP_FLAG_NONE, &upload_desc, @@ -453,7 +957,7 @@ int main() { upload->Unmap(0, nullptr); } if (upload && allocator->Reset() == S_OK && list->Reset(allocator, nullptr) == S_OK) { - D3D12_RESOURCE_BARRIER to_dest = {}; + D3D12_RESOURCE_BARRIER to_dest{}; to_dest.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; to_dest.Transition.pResource = placed_buf; to_dest.Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES; @@ -503,10 +1007,12 @@ int main() { char log_path[MAX_PATH]; DWORD log_len = GetEnvironmentVariableA("BX_LOG_FILE", log_path, sizeof(log_path)); const bool have_log = log_len > 0 && log_len < sizeof(log_path); - std::printf("RESULT: cpu_va=0x%llx buffer_gpu_va=0x%llx flush=%d copy_buffer=%u/%u copy_texture=%u/%u " - "texture_path=%s cpu_after_gpu=%u/%u\n", - static_cast(cpu_va), static_cast(buf_gpu), flush_ok, buf_match, - kBufBytes, tex_match, kFootprint, texture_path, reverse_match, kBufBytes); + std::printf("RESULT: cpu_va=0x%llx map=0x%llx buffer_gpu_va=0x%llx flush=%d copy_buffer=%u/%u copy_texture=%u/%u " + "texture_path=%s cpu_after_gpu=%u/%u small_align=%llu upload_100000=%llu\n", + static_cast(cpu_va), static_cast(map_pointer), + static_cast(buf_gpu), flush_ok, buf_match, kBufBytes, tex_match, kFootprint, + texture_path, reverse_match, kBufBytes, static_cast(small_align), + static_cast(odd_size)); std::fflush(stdout); if (have_log) { @@ -526,10 +1032,30 @@ int main() { check(false, "BX_LOG_FILE must be set"); } + if (small_res) small_res->Release(); + if (small_host_res) small_host_res->Release(); + if (small_heap) small_heap->Release(); + if (small_host_heap) small_host_heap->Release(); + if (heap1) heap1->Release(); + if (heap1_host) heap1_host->Release(); + if (heap1_base) heap1_base->Release(); + if (heap1_host_base) heap1_host_base->Release(); + if (align_hook) align_hook->Release(); + if (align_host) align_host->Release(); + if (odd) odd->Release(); + if (odd_host) odd_host->Release(); + if (upload_same) upload_same->Release(); + if (deny_same) deny_same->Release(); + if (upload_host) upload_host->Release(); + if (deny_host) deny_host->Release(); + if (custom_later) custom_later->Release(); + if (custom_a) custom_a->Release(); + if (custom_b) custom_b->Release(); if (readback) readback->Release(); if (placed_tex) placed_tex->Release(); if (placed_buf) placed_buf->Release(); - if (heap) heap->Release(); + if (backing) backing->Release(); + if (host) host->Release(); check(device->Release() == 0, "device proxy leaked references"); if (view) { @@ -539,13 +1065,16 @@ int main() { SIZE_T free_count = 2; XMemFreePhysicalPages(&free_count, pages, 0); } + if (sync.ready) CloseHandle(sync.ready); + if (sync.done) CloseHandle(sync.done); if (g_failures > 0) { std::fprintf(stderr, "FAIL: test_d3d12_placed (%d of %d checks failed)\n", g_failures, g_checks); return 1; } std::printf("PASS: test_d3d12_placed (%d checks passed, buffer %u/%u bytes, texture %u/%u bytes, " - "texture_path=%s, cpu_after_gpu %u/%u)\n", - g_checks, buf_match, kBufBytes, tex_match, kFootprint, texture_path, reverse_match, kBufBytes); + "texture_path=%s, cpu_after_gpu %u/%u, small_align=%llu, upload_100000=%llu)\n", + g_checks, buf_match, kBufBytes, tex_match, kFootprint, texture_path, reverse_match, kBufBytes, + static_cast(small_align), static_cast(odd_size)); return 0; }