Compare commits

...
Author SHA1 Message Date
ates c545d15530 d3d12_xs: release a texture copy's upload buffer once the GPU has copied from it (#782)
A texture's upload buffer (as large as the texture) was kept for the life of its copy. It is now released once the copy's fence has passed and made again only when a later check finds the title memory changed.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-12-01 17:49:33 +03:00
ates 714d90baf8 d3d12_xs: release implicit shadows the title has replaced (#782)
CreatePlacedRawShaderResourceViewX / CreatePlacedRawUnorderedAccessViewX
back each view of placed memory with a host resource of the shim's own,
made per (address, shape) and kept for the life of the process. The
target build streams textures and buffers through recycled memory: about
58,000 such resources a minute, an 11 GB footprint after about 140 s.

A new view whose title memory overlaps an older implicit shadow of
another address or shape now retires that shadow: the title reuses
memory only once it no longer uses the old contents. The host resource
is released 64 queue submissions later, as a margin for host work in
flight; its texture-contents copy is retired through its own fence;
translated-draw markers of it stop referencing it and resolve to null
views; a constant view whose fallback lay in it falls back to a null
view instead. Releases are logged as `implicit_shadows` when the total
passes a power of two.

test_d3d12_placed_implicit_release views four slots 256 times with new
shapes: 256 resources made, at most 4 live, at least 128 released, and a
view with the live shadow's address and shape reuses it.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-12-01 17:30:13 +03:00
ates d18c2d514a d3d12_xs: claim #782 (host resources for placed raw views are never released)
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-12-01 17:21:41 +03:00
8 changed files with 482 additions and 27 deletions

No files matched your search

+1
View File
@@ -10,6 +10,7 @@ Guest execution uses original, purpose-built test programs. Commercial Xbox game
remains unsupported.
### Fixed
- **`d3d12_xs.dll`: host resources made for views of placed memory are released once the title places something else there** (#782). `CreatePlacedRawShaderResourceViewX` and `CreatePlacedRawUnorderedAccessViewX` back each view with a host resource of the shim's own (an implicit shadow), made per (address, shape) and kept for the life of the process. The target build streams textures and buffers through recycled memory: about 58,000 such resources a minute, and a physical footprint of 11 GB after about 140 s on a 16 GB Mac (#782). A new view whose title memory overlaps an older implicit shadow of another address or shape now retires that shadow. The title only reuses memory once it no longer uses the old contents, and the host resource is released 64 queue submissions later as a margin. Its texture-contents copy (#745) is retired through its own fence. Translated-draw markers of it stop referencing it and resolve to null views, and a constant view's fallback that lay in it is dropped. `test_d3d12_placed_implicit_release` views four slots of memory 256 times with new shapes and checks that at most one host resource per slot stays live and that the rest are released.
- **`d3d12_xs`: translated pipelines bind input elements to the vertex shader by semantic.** The host input layout took the title's elements in their layout order as `ATTR0`, `ATTR1`, …, while the translated vertex shader reads input register r as `ATTR<r>` and the console shader's input signature (ISG1/ISGN) gives each register its semantic. Direct3D 12 links elements to shader inputs by semantic name and index, not by order, so a layout listing its elements in another order than the signature fed the wrong data to the shader (for example colour in place of texture coordinates). Each input register now gets the element whose semantic the signature names; a container without a signature keeps layout order, and a missing element is logged as the reason the pipeline is not drawn. New test `test_d3d12_console_input_semantics`.
- **`d3d12_xs`: a buffer view made with `CreatePlacedRawShaderResourceViewX` reaches translated draws as a constant buffer.** The view wrote nothing into the title's 32-byte descriptor, so a title that copies it into a draw's table with plain stores copied zeros, and a console shader that reads it with scalar buffer loads (a constant buffer) read zeros. The view now leaves a marker of a constant view of its title memory, and translated draws get the buffer's current contents. New test `test_d3d12_console_raw_buffer_constants`.
- **`gfx10-translate`: scan all `XBCH` candidates and support version 2/3 payloads** (#721). `container_code` previously stopped at the first `b"XBCH"` byte sequence in a container, so incidental `b"XBCH"` bytes earlier in the blob (for example in `STAT` or `DXIL` bitcode) caused it to read garbage sizes and fail with `XBCH record: compressed size past the end`. It now scans all `b"XBCH"` occurrences, validates the 24-byte header, bounds, version (`2` uncompressed `FSSM`, `1` and `3` zlib-compressed `FSSM`), and `FSSM` magic, and skips non-matching candidates. Covered by synthetic unit tests in `gfx10_translate::container::tests`.
+52 -9
View File
@@ -24,8 +24,9 @@
* known here): a title that reads its descriptors back, rather than only copying them, would
* see it. Entries without a marker are left as the host heap has them and are logged.
*
* Limits, logged when met: a registered texture is kept referenced for the life of the process;
* a table changed between a draw and the submission of its list is read at submission.
* Limits, logged when met: a registered texture is kept referenced until the shim releases it
* (placed_x.cpp releases implicit shadows the title has replaced; their markers then resolve to null
* views); a table changed between a draw and the submission of its list is read at submission.
*/
#include "console_pipelines.h"
@@ -76,15 +77,21 @@ struct View {
std::mutex g_view_lock;
std::vector<View> g_views(1); // id 0 is never used
std::vector<std::string> g_view_keys(1);
std::unordered_map<std::string, uint32_t> g_view_ids;
std::unordered_map<const ID3D12Resource*, std::vector<uint32_t>> g_views_of; // resource -> ids of its views
uint32_t intern(const std::string& key, const View& view) {
/* `owner`: the resource the view depends on, when the shim may release it early; an SRV's own
resource otherwise. */
uint32_t intern(const std::string& key, const View& view, ID3D12Resource* owner = nullptr) {
std::lock_guard<std::mutex> guard(g_view_lock);
auto it = g_view_ids.find(key);
if (it != g_view_ids.end()) return it->second;
const uint32_t id = static_cast<uint32_t>(g_views.size());
g_views.push_back(view);
g_view_keys.push_back(key);
if (view.resource) view.resource->AddRef();
if (const ID3D12Resource* index = owner ? owner : view.resource) g_views_of[index].push_back(id);
g_view_ids.emplace(key, id);
return id;
}
@@ -161,21 +168,28 @@ void resolve(ID3D12Device* device, const char* key, const BxConsoleUse& use, uin
std::lock_guard<std::mutex> guard(g_view_lock);
ok = words[1] != 0 && words[1] < g_views.size();
if (ok) view = g_views[words[1]];
// Held for this resolve: bx_console_forget_resource may drop the registry's reference.
if (ok && view.resource) view.resource->AddRef();
}
const D3D12_CPU_DESCRIPTOR_HANDLE host = bx_xbox_host_cpu_handle({static_cast<SIZE_T>(entry)});
uint64_t total = 0;
// A view whose resource the shim has released (an implicit shadow the title replaced) resolves
// to a null view: never to memory that is gone.
const bool released = ok && view.texture && !view.resource;
if (ok && !use.texture && !view.texture) {
D3D12_CONSTANT_BUFFER_VIEW_DESC copy{};
// Fresh bytes from title memory when it can be read; otherwise the view as created.
// Fresh bytes from title memory when it can be read; otherwise the view as created, or a
// null view when the buffer behind it has been released.
if (constant_copy(device, view.title_va, view.cbv.SizeInBytes, &copy)) {
device->CreateConstantBufferView(&copy, host);
} else {
device->CreateConstantBufferView(&view.cbv, host);
device->CreateConstantBufferView(view.cbv.BufferLocation ? &view.cbv : nullptr, host);
}
++g_resolved;
} else if (ok && use.texture && view.texture) {
} else if (ok && use.texture && view.texture && !(released && !view.has_srv_desc)) {
// A texture placed in title memory is read through a copy of its contents (#745).
device->CreateShaderResourceView(bx_xbox_texture_contents(view.resource, uploads), view.has_srv_desc ? &view.srv : nullptr, host);
ID3D12Resource* contents = released ? nullptr : bx_xbox_texture_contents(view.resource, uploads);
device->CreateShaderResourceView(contents, view.has_srv_desc ? &view.srv : nullptr, host);
++g_resolved;
} else if (sampled(g_unmarked, &total)) {
log(BX_LOG_WARN, "console_descriptor",
@@ -185,11 +199,13 @@ void resolve(ID3D12Device* device, const char* key, const BxConsoleUse& use, uin
ok ? "a view of the other kind" : "no view this layer created", words[0], words[1], words[2], words[3],
static_cast<unsigned long long>(total), static_cast<unsigned long long>(g_resolved.load()));
}
if (ok && view.resource) view.resource->Release();
}
} // namespace
void bx_console_mark_cbv(uint64_t title_handle, uint64_t title_va, const D3D12_CONSTANT_BUFFER_VIEW_DESC& host_desc) {
void bx_console_mark_cbv_of(uint64_t title_handle, uint64_t title_va, const D3D12_CONSTANT_BUFFER_VIEW_DESC& host_desc,
ID3D12Resource* owner) {
if (!bx_console_shaders_enabled() || !title_handle) return;
View view;
view.cbv = host_desc;
@@ -197,7 +213,34 @@ void bx_console_mark_cbv(uint64_t title_handle, uint64_t title_va, const D3D12_C
char key[80];
std::snprintf(key, sizeof(key), "c%llx:%llx:%u", static_cast<unsigned long long>(title_va),
static_cast<unsigned long long>(host_desc.BufferLocation), host_desc.SizeInBytes);
write_marker(title_handle, intern(key, view));
write_marker(title_handle, intern(key, view, owner));
}
void bx_console_mark_cbv(uint64_t title_handle, uint64_t title_va, const D3D12_CONSTANT_BUFFER_VIEW_DESC& host_desc) {
bx_console_mark_cbv_of(title_handle, title_va, host_desc, nullptr);
}
void bx_console_forget_resource(ID3D12Resource* resource) {
if (!resource) return;
std::vector<ID3D12Resource*> references;
{
std::lock_guard<std::mutex> guard(g_view_lock);
auto it = g_views_of.find(resource);
if (it == g_views_of.end()) return;
for (const uint32_t id : it->second) {
View& v = g_views[id];
if (v.resource == resource) {
references.push_back(resource);
v.resource = nullptr;
}
if (!v.texture) v.cbv.BufferLocation = 0; // the fallback lay in the released buffer
// A new view made later with the same description gets a new id.
auto key = g_view_ids.find(g_view_keys[id]);
if (key != g_view_ids.end() && key->second == id) g_view_ids.erase(key);
}
g_views_of.erase(it);
}
for (ID3D12Resource* r : references) r->Release();
}
void bx_console_mark_srv(uint64_t title_handle, ID3D12Resource* host, const D3D12_SHADER_RESOURCE_VIEW_DESC* host_desc) {
+7
View File
@@ -60,7 +60,14 @@ bool bx_console_pipeline_info(BxConsolePipeline* pipeline, ID3D12Device** device
/* console_descriptors.cpp: descriptors the title copies itself. `title_handle` is the title's
descriptor handle (an address in its descriptor memory). */
void bx_console_mark_cbv(uint64_t title_handle, uint64_t title_va, const D3D12_CONSTANT_BUFFER_VIEW_DESC& host_desc);
/* As bx_console_mark_cbv, for a constant view whose host fallback lies in `owner`, a resource the
shim may release early (bx_console_forget_resource). */
void bx_console_mark_cbv_of(uint64_t title_handle, uint64_t title_va, const D3D12_CONSTANT_BUFFER_VIEW_DESC& host_desc,
ID3D12Resource* owner);
void bx_console_mark_srv(uint64_t title_handle, ID3D12Resource* host, const D3D12_SHADER_RESOURCE_VIEW_DESC* host_desc);
/* The shim is releasing `resource` (placed_x.cpp, implicit shadows): views marked with it stop
referencing it. A marker of such a view resolves to a null view from then on. */
void bx_console_forget_resource(ID3D12Resource* resource);
/* Direct3D copied `count` descriptors between title handles: the title-side bytes follow. */
void bx_console_copy_title(uint64_t dest, uint64_t src, UINT count);
void bx_console_note_table(ID3D12GraphicsCommandList* list, UINT param, uint64_t title_handle);
+1
View File
@@ -147,6 +147,7 @@ void execute(void* self, UINT count, ID3D12CommandList* const* lists) {
auto* queue = bx_xbox_host<ID3D12CommandQueue>(self);
BxXboxUnwrapArray<ID3D12CommandList> host(lists, count);
if (!host.ok()) return;
bx_xbox_placed_note_submission(); // releases implicit shadows replaced long enough ago (#782)
std::vector<Write> pending;
{
std::lock_guard<std::mutex> guard(g_lock);
+184 -18
View File
@@ -43,6 +43,8 @@ struct Shadow {
D3D12_RESOURCE_DESC desc;
ULONGLONG title_attributes; // non-zero: title_va came from XMemAlloc and is freed with the resource
int mapped = 0; // outstanding Map calls on title memory (buffers)
bool implicit = false; // made for a view of placed memory (implicit_shadow); owned by this table
uint64_t span = 0; // implicit: the bytes of title memory the resource covers
};
// Copies between a buffer's title memory and its host resource, when the host is CPU-mappable.
@@ -165,17 +167,63 @@ bool same_shape(const D3D12_RESOURCE_DESC& a, const D3D12_RESOURCE_DESC& b) {
a.DepthOrArraySize == b.DepthOrArraySize && a.MipLevels == b.MipLevels && a.Format == b.Format;
}
// A view of placed memory with no resource object: reuse the shadow made for the same address
// and shape, or make one. These shadows live for the rest of the process (logged).
// The bytes of title memory a placed resource of `desc` covers: XG's size for console layouts,
// 256-byte rows for the linear layout, packed elements otherwise. At least 1.
uint64_t title_span(const D3D12_RESOURCE_DESC& desc) {
if (desc.Dimension == D3D12_RESOURCE_DIMENSION_BUFFER) return desc.Width ? desc.Width : 1;
uint64_t size = 0, alignment = 0;
if (static_cast<UINT>(desc.Layout) > 0x100 && bx_gdk_xg_layout_size(desc, &size, &alignment) && size) return size;
bool block = false;
const UINT element = bx_texture_element_bytes(desc.Format, &block);
const uint64_t width = block ? (desc.Width + 3) / 4 : desc.Width;
const uint64_t height = block ? (desc.Height + 3) / 4 : desc.Height;
uint64_t row = width * (element ? element : 4);
if (static_cast<UINT>(desc.Layout) == 0x100) row = (row + 255) / 256 * 256;
size = row * (height ? height : 1) * (desc.DepthOrArraySize ? desc.DepthOrArraySize : 1);
return size ? size : 1;
}
// Implicit shadows the title has replaced, released once enough submissions have passed.
void retire_implicit(const std::vector<ID3D12Resource*>& hosts);
/*
* A view of placed memory with no resource object: reuse the shadow made for the same address
* and shape, or make one (#782). A title streams textures and buffers through recycled memory, so
* a new view whose title range overlaps an older implicit shadow of another address or shape means
* the title has placed something else there and no longer uses the old one: that shadow is retired
* and released later (retire_implicit). Without this, every (address, shape) a title ever viewed kept
* a host resource for the life of the process.
*/
ID3D12Resource* implicit_shadow(ID3D12Device* device, uint64_t title_va, const D3D12_RESOURCE_DESC& desc) {
const uint64_t span = title_span(desc);
std::vector<ID3D12Resource*> replaced;
{
std::lock_guard<std::mutex> guard(g_lock);
for (size_t i = 0; i < g_count; ++i) {
if (g_shadows[i].title_va == title_va && same_shape(g_shadows[i].desc, desc)) return g_shadows[i].host;
}
for (size_t i = 0; i < g_count;) {
const Shadow& s = g_shadows[i];
if (s.implicit && title_va < s.title_va + s.span && s.title_va < title_va + span) {
replaced.push_back(s.host);
g_shadows[i] = g_shadows[--g_count];
} else {
++i;
}
}
}
if (!replaced.empty()) retire_implicit(replaced);
ID3D12Resource* resource = nullptr;
return SUCCEEDED(make_shadow(device, title_va, desc, "implicit shadow for a placed view", &resource)) ? resource : nullptr;
if (FAILED(make_shadow(device, title_va, desc, "implicit shadow for a placed view", &resource))) return nullptr;
std::lock_guard<std::mutex> guard(g_lock);
for (size_t i = g_count; i-- > 0;) {
if (g_shadows[i].host == resource) {
g_shadows[i].implicit = true;
g_shadows[i].span = span;
break;
}
}
return resource;
}
// The Xbox view descriptions start with the PC description's 40 bytes; ResourceLocation follows.
@@ -234,6 +282,7 @@ struct TextureCopy {
uint64_t sample = 0; // the sample hash the copy was made from
ID3D12Fence* fence = nullptr; // the upload list's fence and the value after the last copy
uint64_t fence_value = 0;
uint64_t upload_bytes = 0; // the upload buffer's size; the buffer exists only while needed
};
std::mutex g_texture_lock;
std::unordered_map<const void*, TextureCopy> g_texture_copies; // host texture -> its copy
@@ -276,6 +325,41 @@ void note_texture_skipped(const D3D12_RESOURCE_DESC& desc, const char* why) {
bx_log_emit(BX_LOG_WARN, "d3d12_xs", "texture_contents", detail);
}
/* The upload buffer of `t` (t.upload_bytes, persistently mapped at t.mapped), made when a copy is
about to be written. Released again once the GPU has copied from it (#782): a texture whose title
memory never changes keeps only its copy. */
HRESULT make_upload(ID3D12Device* device, TextureCopy& t) {
D3D12_HEAP_PROPERTIES heap{};
heap.Type = D3D12_HEAP_TYPE_UPLOAD;
D3D12_RESOURCE_DESC buffer{};
buffer.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER;
buffer.Width = t.upload_bytes;
buffer.Height = 1;
buffer.DepthOrArraySize = 1;
buffer.MipLevels = 1;
buffer.SampleDesc.Count = 1;
buffer.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;
HRESULT hr = t.upload_bytes ? device->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &buffer, D3D12_RESOURCE_STATE_GENERIC_READ,
nullptr, __uuidof(ID3D12Resource), reinterpret_cast<void**>(&t.upload))
: E_INVALIDARG;
if (SUCCEEDED(hr) && t.upload) hr = t.upload->Map(0, nullptr, reinterpret_cast<void**>(&t.mapped));
if (FAILED(hr) || !t.mapped) {
if (t.upload) t.upload->Release();
t.upload = nullptr;
t.mapped = nullptr;
return FAILED(hr) ? hr : E_FAIL;
}
return S_OK;
}
HRESULT make_upload(ID3D12Resource* owner, TextureCopy& t) {
ID3D12Device* device = nullptr;
if (!owner || FAILED(owner->GetDevice(__uuidof(ID3D12Device), reinterpret_cast<void**>(&device))) || !device) return E_FAIL;
const HRESULT hr = make_upload(device, t);
device->Release();
return hr;
}
/* A default-heap copy of `host`'s description and an upload buffer for all its subresources. */
bool make_texture_copy(ID3D12Resource* host, TextureCopy& t) {
ID3D12Device* device = nullptr;
@@ -287,24 +371,12 @@ bool make_texture_copy(ID3D12Resource* host, TextureCopy& t) {
std::vector<UINT64> row_bytes(subresources);
UINT64 total = 0;
device->GetCopyableFootprints(&desc, 0, subresources, 0, t.footprints.data(), t.rows.data(), row_bytes.data(), &total);
t.upload_bytes = total;
D3D12_HEAP_PROPERTIES heap{};
heap.Type = D3D12_HEAP_TYPE_DEFAULT;
HRESULT hr = device->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_ALL_SHADER_RESOURCE, nullptr,
__uuidof(ID3D12Resource), reinterpret_cast<void**>(&t.copy));
D3D12_RESOURCE_DESC buffer{};
buffer.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER;
buffer.Width = total;
buffer.Height = 1;
buffer.DepthOrArraySize = 1;
buffer.MipLevels = 1;
buffer.SampleDesc.Count = 1;
buffer.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;
heap.Type = D3D12_HEAP_TYPE_UPLOAD;
if (SUCCEEDED(hr) && total) {
hr = device->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &buffer, D3D12_RESOURCE_STATE_GENERIC_READ, nullptr,
__uuidof(ID3D12Resource), reinterpret_cast<void**>(&t.upload));
}
if (SUCCEEDED(hr) && t.upload) hr = t.upload->Map(0, nullptr, reinterpret_cast<void**>(&t.mapped));
if (SUCCEEDED(hr) && total) hr = make_upload(device, t);
device->Release();
if (FAILED(hr) || !total || !t.mapped) {
bx_xbox_log_host_failure("XboxResource", "CreateCommittedResource(texture contents copy)", FAILED(hr) ? hr : E_FAIL);
@@ -348,6 +420,85 @@ void sweep_retired_locked() {
}
}
/*
* Implicit shadows the title replaced (#782). The title reuses memory only once its own GPU work on
* the old contents is done, so the host resource is no longer needed by the title; it is still
* released only kReleaseAfter queue submissions later, as a margin for host work in flight. Its
* texture-contents copy is retired through the copy's own fence (retire_locked), and translated-draw
* markers of it stop referencing it (bx_console_forget_resource) and resolve to null views.
*/
constexpr uint64_t kReleaseAfter = 64; // queue submissions
struct RetiredShadow {
ID3D12Resource* host;
uint64_t submission;
};
std::mutex g_implicit_lock;
std::vector<RetiredShadow> g_implicit_retired; // under g_implicit_lock
std::atomic<uint64_t> g_submissions{0};
std::atomic<uint64_t> g_implicit_retired_total{0};
std::atomic<uint64_t> g_implicit_released_total{0};
void retire_implicit(const std::vector<ID3D12Resource*>& hosts) {
{
std::lock_guard<std::mutex> guard(g_texture_lock);
for (ID3D12Resource* host : hosts) {
auto copy = g_texture_copies.find(host);
if (copy != g_texture_copies.end()) {
retire_locked(copy->second);
g_texture_copies.erase(copy);
}
}
}
const uint64_t now = g_submissions.load();
std::lock_guard<std::mutex> guard(g_implicit_lock);
for (ID3D12Resource* host : hosts) g_implicit_retired.push_back({host, now});
g_implicit_retired_total += hosts.size();
}
void sweep_implicit() {
const uint64_t now = g_submissions.load();
std::vector<ID3D12Resource*> release;
size_t pending = 0;
{
std::lock_guard<std::mutex> guard(g_implicit_lock);
for (size_t i = 0; i < g_implicit_retired.size();) {
if (g_implicit_retired[i].submission + kReleaseAfter <= now) {
release.push_back(g_implicit_retired[i].host);
g_implicit_retired[i] = g_implicit_retired.back();
g_implicit_retired.pop_back();
} else {
++i;
}
}
pending = g_implicit_retired.size();
}
if (release.empty()) return;
for (ID3D12Resource* host : release) {
bx_console_forget_resource(host);
host->Release();
}
const uint64_t before = g_implicit_released_total.fetch_add(release.size());
const uint64_t after = before + release.size();
// Logged at the first release and whenever the total passes a power of two.
auto bits = [](uint64_t v) {
int n = 0;
for (; v; v >>= 1) ++n;
return n;
};
if (before == 0 || bits(after) > bits(before)) {
size_t live = 0;
{
std::lock_guard<std::mutex> guard(g_lock);
for (size_t i = 0; i < g_count; ++i) live += g_shadows[i].implicit ? 1 : 0;
}
char detail[160];
std::snprintf(detail, sizeof(detail), "live=%zu retired=%llu released=%llu pending=%zu", live,
static_cast<unsigned long long>(g_implicit_retired_total.load()), static_cast<unsigned long long>(after),
pending);
bx_log_emit(BX_LOG_INFO, "d3d12_xs", "implicit_shadows", detail);
}
}
} // namespace
extern "C" {
@@ -396,7 +547,8 @@ void STDMETHODCALLTYPE bx_xbox_device_create_placed_raw_srv_x(void* self, const
D3D12_CONSTANT_BUFFER_VIEW_DESC cbv{};
cbv.BufferLocation = resource->GetGPUVirtualAddress() + offset;
cbv.SizeInBytes = static_cast<UINT>((bytes + 255) & ~255ull);
if (bytes) bx_console_mark_cbv(dest.ptr, view_location(xbox_desc) + offset, cbv);
// The fallback lies in the implicit shadow, which is released if the title replaces it.
if (bytes) bx_console_mark_cbv_of(dest.ptr, view_location(xbox_desc) + offset, cbv, resource);
}
}
@@ -595,6 +747,13 @@ ID3D12Resource* bx_xbox_texture_contents(ID3D12Resource* host, BxTextureUploads*
if (known.filled && now - known.checked_at < known.interval) return known.copy;
// The GPU is still copying from this buffer (from an earlier submission): check later.
if (known.fence && known.fence->GetCompletedValue() < known.fence_value) return known.filled ? known.copy : host;
// The GPU is past the last copy: the upload buffer is not needed until the title memory
// changes, and is made again then (#782).
if (known.filled && known.upload) {
known.upload->Release();
known.upload = nullptr;
known.mapped = nullptr;
}
known.checked_at = now;
// The title memory the texture occupies.
uint64_t bytes = 0;
@@ -620,6 +779,8 @@ ID3D12Resource* bx_xbox_texture_contents(ID3D12Resource* host, BxTextureUploads*
sample = sample_hash(shadow.title_va, bytes);
if (filled && sample == known.sample) {
hr = S_FALSE; // checked, unchanged
} else if (!known.upload && FAILED(hr = make_upload(known.copy, known))) {
// no upload buffer: logged below, the next draw tries again
} else if (kind == TextureKind::Linear) {
const D3D12_PLACED_SUBRESOURCE_FOOTPRINT& fp = known.footprints[0];
const size_t row = static_cast<size_t>(shadow.desc.Width) * element;
@@ -699,6 +860,11 @@ void bx_xbox_note_texture_copy_source(ID3D12Resource* source) {
bx_log_emit(BX_LOG_WARN, "d3d12_xs", "texture_contents", detail);
}
void bx_xbox_placed_note_submission() {
++g_submissions;
sweep_implicit();
}
void bx_xbox_placed_forget(IUnknown* host) {
Shadow gone{};
{
+3
View File
@@ -466,6 +466,9 @@ void STDMETHODCALLTYPE bx_xbox_device_create_placed_uav_x(void* self, ID3D12Reso
D3D12_CPU_DESCRIPTOR_HANDLE dest);
/* Drops the shadow record of a destroyed resource. */
void bx_xbox_placed_forget(IUnknown* host);
/* gpu_writes.cpp, at each ExecuteCommandLists: counts submissions and releases implicit shadows
retired long enough ago (placed_x.cpp). */
void bx_xbox_placed_note_submission();
/* Command-list slots whose structures carry interface pointers, unwrapped before the host call.
The Xbox ResourceBarrier also returns the actions it took; 0 is returned. */
@@ -0,0 +1,6 @@
# Host resources made for views of placed memory (CreatePlacedRawShaderResourceViewX) are released
# once the title places something else in that memory (#782). Needs D3DMetal; reads the shim log
# (BX_LOG_FILE, set by bx-cli run).
add_executable(test_d3d12_placed_implicit_release main.cpp)
target_compile_definitions(test_d3d12_placed_implicit_release PRIVATE WIDL_EXPLICIT_AGGREGATE_RETURNS)
target_link_libraries(test_d3d12_placed_implicit_release PRIVATE d3d12_xs kernel32 uuid)
@@ -0,0 +1,228 @@
/*
* Conformance test: host resources made for views of placed memory are released once the title
* places something else in that memory (#782).
*
* CreatePlacedRawShaderResourceViewX makes a view of title memory at an address from a resource
* description, with no resource object. d3d12_xs backs each such view with a host resource of its
* own (an implicit shadow). A title streams textures through recycled memory, so over a run it
* views thousands of (address, shape) pairs; before #782 every one kept a host resource for the
* life of the process (the target build reached an 11 GB footprint in about 140 s).
*
* The program views four 64 KiB slots of its own memory 256 times, each view with a shape not used
* before, so each view replaces the one before it in that slot. After each view the queue executes
* an empty command list (the shim releases replaced shadows a number of submissions later), then
* 80 more submissions follow. Expected, from the program alone:
* - 256 host resources are made (no (address, shape) repeats);
* - at the end at most 4 are live (one per slot), and at least 128 have been released (the shim
* logs `implicit_shadows ... released=N` when the count passes a power of two);
* - a view with the same address and shape as the live one reuses it: no new host resource.
* Without the release, no `implicit_shadows` line is logged and all 256 stay live.
*
* Slots (Xbox-layout tables, ADR 0009): 2 Release; device 9 CreateCommandAllocator,
* 14 CreateDescriptorHeap, 48 CreateCommandQueueX, 70 CreatePlacedRawShaderResourceViewX,
* 73 CreateCommandListX; descriptor heap 9 GetCPUDescriptorHandleForHeapStart; command list 9 Close;
* queue 10 ExecuteCommandLists.
*/
#include <windows.h>
#include <d3d12.h>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <string>
extern "C" __declspec(dllimport) HRESULT WINAPI D3D12XboxCreateDevice(PVOID adapter, const void* params, REFIID riid,
void** ppv);
namespace {
constexpr int kRelease = 2;
constexpr int kDevCreateCommandAllocator = 9, kDevCreateDescriptorHeap = 14, kDevCreateCommandQueueX = 48;
constexpr int kDevCreatePlacedRawShaderResourceViewX = 70, kDevCreateCommandListX = 73;
constexpr int kHeapGetCpuStart = 9, kListClose = 9, kQueueExecuteCommandLists = 10;
constexpr int kSlots = 4;
constexpr int kViews = 256;
constexpr int kFlush = 80; // submissions after the last view
int g_checks = 0;
int g_failed = 0;
#define CHECK(cond, ...) \
do { \
++g_checks; \
if (!(cond)) { \
++g_failed; \
std::fprintf(stderr, "FAIL: test_d3d12_placed_implicit_release:%d: ", __LINE__); \
std::fprintf(stderr, __VA_ARGS__); \
std::fprintf(stderr, "\n"); \
} \
} while (0)
template <typename Fn>
Fn slot(void* object, int index) {
return reinterpret_cast<Fn>((*static_cast<void* const* const*>(object))[index]);
}
struct QueueDescX {
D3D12_COMMAND_LIST_TYPE Type;
UINT Flags, EngineOrPipeIndex, QueueIndex;
};
struct ListDescX {
D3D12_COMMAND_LIST_TYPE Type;
UINT Flags, NodeMask, ResourceBarrierBatchSize;
};
using ReleaseFn = ULONG(STDMETHODCALLTYPE*)(void*);
using CreateQueueXFn = HRESULT(STDMETHODCALLTYPE*)(void*, const QueueDescX*, REFIID, void**);
using CreateAllocatorFn = HRESULT(STDMETHODCALLTYPE*)(void*, D3D12_COMMAND_LIST_TYPE, REFIID, void**);
using CreateListXFn = HRESULT(STDMETHODCALLTYPE*)(void*, const ListDescX*, void*, void*, REFIID, void**);
using CreateHeapFn = HRESULT(STDMETHODCALLTYPE*)(void*, const D3D12_DESCRIPTOR_HEAP_DESC*, REFIID, void**);
using HeapStartFn = D3D12_CPU_DESCRIPTOR_HANDLE(STDMETHODCALLTYPE*)(void*);
using CreatePlacedRawSrvXFn = void(STDMETHODCALLTYPE*)(void*, const D3D12_RESOURCE_DESC*, const void*, D3D12_CPU_DESCRIPTOR_HANDLE);
using CloseFn = HRESULT(STDMETHODCALLTYPE*)(void*);
using ExecuteFn = void(STDMETHODCALLTYPE*)(void*, UINT, void* const*);
std::string read_log() {
char path[MAX_PATH];
const DWORD n = GetEnvironmentVariableA("BX_LOG_FILE", path, sizeof(path));
if (n == 0 || n >= sizeof(path)) return {};
std::string text;
if (FILE* f = std::fopen(path, "rb")) {
char buffer[4096];
size_t got;
while ((got = std::fread(buffer, 1, sizeof(buffer), f)) > 0) text.append(buffer, got);
std::fclose(f);
}
return text;
}
size_t count_of(const std::string& text, const char* needle) {
size_t n = 0;
for (size_t pos = text.find(needle); pos != std::string::npos; pos = text.find(needle, pos + 1)) ++n;
return n;
}
/* The highest `released=` value among `implicit_shadows` lines, and the `live=` of that line. */
bool last_release_line(const std::string& text, unsigned long long* released, unsigned long long* live) {
bool found = false;
*released = 0;
*live = 0;
for (size_t pos = text.find("\"implicit_shadows\""); pos != std::string::npos; pos = text.find("\"implicit_shadows\"", pos + 1)) {
const size_t l = text.find("live=", pos), r = text.find("released=", pos);
if (l == std::string::npos || r == std::string::npos) continue;
const unsigned long long rel = std::strtoull(text.c_str() + r + 9, nullptr, 10);
if (!found || rel >= *released) {
*released = rel;
*live = std::strtoull(text.c_str() + l + 5, nullptr, 10);
found = true;
}
}
return found;
}
/* View `i`: slot i % 4, a 2D R8G8B8A8 texture in the linear console layout whose width is new for
every view of the slot (16, 20, ... 268 texels by 4 rows: at most 5 KiB of a 64 KiB slot), as a
title streaming different textures through the same memory makes them. */
D3D12_RESOURCE_DESC view_desc(int i) {
D3D12_RESOURCE_DESC d{};
d.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D;
d.Width = 16 + 4 * static_cast<UINT64>(i / kSlots);
d.Height = 4;
d.DepthOrArraySize = 1;
d.MipLevels = 1;
d.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
d.SampleDesc.Count = 1;
d.Layout = static_cast<D3D12_TEXTURE_LAYOUT>(0x100);
return d;
}
} // namespace
int main() {
const std::string before = read_log();
alignas(8) unsigned char title_params[80] = {};
const UINT version = 0x20004; // a non-zero version selects the Xbox-layout device
std::memcpy(title_params, &version, sizeof(version));
void* dev = nullptr;
HRESULT hr = D3D12XboxCreateDevice(nullptr, title_params, __uuidof(ID3D12Device), &dev);
if (hr == E_NOINTERFACE) {
std::printf("SKIP: test_d3d12_placed_implicit_release: host lacks the Xbox-layout device interface (E_NOINTERFACE)\n");
return 77;
}
CHECK(hr == S_OK && dev != nullptr, "Xbox-layout device creation hr=0x%08lx", static_cast<unsigned long>(hr));
if (!dev) return 1;
const QueueDescX qdesc{D3D12_COMMAND_LIST_TYPE_DIRECT, 0, 0, 0};
const ListDescX ldesc{D3D12_COMMAND_LIST_TYPE_DIRECT, 0, 0, 0};
void* queue = nullptr;
void* allocator = nullptr;
void* list = nullptr;
slot<CreateQueueXFn>(dev, kDevCreateCommandQueueX)(dev, &qdesc, __uuidof(ID3D12CommandQueue), &queue);
slot<CreateAllocatorFn>(dev, kDevCreateCommandAllocator)(dev, D3D12_COMMAND_LIST_TYPE_DIRECT, __uuidof(ID3D12CommandAllocator),
&allocator);
slot<CreateListXFn>(dev, kDevCreateCommandListX)(dev, &ldesc, allocator, nullptr, __uuidof(ID3D12GraphicsCommandList), &list);
D3D12_DESCRIPTOR_HEAP_DESC heap_desc{};
heap_desc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV;
heap_desc.NumDescriptors = kSlots;
void* heap = nullptr;
hr = slot<CreateHeapFn>(dev, kDevCreateDescriptorHeap)(dev, &heap_desc, __uuidof(ID3D12DescriptorHeap), &heap);
void* memory = VirtualAlloc(nullptr, kSlots * 64 * 1024, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE);
if (!queue || !allocator || !list || !heap || !memory) {
std::fprintf(stderr, "FAIL: test_d3d12_placed_implicit_release: setup (hr=0x%08lx)\n", static_cast<unsigned long>(hr));
return 1;
}
CHECK(slot<CloseFn>(list, kListClose)(list) == S_OK, "list Close");
const D3D12_CPU_DESCRIPTOR_HANDLE start = slot<HeapStartFn>(heap, kHeapGetCpuStart)(heap);
auto create = slot<CreatePlacedRawSrvXFn>(dev, kDevCreatePlacedRawShaderResourceViewX);
auto execute = slot<ExecuteFn>(queue, kQueueExecuteCommandLists);
void* lists[] = {list};
struct alignas(8) {
D3D12_SHADER_RESOURCE_VIEW_DESC pc;
uint64_t location;
} xbox_srv{};
xbox_srv.pc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
xbox_srv.pc.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D;
xbox_srv.pc.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING;
xbox_srv.pc.Texture2D.MipLevels = 1;
for (int i = 0; i < kViews; ++i) {
const D3D12_RESOURCE_DESC d = view_desc(i);
xbox_srv.location = reinterpret_cast<uint64_t>(memory) + static_cast<uint64_t>(i % kSlots) * 64 * 1024;
create(dev, &d, &xbox_srv, {start.ptr + static_cast<SIZE_T>(i % kSlots) * 32});
execute(queue, 1, lists);
}
for (int i = 0; i < kFlush; ++i) execute(queue, 1, lists);
// The live view of slot 0 again, same address and shape: reused, not made anew.
const std::string mid = read_log();
{
const D3D12_RESOURCE_DESC d = view_desc(kViews - kSlots);
xbox_srv.location = reinterpret_cast<uint64_t>(memory);
create(dev, &d, &xbox_srv, {start.ptr});
}
const std::string log = read_log();
if (!log.empty()) {
const std::string mine = log.substr(before.size() <= log.size() ? before.size() : 0);
const std::string after_mid = log.substr(mid.size() <= log.size() ? mid.size() : 0);
const size_t made = count_of(mine, "implicit shadow for a placed view");
CHECK(made == kViews, "every view of a new shape made a host resource (%zu of %d)", made, kViews);
unsigned long long released = 0, live = 0;
const bool logged = last_release_line(mine, &released, &live);
CHECK(logged, "replaced host resources are released (an implicit_shadows line is logged)");
CHECK(released >= 128, "at least 128 replaced host resources are released (%llu)", released);
CHECK(live <= kSlots, "at most one host resource per slot is live (%llu)", live);
CHECK(count_of(after_mid, "implicit shadow for a placed view") == 0,
"a view with the live shadow's address and shape reuses it (%zu new)", count_of(after_mid, "implicit shadow for a placed view"));
} else {
std::printf("note: no BX_LOG_FILE; the log checks did not run\n");
}
for (void* object : {heap, list, allocator, queue, dev}) slot<ReleaseFn>(object, kRelease)(object);
VirtualFree(memory, 0, MEM_RELEASE);
std::printf("%s: test_d3d12_placed_implicit_release (%d of %d checks passed)\n", g_failed ? "FAIL" : "PASS",
g_checks - g_failed, g_checks);
return g_failed ? 1 : 0;
}